diff --git a/README_en.md b/README_en.md new file mode 100644 index 000000000..1dd705549 --- /dev/null +++ b/README_en.md @@ -0,0 +1,302 @@ +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + +
+

Xiaozhi Backend Server xiaozhi-esp32-server

+
+ +

+This project provides backend services for the open-source smart hardware project +xiaozhi-esp32
+Implemented in Python according to the Xiaozhi Communication Protocol
+Helping you quickly set up your Xiaozhi server +

+ +

+简体中文 +· English +· Changelog +· Deployment Guide +· Report Issues +

+

+ + GitHub Contributors + + + GitHub Contributors + + + Issues + + + GitHub pull requests + + + GitHub pull requests + + + GitHub pull requests + +

+ +--- + +## Target Users 👥 + +This project requires ESP32 hardware devices. If you have purchased ESP32-related hardware, successfully connected to Brother Xia's backend service, and wish to set up your own `xiaozhi-esp32` backend service, then this project is perfect for you. + +Want to see it in action? Check out these videos 🎥 + + + + + + + + + + + + + + + + +
+ + + Xiaozhi esp32 connecting to your own backend model + + + + + + Custom voice + + + + + + Communicating in Cantonese + + + + + + Control home appliances + + + + + + Lowest cost configuration + + +
+ + + Custom voice + + + + + + Play music + + + + + + Weather plugin + + + + + + IOT command control device + + + + + + News broadcast + + +
+ +--- + +## System Requirements and Prerequisites 🖥️ + +- **Computer or Server**: Recommended 4-core CPU, 8GB RAM computer. If using ASR with API, can run on a 2-core CPU, 2GB RAM server. +- **Update Client Interface**: Please update the backend service interface address in the client. + +--- + +## Warning ⚠️ + +1. This is open-source software. This software and any third-party API service providers it interfaces with (including but not limited to speech recognition, large language models, speech synthesis, and other platforms) have no commercial partnership. We do not provide any form of guarantee for their service quality or financial security. +We recommend users prioritize service providers with relevant business licenses and carefully read their service agreements and privacy policies. This software does not host any account keys, does not participate in fund transfers, and does not bear the risk of recharge fund losses. + +2. This project is relatively new and has not yet passed network security testing. Please do not use it in production environments. If you deploy this project for learning purposes in a public network environment, please make sure to enable protection in the `config.yaml` configuration file: + +```yaml +server: + auth: + # Enable protection + enabled: true +``` + +After enabling protection, you need to verify the machine's token or MAC address according to actual circumstances. Please refer to the configuration documentation for details. + +--- + +## Deployment Methods 🚀 + +### I. [Deployment Guide](./docs/Deployment.md) + +This project supports three deployment methods. You can choose based on your actual needs. + +1. [Quick Docker Deployment](./docs/Deployment.md) + +Suitable for regular users who want to quickly experience without much environment configuration. The downside is that pulling the image can be slow. Video tutorial available: [Beautiful expert teaches Docker deployment](https://www.bilibili.com/video/BV1RNQnYDE5t) + +2. [Deploy Using Docker Environment](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2) + +For software engineers who have Docker installed and want to make custom code modifications. + +3. [Local Source Code Run](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C) + +Suitable for users familiar with `Conda` environment or who want to build the running environment from scratch. + +For scenarios requiring higher response speed, we recommend using the local source code run method to reduce additional overhead. Video tutorial available: [Handsome expert teaches source code deployment](https://www.bilibili.com/video/BV1GvQWYZEd2) + +### II. [Firmware Compilation](./docs/firmware-build.md) + +Click here to view the detailed process of [firmware compilation](./docs/firmware-build.md). + +After successful flashing and network connection, wake up Xiaozhi using the wake word and pay attention to the console output on the server side. + +--- + +## Common Questions ❓ + +For issues or product suggestions, please [click here](docs/FAQ.md). + +--- + +## Product Ecosystem 👬 +Xiaozhi is an ecosystem. When using this product, you might want to check out other excellent projects in this ecosystem: + +- [Xiaozhi Android Client](https://github.com/TOM88812/xiaozhi-android-client) + A voice dialogue application based on xiaozhi-server for Android and iOS, supporting real-time voice interaction and text dialogue. Now in Flutter version, supporting both iOS and Android. +- [Xiaozhi PC Client](https://github.com/Huang-junsen/py-xiaozhi) + This project provides a Python-based Xiaobai AI client, allowing you to experience Xiaozhi AI features through code even without physical hardware. Main features include AI voice interaction, visual multimodal recognition, IoT device integration, online music playback, voice wake-up, automatic dialogue mode, graphical interface, command-line mode, cross-platform support, volume control, session management, encrypted audio transmission, automatic verification code processing, etc. +- [Xiaozhi Java Server](https://github.com/joey-zhou/xiaozhi-esp32-server-java) + + The Xiaozhi open-source backend service Java version is a Java-based open-source project that includes both frontend and backend services, aiming to provide users with a complete backend service solution. +--- +## Feature List ✨ + +### Implemented ✅ + +- **Communication Protocol** + Based on `xiaozhi-esp32` protocol, implementing data interaction through WebSocket. +- **Dialogue Interaction** + Supports wake-up dialogue, manual dialogue, and real-time interruption. Automatically sleeps after long periods without dialogue +- **Intent Recognition** + Supports LLM intent recognition and function call, reducing hard-coded intent judgment +- **Multi-language Recognition** + Supports Mandarin, Cantonese, English, Japanese, Korean (default using FunASR). +- **LLM Module** + Supports flexible switching of LLM modules, default using ChatGLMLLM, can also use Alibaba Bailian, DeepSeek, Ollama, and other interfaces. +- **TTS Module** + Supports EdgeTTS (default), Volcano Engine Doubao TTS, and other TTS interfaces to meet speech synthesis needs. +- **Memory Function** + Supports ultra-long memory, local summary memory, and no memory modes to meet different scenario needs. +- **IOT Function** + Supports managing registered device IOT functions, supporting intelligent IoT control based on dialogue context. + +### Under Development 🚧 + +- Multiple mood modes +- Smart control panel webui + +To learn about specific development progress, [click here](https://github.com/users/xinnan-tech/projects/3) + +If you are a software developer, here's an [Open Letter to Developers](docs/contributor_open_letter.md), welcome to join! + +--- + +## Supported Platforms/Components List 📋 + +### LLM Language Models + +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| openai interface call | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini | +| ollama interface call | Ollama | - | +| dify interface call | Dify | - | +| fastgpt interface call | Fastgpt | - | +| coze interface call | Coze | - | + +In fact, any LLM supporting openai interface calls can be integrated. + +--- + +### TTS Speech Synthesis + +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| Interface Call | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS | EdgeTTS, CosyVoiceSiliconflow(partial) | +| Local Service | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | + +--- + +### VAD Voice Activity Detection + +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:---:|:---------:|:----:|:----:|:--:| +| VAD | SileroVAD | Local Use | Free | | + +--- + +### ASR Speech Recognition + +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| Local Use | FunASR, SherpaASR | FunASR, SherpaASR | +| Interface Call | DoubaoASR | - | + +--- + +### Memory Storage + +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:------:|:---------------:|:----:|:---------:|:--:| +| Memory | mem0ai | Interface Call | 1000 times/month quota | | +| Memory | mem_local_short | Local Summary | Free | | + +--- + +### Intent Recognition + +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:------:|:-------------:|:----:|:-------:|:---------------------:| +| Intent | intent_llm | Interface Call | Based on LLM pricing | Intent recognition through large models, highly generalizable | +| Intent | function_call | Interface Call | Based on LLM pricing | Intent completion through large model function calls, fast and effective | + +--- + +## Acknowledgments 🙏 + +- This project was inspired by [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) and implemented based on it. +- Thanks to [Tenclass](https://www.tenclass.com/) for providing detailed documentation support for the Xiaozhi communication protocol. + + + + + + Star History Chart + + \ No newline at end of file diff --git a/docs/images/deploy.png b/docs/images/deploy.png new file mode 100644 index 000000000..e1db8a48b Binary files /dev/null and b/docs/images/deploy.png differ diff --git a/main/.vscode/extensions.json b/main/.vscode/extensions.json new file mode 100644 index 000000000..78227ea83 --- /dev/null +++ b/main/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "github.copilot-chat" + ] +} \ No newline at end of file diff --git a/main/.vscode/settings.json b/main/.vscode/settings.json new file mode 100644 index 000000000..7b016a89f --- /dev/null +++ b/main/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.compile.nullAnalysis.mode": "automatic" +} \ No newline at end of file diff --git a/main/README.md b/main/README.md index a91c9fdca..ba3a499be 100644 --- a/main/README.md +++ b/main/README.md @@ -1,6 +1,8 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3) +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](./FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) # 项目目录介绍 +当你看到这份文件的时候,这个这个项目还没完善好。我们还有很多东西要做。 + 如果你是一名软件开发者,这里有一份[《致开发者的公开信》](../docs/contributor_open_letter.md),欢迎归队! ``` @@ -10,9 +12,9 @@ xiaozhi-esp32-server ├─ manager-api 8002 端口 Java语言开发 负责提供控制台的api ``` -# xiaozhi-server 和ESP32通讯协议 +# xiaozhi-server 接口协议 -https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh +[虾哥团队通信协议:Websocket 连接](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) # manager-web 、manager-api接口协议 diff --git a/main/manager-api/README.md b/main/manager-api/README.md index 484c28dc0..bef06b68e 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,5 +1,4 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3) - +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../../docs/Deployment.md) # 项目介绍 manager-api 该项目基于SpringBoot框架开发。 @@ -13,6 +12,80 @@ MySQL 8.0+ Redis 5.0+ Vue 3.x +# 创建数据库 + +如果本机已经安装了MySQL,可以直接在数据库中创建名为`xiaozhi_esp32_server`的数据库。 + +```sql +CREATE DATABASE xiaozhi_esp32_server CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +``` + +如果还没有MySQL,你可以通过docker安装mysql + +``` +docker run --name xiaozhi-esp32-server-db -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -e MYSQL_DATABASE=xiaozhi_esp32_server -e MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci" -d mysql:latest +``` + +# 确认项目数据库连接信息 + +在`src/main/resources/application-dev.yml`中配置数据库连接信息 + +``` +spring: + datasource: + username: root + password: 123456 +``` + + +# 连接Redis + +如果还没有Redis,你可以通过docker安装redis + +``` +docker run --name xiaozhi-esp32-server-redis -d -p 6379:6379 redis +``` + +# 确认项目Redis连接信息 + +在`src/main/resources/application-dev.yml`中配置Redis连接信息 + +``` +spring: + data: + redis: + host: localhost + port: 6379 + password: + database: 0 +``` + + +# 测试启动 + +本项目为SpringBoot项目,启动方式为: +打开`Application.java`运行`Main`方法启动 + +``` +路径地址: +src/main/java/xiaozhi/AdminApplication.java +``` + +# 打包编译 + +执行以下命令生产jar包 + +``` +mvn clean install +``` + +把jar包放在服务器上,执行 + +``` +nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.activate=dev +``` + + # 接口文档 启动后打开:http://localhost:8002/xiaozhi/doc.html diff --git a/main/manager-api/firmware/070bf471-54d2-47b4-8f6a-dfe73c2a07b6_bootloader.bin b/main/manager-api/firmware/070bf471-54d2-47b4-8f6a-dfe73c2a07b6_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/070bf471-54d2-47b4-8f6a-dfe73c2a07b6_bootloader.bin differ diff --git a/main/manager-api/firmware/201df61b-684a-46fb-bf3a-24df795e0e74_bootloader.elf b/main/manager-api/firmware/201df61b-684a-46fb-bf3a-24df795e0e74_bootloader.elf new file mode 100644 index 000000000..75e467596 Binary files /dev/null and b/main/manager-api/firmware/201df61b-684a-46fb-bf3a-24df795e0e74_bootloader.elf differ diff --git a/main/manager-api/firmware/33c69cb3-fe21-4e85-a854-e726df8979c8_bootloader.bin b/main/manager-api/firmware/33c69cb3-fe21-4e85-a854-e726df8979c8_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/33c69cb3-fe21-4e85-a854-e726df8979c8_bootloader.bin differ diff --git a/main/manager-api/firmware/45d520f8-77b9-441f-8390-b462c21b39ae_bootloader.bin b/main/manager-api/firmware/45d520f8-77b9-441f-8390-b462c21b39ae_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/45d520f8-77b9-441f-8390-b462c21b39ae_bootloader.bin differ diff --git a/main/manager-api/firmware/466e560f-5ec8-4d12-9e6d-9ea139e4f767_bootloader.bin b/main/manager-api/firmware/466e560f-5ec8-4d12-9e6d-9ea139e4f767_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/466e560f-5ec8-4d12-9e6d-9ea139e4f767_bootloader.bin differ diff --git a/main/manager-api/firmware/569f7541-cca4-448b-978e-93bb7f7869cf_bootloader.bin b/main/manager-api/firmware/569f7541-cca4-448b-978e-93bb7f7869cf_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/569f7541-cca4-448b-978e-93bb7f7869cf_bootloader.bin differ diff --git a/main/manager-api/firmware/5fcbc2d9-ab98-4904-be15-31d9c7e4a24d_bootloader.bin b/main/manager-api/firmware/5fcbc2d9-ab98-4904-be15-31d9c7e4a24d_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/5fcbc2d9-ab98-4904-be15-31d9c7e4a24d_bootloader.bin differ diff --git a/main/manager-api/firmware/6149ce45-e14b-4f58-9785-72d2cb4329e7_bootloader.bin b/main/manager-api/firmware/6149ce45-e14b-4f58-9785-72d2cb4329e7_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/6149ce45-e14b-4f58-9785-72d2cb4329e7_bootloader.bin differ diff --git a/main/manager-api/firmware/635205ae-2cf7-4900-abe0-857134fc745d_bootloader.bin b/main/manager-api/firmware/635205ae-2cf7-4900-abe0-857134fc745d_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/635205ae-2cf7-4900-abe0-857134fc745d_bootloader.bin differ diff --git a/main/manager-api/firmware/754b8c2e-e04a-4438-923f-90ccb5a1c93f_bootloader.bin b/main/manager-api/firmware/754b8c2e-e04a-4438-923f-90ccb5a1c93f_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/754b8c2e-e04a-4438-923f-90ccb5a1c93f_bootloader.bin differ diff --git a/main/manager-api/firmware/75b375b8-f349-4c0d-9871-b5fd6ea359e6_bootloader.bin b/main/manager-api/firmware/75b375b8-f349-4c0d-9871-b5fd6ea359e6_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/75b375b8-f349-4c0d-9871-b5fd6ea359e6_bootloader.bin differ diff --git a/main/manager-api/firmware/7787ae88-3def-45f2-b8a1-69e4fab82d6f_bootloader.bin b/main/manager-api/firmware/7787ae88-3def-45f2-b8a1-69e4fab82d6f_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/7787ae88-3def-45f2-b8a1-69e4fab82d6f_bootloader.bin differ diff --git a/main/manager-api/firmware/816ec179-a84c-4ff8-be5e-226bf758d9b7_bootloader.bin b/main/manager-api/firmware/816ec179-a84c-4ff8-be5e-226bf758d9b7_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/816ec179-a84c-4ff8-be5e-226bf758d9b7_bootloader.bin differ diff --git a/main/manager-api/firmware/8e5e3bed-cf35-44b9-9de0-3955db9e4032_bootloader.bin b/main/manager-api/firmware/8e5e3bed-cf35-44b9-9de0-3955db9e4032_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/8e5e3bed-cf35-44b9-9de0-3955db9e4032_bootloader.bin differ diff --git a/main/manager-api/firmware/963e65bd-5dcc-4970-98d9-f4350dce7693_bootloader.bin b/main/manager-api/firmware/963e65bd-5dcc-4970-98d9-f4350dce7693_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/963e65bd-5dcc-4970-98d9-f4350dce7693_bootloader.bin differ diff --git a/main/manager-api/firmware/ae8424be-53fe-4157-9fb4-6abacb024d51_bootloader.bin b/main/manager-api/firmware/ae8424be-53fe-4157-9fb4-6abacb024d51_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/ae8424be-53fe-4157-9fb4-6abacb024d51_bootloader.bin differ diff --git a/main/manager-api/firmware/d8ea28ad-d5aa-401c-9633-b755c7770202_bootloader.elf b/main/manager-api/firmware/d8ea28ad-d5aa-401c-9633-b755c7770202_bootloader.elf new file mode 100644 index 000000000..75e467596 Binary files /dev/null and b/main/manager-api/firmware/d8ea28ad-d5aa-401c-9633-b755c7770202_bootloader.elf differ diff --git a/main/manager-api/firmware/df747842-979e-415c-abde-c7deff8b4537_bootloader.bin b/main/manager-api/firmware/df747842-979e-415c-abde-c7deff8b4537_bootloader.bin new file mode 100644 index 000000000..1681e4fe6 Binary files /dev/null and b/main/manager-api/firmware/df747842-979e-415c-abde-c7deff8b4537_bootloader.bin differ diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml index 9ad380432..a77e15176 100644 --- a/main/manager-api/pom.xml +++ b/main/manager-api/pom.xml @@ -195,6 +195,7 @@ org.projectlombok lombok + 1.18.30 true @@ -232,10 +233,8 @@ org.apache.maven.plugins - maven-surefire-plugin - - true - + maven-clean-plugin + 3.2.0 diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java index 8fb316419..0def65894 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java @@ -71,14 +71,6 @@ public class SwaggerConfig { .build(); } - @Bean - public GroupedOpenApi configApi() { - return GroupedOpenApi.builder() - .group("config") - .pathsToMatch("/config/**") - .build(); - } - @Bean public OpenAPI customOpenAPI() { return new OpenAPI().info(new Info() diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index 1ff70fd46..8daeb25e2 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -84,16 +84,6 @@ public interface Constant { */ String SERVER_SECRET = "server.secret"; - /** - * 是否允许用户注册 - */ - String SERVER_ALLOW_USER_REGISTER = "server.allow_user_register"; - - /** - * 下发六位验证码时显示的控制面板地址 - */ - String SERVER_FRONTED_URL = "server.fronted_url"; - /** * 路径分割符 */ diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java index c59a6a14e..4497a0958 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java @@ -51,8 +51,4 @@ public interface ErrorCode { int PARAM_NUMBER_INVALID = 10037; int PARAM_BOOLEAN_INVALID = 10038; int PARAM_ARRAY_INVALID = 10039; - int PARAM_JSON_INVALID = 10040; - - int OTA_DEVICE_NOT_FOUND = 10041; - int OTA_DEVICE_NEED_BIND = 10042; } diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java index 7bc0c48d1..53aa08dc2 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java @@ -38,14 +38,7 @@ public class RedisKeys { * 模型名称的Key */ public static String getModelNameById(String id) { - return "model:name:" + id; - } - - /** - * 模型配置的Key - */ - public static String getModelConfigById(String id) { - return "model:data:" + id; + return "sys:model:name:" + id; } /** @@ -61,18 +54,4 @@ public class RedisKeys { public static String getAgentDeviceCountById(String id) { return "agent:device:count:" + id; } - - /** - * 获取系统配置缓存key - */ - public static String getServerConfigKey() { - return "server:config"; - } - - /** - * 获取音色详情缓存key - */ - public static String getTimbreDetailsKey(String id) { - return "timbre:details:" + id; - } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/Query.java b/main/manager-api/src/main/java/xiaozhi/common/utils/Query.java new file mode 100644 index 000000000..dae94c61c --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/Query.java @@ -0,0 +1,56 @@ +package xiaozhi.common.utils; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.commons.lang3.StringUtils; + +import java.util.Map; + +/** + * 查询参数 + */ +public class Query { + + public IPage getPage(Map params) { + return getPage(params, null, false); + } + + public IPage getPage(Map params, String defaultOrderField, boolean isAsc) { + // 分页参数 + long curPage = 1; + long limit = 10; + + if (params.get("page") != null) { + curPage = Long.parseLong((String) params.get("page")); + } + if (params.get("limit") != null) { + limit = Long.parseLong((String) params.get("limit")); + } + + // 分页对象 + Page page = new Page<>(curPage, limit); + + // 排序字段 + String orderField = (String) params.get("orderField"); + String order = (String) params.get("order"); + + // 前端字段排序 + if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) { + if ("asc".equalsIgnoreCase(order)) { + return page.addOrder(OrderItem.asc(orderField)); + } else { + return page.addOrder(OrderItem.desc(orderField)); + } + } + + // 默认排序 + if (isAsc) { + page.addOrder(OrderItem.asc(defaultOrderField)); + } else { + page.addOrder(OrderItem.desc(defaultOrderField)); + } + + return page; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 123e10ba7..eea2d7fe4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -191,5 +191,4 @@ public class AgentController { .list(new QueryWrapper().orderByAsc("sort")); return new Result>().ok(list); } - } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java index 4e279c405..197c860eb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java @@ -17,12 +17,4 @@ public interface AgentTemplateService extends IService { * @return 默认模板实体 */ AgentTemplateEntity getDefaultTemplate(); - - /** - * 更新默认模板中的模型ID - * - * @param modelType 模型类型 - * @param modelId 模型ID - */ - void updateDefaultTemplateModelId(String modelType, String modelId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index ff284ef0c..bb2a3ed0f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -44,7 +44,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp @Override public PageData adminAgentList(Map params) { IPage page = agentDao.selectPage( - getPage(params, "agent_name", true), + getPage(params, "sort", true), new QueryWrapper<>()); return new PageData<>(page.getRecords(), page.getTotal()); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java index 9ac3de252..949a2f2d1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java @@ -3,7 +3,6 @@ package xiaozhi.modules.agent.service.impl; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import xiaozhi.modules.agent.dao.AgentTemplateDao; @@ -30,40 +29,4 @@ public class AgentTemplateServiceImpl extends ServiceImpl wrapper = new UpdateWrapper<>(); - switch (modelType) { - case "ASR": - wrapper.set("asr_model_id", modelId); - break; - case "VAD": - wrapper.set("vad_model_id", modelId); - break; - case "LLM": - wrapper.set("llm_model_id", modelId); - break; - case "TTS": - wrapper.set("tts_model_id", modelId); - wrapper.set("tts_voice_id", null); - break; - case "MEMORY": - wrapper.set("mem_model_id", modelId); - break; - case "INTENT": - wrapper.set("intent_model_id", modelId); - break; - } - wrapper.ge("sort", 0); - update(wrapper); - } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java index 30f30b53e..a7f707c98 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java @@ -1,16 +1,23 @@ package xiaozhi.modules.device.controller; +import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; +import java.util.UUID; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; @@ -21,44 +28,224 @@ import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; +import xiaozhi.common.page.PageData; +import xiaozhi.common.utils.Result; import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO; +import xiaozhi.modules.device.entity.OtaEntity; import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.device.service.OtaService; import xiaozhi.modules.device.utils.NetworkUtil; +import xiaozhi.common.constant.Constant; +import io.swagger.v3.oas.annotations.Parameters; +import xiaozhi.common.validator.ValidatorUtils; -@Tag(name = "设备管理", description = "OTA 相关接口") +@Tag(name = "固件管理", description = "OTA固件管理接口") @RestController @RequiredArgsConstructor -@RequestMapping("/ota/") +@RequestMapping("/ota") public class OTAController { + private static final Logger logger = LoggerFactory.getLogger(OTAController.class); private final DeviceService deviceService; + private final OtaService otaService; + + @GetMapping("/otas") + @Operation(summary = "分页查询 OTA 固件信息") + @Parameters({ + @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), + @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true) + }) + public Result> page(@Parameter(hidden = true) @RequestParam Map params) { + ValidatorUtils.validateEntity(params); + PageData page = otaService.page(params); + return new Result>().ok(page); + } + + @GetMapping("{id}") + @Operation(summary = "信息 OTA 固件信息") + public Result get(@PathVariable("id") String id) { + OtaEntity data = otaService.getById(id); + return new Result().ok(data); + } + + @PostMapping + @Operation(summary = "保存 OTA 固件信息") + public Result save(@RequestBody OtaEntity entity) { + if (entity == null) { + return new Result().error("固件信息不能为空"); + } + if (StringUtils.isBlank(entity.getFirmwareName())) { + return new Result().error("固件名称不能为空"); + } + if (StringUtils.isBlank(entity.getType())) { + return new Result().error("固件类型不能为空"); + } + if (StringUtils.isBlank(entity.getVersion())) { + return new Result().error("版本号不能为空"); + } + try { + otaService.save(entity); + return new Result(); + } catch (RuntimeException e) { + return new Result().error(e.getMessage()); + } + } + + @PutMapping("/{id}") + @Operation(summary = "修改 OTA 固件信息") + public Result update(@PathVariable("id") String id, @RequestBody OtaEntity entity) { + if (entity == null) { + return new Result<>().error("固件信息不能为空"); + } + entity.setId(id); + try { + otaService.update(entity); + return new Result<>(); + } catch (RuntimeException e) { + return new Result<>().error(e.getMessage()); + } + } + + @DeleteMapping("/{id}") + @Operation(summary = "OTA 删除") + public Result delete(@PathVariable("id") String[] ids) { + if (ids == null || ids.length == 0) { + return new Result().error("删除的固件ID不能为空"); + } + otaService.delete(ids); + return new Result(); + } @Operation(summary = "检查 OTA 版本和设备激活状态") - @PostMapping + @PostMapping("check") public ResponseEntity checkOTAVersion( @RequestBody DeviceReportReqDTO deviceReportReqDTO, @Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId, - @Parameter(name = "Client-Id", description = "客户端标识", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) { - if (StringUtils.isBlank(deviceId)) { + @Parameter(name = "Client-Id", description = "客户端标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Client-Id") String clientId) { + if (StringUtils.isAnyBlank(deviceId, clientId)) { return createResponse(DeviceReportRespDTO.createError("Device ID is required")); } - if (StringUtils.isBlank(clientId)) { - clientId = deviceId; - } String macAddress = deviceReportReqDTO.getMacAddress(); boolean macAddressValid = NetworkUtil.isMacAddressValid(macAddress); // 设备Id和Mac地址应是一致的, 并且必须需要application字段 if (!deviceId.equals(macAddress) || !macAddressValid || deviceReportReqDTO.getApplication() == null) { return createResponse(DeviceReportRespDTO.createError("Invalid OTA request")); } - return createResponse(deviceService.checkDeviceActive(macAddress, clientId, deviceReportReqDTO)); + return createResponse(deviceService.checkDeviceActive(macAddress, deviceId, clientId, deviceReportReqDTO)); } - @GetMapping + @Operation(summary = "获取 OTA 提示信息") + @GetMapping("prompt") public ResponseEntity getOTAPrompt() { return createResponse(DeviceReportRespDTO.createError("请提交正确的ota参数")); } + @GetMapping("/download/{id}") + @Operation(summary = "下载固件文件") + public ResponseEntity downloadFirmware(@PathVariable("id") String id) { + try { + // 获取固件信息 + OtaEntity otaEntity = otaService.getById(id); + if (otaEntity == null || StringUtils.isBlank(otaEntity.getFirmwarePath())) { + logger.warn("Firmware not found or path is empty for ID: {}", id); + return ResponseEntity.notFound().build(); + } + + // 获取文件路径 - 确保路径是绝对路径或正确的相对路径 + String firmwarePath = otaEntity.getFirmwarePath(); + Path path; + + // 检查是否是绝对路径 + if (Paths.get(firmwarePath).isAbsolute()) { + path = Paths.get(firmwarePath); + } else { + // 如果是相对路径,则从当前工作目录解析 + path = Paths.get(System.getProperty("user.dir"), firmwarePath); + } + + logger.info("Attempting to download firmware for ID: {}, DB path: {}, resolved path: {}", + id, firmwarePath, path.toAbsolutePath()); + + if (!Files.exists(path) || !Files.isRegularFile(path)) { + // 尝试直接从firmware目录下查找文件名 + String fileName = new File(firmwarePath).getName(); + Path altPath = Paths.get(System.getProperty("user.dir"), "firmware", fileName); + + logger.info("File not found at primary path, trying alternative path: {}", altPath.toAbsolutePath()); + + if (Files.exists(altPath) && Files.isRegularFile(altPath)) { + path = altPath; + } else { + logger.error("Firmware file not found at either path: {} or {}", + path.toAbsolutePath(), altPath.toAbsolutePath()); + return ResponseEntity.notFound().build(); + } + } + + // 读取文件内容 + byte[] fileContent = Files.readAllBytes(path); + + // 设置响应头 + String originalFilename = otaEntity.getFirmwareName() + "_" + otaEntity.getVersion(); + if (firmwarePath.contains(".")) { + String extension = firmwarePath.substring(firmwarePath.lastIndexOf(".")); + originalFilename += extension; + } + + // 清理文件名,移除不安全字符 + String safeFilename = originalFilename.replaceAll("[^a-zA-Z0-9._-]", "_"); + + logger.info("Providing download for firmware ID: {}, filename: {}, size: {} bytes", + id, safeFilename, fileContent.length); + + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + safeFilename + "\"") + .body(fileContent); + } catch (IOException e) { + logger.error("Error reading firmware file for ID: {}", id, e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } catch (Exception e) { + logger.error("Unexpected error during firmware download for ID: {}", id, e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + @PostMapping("/upload") + @Operation(summary = "上传固件文件") + public Result uploadFirmware(@RequestParam("file") MultipartFile file) { + if (file.isEmpty()) { + return new Result().error("上传文件不能为空"); + } + + try { + // 获取文件名 + String originalFilename = file.getOriginalFilename(); + // 生成唯一的文件名 + String uniqueFileName = UUID.randomUUID().toString() + "_" + originalFilename; + // 设置存储路径 + String uploadDir = "firmware"; + Path uploadPath = Paths.get(uploadDir); + System.out.println(uploadPath); + + // 如果目录不存在,创建目录 + if (!Files.exists(uploadPath)) { + Files.createDirectories(uploadPath); + } + + // 完整的文件路径 + Path filePath = uploadPath.resolve(uniqueFileName); + + // 保存文件 + Files.copy(file.getInputStream(), filePath); + + // 返回文件路径 + return new Result().ok(filePath.toString()); + } catch (IOException e) { + return new Result().error("文件上传失败:" + e.getMessage()); + } + } + @SneakyThrows private ResponseEntity createResponse(DeviceReportRespDTO deviceReportRespDTO) { ObjectMapper objectMapper = new ObjectMapper(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java new file mode 100644 index 000000000..975f69be1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/OtaDao.java @@ -0,0 +1,15 @@ +package xiaozhi.modules.device.dao; + +import org.apache.ibatis.annotations.Mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import xiaozhi.modules.device.entity.OtaEntity; + +/** + * OTA固件管理 + */ +@Mapper +public interface OtaDao extends BaseMapper { + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java new file mode 100644 index 000000000..b93c608bd --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/OtaEntity.java @@ -0,0 +1,61 @@ +package xiaozhi.modules.device.entity; + +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("ai_ota") +@Schema(description = "固件信息") +public class OtaEntity { + + @TableId(type = IdType.ASSIGN_UUID) + @Schema(description = "ID") + private String id; + + @Schema(description = "固件名称") + private String firmwareName; + + @Schema(description = "固件类型") + private String type; + + @Schema(description = "版本号") + private String version; + + @Schema(description = "文件大小(字节)") + private Long size; + + @Schema(description = "备注/说明") + private String remark; + + @Schema(description = "固件路径") + private String firmwarePath; + + @Schema(description = "排序") + private Integer sort; + + @Schema(description = "更新者") + @TableField(fill = FieldFill.UPDATE) + private Long updater; + + @Schema(description = "更新时间") + @TableField(fill = FieldFill.UPDATE) + private Date updateDate; + + @Schema(description = "创建者") + @TableField(fill = FieldFill.INSERT) + private Long creator; + + @Schema(description = "创建时间") + @TableField(fill = FieldFill.INSERT) + private Date createDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index 8bb203cc4..37ff8d490 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -19,7 +19,7 @@ public interface DeviceService { /** * 检查设备是否激活 */ - DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId, + DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId, DeviceReportReqDTO deviceReport); /** @@ -66,20 +66,4 @@ public interface DeviceService { * @return 用户列表分页数据 */ PageData page(DevicePageUserDTO dto); - - /** - * 根据MAC地址获取设备信息 - * - * @param macAddress MAC地址 - * @return 设备信息 - */ - DeviceEntity getDeviceByMacAddress(String macAddress); - - /** - * 根据设备ID获取激活码 - * - * @param deviceId 设备ID - * @return 激活码 - */ - String geCodeByDeviceId(String deviceId); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java new file mode 100644 index 000000000..d3e53e9bb --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/OtaService.java @@ -0,0 +1,20 @@ +package xiaozhi.modules.device.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import xiaozhi.common.page.PageData; +import xiaozhi.modules.device.entity.OtaEntity; + +import java.util.Map; + +/** + * OTA固件管理 + */ +public interface OtaService extends IService { + PageData page(Map params); + + boolean save(OtaEntity entity); + + void update(OtaEntity entity); + + void delete(String[] ids); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 71531c76c..a9797f42c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -9,6 +9,7 @@ import java.util.TimeZone; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -33,7 +34,6 @@ import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.vo.UserShowDeviceListVO; import xiaozhi.modules.security.user.SecurityUser; -import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.service.SysUserUtilService; @Service @@ -49,11 +49,11 @@ public class DeviceServiceImpl extends BaseServiceImpl // 添加构造函数来初始化 deviceMapper public DeviceServiceImpl(DeviceDao deviceDao, SysUserUtilService sysUserUtilService, - SysParamsService sysParamsService, + @Value("${app.fronted-url:http://localhost:8001}") String frontedUrl, RedisTemplate redisTemplate) { this.deviceDao = deviceDao; this.sysUserUtilService = sysUserUtilService; - this.frontedUrl = sysParamsService.getValue(Constant.SERVER_FRONTED_URL, true); + this.frontedUrl = frontedUrl; this.redisTemplate = redisTemplate; } @@ -120,7 +120,7 @@ public class DeviceServiceImpl extends BaseServiceImpl } @Override - public DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId, + public DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId, DeviceReportReqDTO deviceReport) { DeviceReportRespDTO response = new DeviceReportRespDTO(); response.setServer_time(buildServerTime()); @@ -132,12 +132,46 @@ public class DeviceServiceImpl extends BaseServiceImpl firmware.setUrl("http://localhost:8002/xiaozhi/ota/download"); response.setFirmware(firmware); - DeviceEntity deviceById = getDeviceById(macAddress); + DeviceEntity deviceById = getDeviceById(deviceId); if (deviceById != null) { // 如果设备存在,则更新上次连接时间 deviceById.setLastConnectedAt(new Date()); deviceDao.updateById(deviceById); } else { // 如果设备不存在,则生成激活码 - DeviceReportRespDTO.Activation code = buildActivation(macAddress, deviceReport); + String safeDeviceId = deviceId.replace(":", "_").toLowerCase(); + String dataKey = String.format("ota:activation:data:%s", safeDeviceId); + + Map cacheMap = redisTemplate.opsForHash().entries(dataKey); + DeviceReportRespDTO.Activation code = new DeviceReportRespDTO.Activation(); + + if (cacheMap != null && cacheMap.containsKey("activation_code")) { + String cachedCode = (String) cacheMap.get("activation_code"); + code.setCode(cachedCode); + code.setMessage(frontedUrl + "\n" + cachedCode); + } else { + String newCode = RandomUtil.randomNumbers(6); + code.setCode(newCode); + code.setMessage(frontedUrl + "\n" + newCode); + + Map dataMap = new HashMap<>(); + dataMap.put("id", deviceId); + dataMap.put("mac_address", macAddress); + dataMap.put("board", (deviceReport.getChipModelName() != null) ? deviceReport.getChipModelName() + : (deviceReport.getBoard() != null ? deviceReport.getBoard().getType() : "unknown")); + dataMap.put("app_version", (deviceReport.getApplication() != null) + ? deviceReport.getApplication().getVersion() + : null); + dataMap.put("deviceId", deviceId); + dataMap.put("activation_code", newCode); + + // 写入主数据 key + redisTemplate.opsForHash().putAll(dataKey, dataMap); + redisTemplate.expire(dataKey, 24, TimeUnit.HOURS); + + // 写入反查激活码 key + String codeKey = "ota:activation:code:" + newCode; + redisTemplate.opsForValue().set(codeKey, deviceId, 24, TimeUnit.HOURS); + } + response.setActivation(code); } @@ -187,7 +221,7 @@ public class DeviceServiceImpl extends BaseServiceImpl params.put(Constant.PAGE, dto.getPage()); params.put(Constant.LIMIT, dto.getLimit()); IPage page = baseDao.selectPage( - getPage(params, "mac_address", true), + getPage(params, "sort", true), // 定义查询条件 new QueryWrapper() // 必须设备关键词查找 @@ -206,16 +240,6 @@ public class DeviceServiceImpl extends BaseServiceImpl return new PageData<>(list, page.getTotal()); } - @Override - public DeviceEntity getDeviceByMacAddress(String macAddress) { - if (StringUtils.isBlank(macAddress)) { - return null; - } - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("mac_address", macAddress); - return baseDao.selectOne(wrapper); - } - private DeviceReportRespDTO.ServerTime buildServerTime() { DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime(); TimeZone tz = TimeZone.getDefault(); @@ -224,60 +248,4 @@ public class DeviceServiceImpl extends BaseServiceImpl serverTime.setTimezone_offset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000)); return serverTime; } - - @Override - public String geCodeByDeviceId(String deviceId) { - String dataKey = getDeviceCacheKey(deviceId); - - Map cacheMap = redisTemplate.opsForHash().entries(dataKey); - if (cacheMap != null && cacheMap.containsKey("activation_code")) { - String cachedCode = (String) cacheMap.get("activation_code"); - return cachedCode; - } - return null; - } - - private String getDeviceCacheKey(String deviceId) { - String safeDeviceId = deviceId.replace(":", "_").toLowerCase(); - String dataKey = String.format("ota:activation:data:%s", safeDeviceId); - return dataKey; - } - - public DeviceReportRespDTO.Activation buildActivation(String deviceId, DeviceReportReqDTO deviceReport) { - DeviceReportRespDTO.Activation code = new DeviceReportRespDTO.Activation(); - - String cachedCode = geCodeByDeviceId(deviceId); - - if (StringUtils.isNotBlank(cachedCode)) { - code.setCode(cachedCode); - code.setMessage(frontedUrl + "\n" + cachedCode); - } else { - String newCode = RandomUtil.randomNumbers(6); - code.setCode(newCode); - code.setMessage(frontedUrl + "\n" + newCode); - - Map dataMap = new HashMap<>(); - dataMap.put("id", deviceId); - dataMap.put("mac_address", deviceId); - - dataMap.put("board", (deviceReport.getChipModelName() != null) ? deviceReport.getChipModelName() - : (deviceReport.getBoard() != null ? deviceReport.getBoard().getType() : "unknown")); - dataMap.put("app_version", (deviceReport.getApplication() != null) - ? deviceReport.getApplication().getVersion() - : null); - - dataMap.put("deviceId", deviceId); - dataMap.put("activation_code", newCode); - - // 写入主数据 key - String dataKey = getDeviceCacheKey(deviceId); - redisTemplate.opsForHash().putAll(dataKey, dataMap); - redisTemplate.expire(dataKey, 24, TimeUnit.HOURS); - - // 写入反查激活码 key - String codeKey = "ota:activation:code:" + newCode; - redisTemplate.opsForValue().set(codeKey, deviceId, 24, TimeUnit.HOURS); - } - return code; - } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java new file mode 100644 index 000000000..14488dc30 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java @@ -0,0 +1,65 @@ +package xiaozhi.modules.device.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.springframework.stereotype.Service; +import xiaozhi.common.page.PageData; +import xiaozhi.common.utils.Query; +import xiaozhi.modules.device.dao.OtaDao; +import xiaozhi.modules.device.entity.OtaEntity; +import xiaozhi.modules.device.service.OtaService; + +import java.util.Arrays; +import java.util.Map; + +@Service +public class OtaServiceImpl extends ServiceImpl implements OtaService { + + @Override + public PageData page(Map params) { + IPage page = baseMapper.selectPage( + new Query().getPage(params), + new QueryWrapper() + .orderByDesc("create_date") + ); + + return new PageData<>(page.getRecords(), page.getTotal()); + } + + @Override + public void update(OtaEntity entity) { + // 检查是否存在相同名称、类型和版本的固件(排除当前记录) + QueryWrapper queryWrapper = new QueryWrapper() + .eq("firmware_name", entity.getFirmwareName()) + .eq("type", entity.getType()) + .eq("version", entity.getVersion()) + .ne("id", entity.getId()); // 排除当前记录 + + if (baseMapper.selectCount(queryWrapper) > 0) { + throw new RuntimeException("已存在相同名称、类型和版本的固件,请修改后重试"); + } + + baseMapper.updateById(entity); + } + + @Override + public void delete(String[] ids) { + baseMapper.deleteBatchIds(Arrays.asList(ids)); + } + + @Override + public boolean save(OtaEntity entity) { + // 检查是否存在相同名称、类型和版本的固件 + QueryWrapper queryWrapper = new QueryWrapper() + .eq("firmware_name", entity.getFirmwareName()) + .eq("type", entity.getType()) + .eq("version", entity.getVersion()); + + if (baseMapper.selectCount(queryWrapper) > 0) { + throw new RuntimeException("已存在相同名称、类型和版本的固件,请勿重复添加"); + } + + return baseMapper.insert(entity) > 0; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java index 8baff29d6..0ce421572 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java @@ -19,8 +19,6 @@ import lombok.AllArgsConstructor; import xiaozhi.common.page.PageData; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.Result; -import xiaozhi.modules.agent.service.AgentTemplateService; -import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; @@ -40,8 +38,6 @@ public class ModelController { private final ModelProviderService modelProviderService; private final TimbreService timbreService; private final ModelConfigService modelConfigService; - private final ConfigService configService; - private final AgentTemplateService agentTemplateService; @GetMapping("/names") @Operation(summary = "获取所有模型名称") @@ -79,7 +75,6 @@ public class ModelController { @PathVariable String provideCode, @RequestBody ModelConfigBodyDTO modelConfigBodyDTO) { ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO); - configService.getConfig(false); return new Result().ok(modelConfigDTO); } @@ -91,7 +86,6 @@ public class ModelController { @PathVariable String id, @RequestBody ModelConfigBodyDTO modelConfigBodyDTO) { ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO); - configService.getConfig(false); return new Result().ok(modelConfigDTO); } @@ -125,27 +119,6 @@ public class ModelController { return new Result(); } - @PutMapping("/default/{id}") - @Operation(summary = "设置默认模型") - @RequiresPermissions("sys:role:superAdmin") - public Result setDefaultModel(@PathVariable String id) { - ModelConfigEntity entity = modelConfigService.selectById(id); - if (entity == null) { - return new Result().error("模型配置不存在"); - } - // 将其他模型设置为非默认 - modelConfigService.setDefaultModel(entity.getModelType(), 0); - entity.setIsEnabled(1); - entity.setIsDefault(1); - modelConfigService.updateById(entity); - - // 更新模板表中对应的模型ID - agentTemplateService.updateDefaultTemplateModelId(entity.getModelType(), entity.getId()); - - configService.getConfig(false); - return new Result(); - } - @GetMapping("/{modelId}/voices") @Operation(summary = "获取模型音色") @RequiresPermissions("sys:role:normal") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java index 9d15ac6df..b8cc38b1b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java @@ -28,21 +28,4 @@ public interface ModelConfigService extends BaseService { * @return 模型名称 */ String getModelNameById(String id); - - /** - * 根据ID获取模型配置 - * - * @param id 模型ID - * @param isCache 是否缓存 - * @return 模型配置实体 - */ - ModelConfigEntity getModelById(String id, boolean isCache); - - /** - * 设置默认模型 - * - * @param modelType 模型类型 - * @param isDefault 是否默认 - */ - void setDefaultModel(String modelType, int isDefault); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java index 00d484861..de8cbd4f3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java @@ -42,7 +42,6 @@ public class ModelConfigServiceImpl extends BaseServiceImpl entities = modelConfigDao.selectList( new QueryWrapper() .eq("model_type", modelType) - .eq("is_enabled", 1) .like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%") .select("id", "model_name")); return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class); @@ -95,8 +94,6 @@ public class ModelConfigServiceImpl extends BaseServiceImpl() - .eq("model_type", modelType)); - } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index fdcb62b20..e5b89c99f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -76,10 +76,8 @@ public class ShiroConfig { filterMap.put("/favicon.ico", "anon"); filterMap.put("/user/captcha", "anon"); filterMap.put("/user/login", "anon"); - filterMap.put("/user/pub-config", "anon"); filterMap.put("/user/register", "anon"); - filterMap.put("/config/server-base", "anon"); - filterMap.put("/config/agent-models", "anon"); + filterMap.put("/device/register", "anon"); filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java index 68e841394..7db612b5d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java @@ -1,8 +1,6 @@ package xiaozhi.modules.security.controller; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -77,9 +75,6 @@ public class LoginController { @PostMapping("/register") @Operation(summary = "注册") public Result register(@RequestBody LoginDTO login) { - if (!sysUserService.getAllowUserRegister()) { - throw new RenException("当前不允许普通用户注册"); - } // 验证是否正确输入验证码 boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha()); if (!validate) { @@ -116,13 +111,4 @@ public class LoginController { sysUserTokenService.changePassword(userId, passwordDTO); return new Result<>(); } - - @GetMapping("/pub-config") - @Operation(summary = "公共配置") - public Result> pubConfig() { - Map config = new HashMap<>(); - config.put("version", "0.3.6"); - config.put("allowUserRegister", sysUserService.getAllowUserRegister()); - return new Result>().ok(config); - } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/config/SystemInitConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/config/SystemInitConfig.java new file mode 100644 index 000000000..5122367d7 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/config/SystemInitConfig.java @@ -0,0 +1,21 @@ +package xiaozhi.modules.sys.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +import jakarta.annotation.PostConstruct; +import xiaozhi.modules.sys.service.SysParamsService; + +@Configuration +@DependsOn("liquibase") +public class SystemInitConfig { + + @Autowired + private SysParamsService sysParamsService; + + @PostConstruct + public void init() { + sysParamsService.initServerSecret(); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java index 1951333fd..c8f955287 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java @@ -27,7 +27,6 @@ import xiaozhi.common.validator.ValidatorUtils; import xiaozhi.common.validator.group.AddGroup; import xiaozhi.common.validator.group.DefaultGroup; import xiaozhi.common.validator.group.UpdateGroup; -import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.sys.dto.SysParamsDTO; import xiaozhi.modules.sys.service.SysParamsService; @@ -43,7 +42,6 @@ import xiaozhi.modules.sys.service.SysParamsService; @AllArgsConstructor public class SysParamsController { private final SysParamsService sysParamsService; - private final ConfigService configService; @GetMapping("page") @Operation(summary = "分页") @@ -79,7 +77,7 @@ public class SysParamsController { ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class); sysParamsService.save(dto); - configService.getConfig(false); + return new Result(); } @@ -92,7 +90,7 @@ public class SysParamsController { ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class); sysParamsService.update(dto); - configService.getConfig(false); + return new Result(); } @@ -105,7 +103,7 @@ public class SysParamsController { AssertUtils.isArrayEmpty(ids, "id"); sysParamsService.delete(ids); - configService.getConfig(false); + return new Result(); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java index 7a35da321..d5d103afa 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java @@ -65,11 +65,4 @@ public interface SysUserService extends BaseService { * @param userIds 用户ID数组 */ void changeStatus(Integer status, String[] userIds); - - /** - * 获取是否允许用户注册 - * - * @return 是否允许用户注册 - */ - boolean getAllowUserRegister(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java index 15f62816d..85814975a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java @@ -37,7 +37,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl page(Map params) { IPage page = baseDao.selectPage( - getPage(params, null, false), + getPage(params, Constant.CREATE_DATE, false), getWrapper(params)); return getPageData(page, SysParamsDTO.class); @@ -125,13 +125,6 @@ public class SysParamsServiceImpl extends BaseServiceImpl queryWrapper = new QueryWrapper<>(); @@ -208,17 +205,4 @@ public class SysUserServiceImpl extends BaseServiceImpl()); - if (userCount == 0) { - return true; - } - return false; - } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java index eebd55be0..f7ee176d6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java @@ -31,7 +31,7 @@ public interface TimbreService extends BaseService { * @param timbreId 音色表id * @return 音色信息 */ - TimbreDetailsVO get(String timbreId); + TimbreDetailsVO get(Long timbreId); /** * 保存音色信息 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java index 2ed5b1ab0..54e5ec045 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java @@ -47,7 +47,7 @@ public class TimbreServiceImpl extends BaseServiceImpl params.put(Constant.PAGE, dto.getPage()); params.put(Constant.LIMIT, dto.getLimit()); IPage page = baseDao.selectPage( - getPage(params, null, true), + getPage(params, "sort", true), // 定义查询条件 new QueryWrapper() // 必须按照ttsID查找 @@ -59,33 +59,9 @@ public class TimbreServiceImpl extends BaseServiceImpl } @Override - public TimbreDetailsVO get(String timbreId) { - if (StringUtils.isBlank(timbreId)) { - return null; - } - - // 先从Redis获取缓存 - String key = RedisKeys.getTimbreDetailsKey(timbreId); - TimbreDetailsVO cachedDetails = (TimbreDetailsVO) redisUtils.get(key); - if (cachedDetails != null) { - return cachedDetails; - } - - // 如果缓存中没有,则从数据库获取 + public TimbreDetailsVO get(Long timbreId) { TimbreEntity entity = baseDao.selectById(timbreId); - if (entity == null) { - return null; - } - - // 转换为VO对象 - TimbreDetailsVO details = ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class); - - // 存入Redis缓存 - if (details != null) { - redisUtils.set(key, details); - } - - return details; + return ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class); } @Override @@ -103,8 +79,6 @@ public class TimbreServiceImpl extends BaseServiceImpl TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class); timbreEntity.setId(timbreId); baseDao.updateById(timbreEntity); - // 删除缓存 - redisUtils.delete(RedisKeys.getTimbreDetailsKey(timbreId)); } @Override diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index b49b31ca2..50056d4a0 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -12,9 +12,9 @@ spring: druid: #MySQL driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://127.0.0.1:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true + url: jdbc:mysql://127.0.0.1:3308/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true username: root - password: 123456 + password: jky123456 initial-size: 10 max-active: 100 min-idle: 10 diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 3daf48a14..abccb0b55 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -63,4 +63,7 @@ mybatis-plus: configuration-properties: prefix: blobType: BLOB - boolValue: TRUE \ No newline at end of file + boolValue: TRUE + +app: + fronted-url: http://localhost:8001 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202504082210.sql b/main/manager-api/src/main/resources/db/changelog/202504082210.sql new file mode 100644 index 000000000..65858527e --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202504082210.sql @@ -0,0 +1,53 @@ +-- 本文件用于初始化模型配置数据,无需手动执行,在项目启动时会自动执行 +-- ------------------------------------------------------- +-- 初始化模型配置数据 +DELETE FROM `ai_model_config`; + +-- VAD模型配置 +INSERT INTO `ai_model_config` VALUES ('VAD_SileroVAD', 'VAD', 'SileroVAD', '语音活动检测', 1, 1, '{\"type\": \"silero\", \"model_dir\": \"models/snakers4_silero-vad\", \"threshold\": 0.5, \"min_silence_duration_ms\": 700}', NULL, NULL, 0, NULL, NULL, NULL, NULL); + +-- ASR模型配置 +INSERT INTO `ai_model_config` VALUES ('ASR_FunASR', 'ASR', 'FunASR', 'FunASR语音识别', 1, 1, '{\"type\": \"fun_local\", \"model_dir\": \"models/SenseVoiceSmall\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('ASR_SherpaASR', 'ASR', 'SherpaASR', 'Sherpa语音识别', 1, 0, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('ASR_DoubaoASR', 'ASR', 'DoubaoASR', '豆包语音识别', 1, 0, '{\"type\": \"doubao\", \"appid\": \"\", \"access_token\": \"\", \"cluster\": \"volcengine_input_common\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); + +-- LLM模型配置 +INSERT INTO `ai_model_config` VALUES ('LLM_AliLLM', 'LLM', 'AliLLM', '通义千问', 1, 0, '{\"type\": \"openai\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"model_name\": \"qwen-turbo\", \"api_key\": \"\", \"temperature\": 0.7, \"max_tokens\": 500, \"top_p\": 1, \"top_k\": 50, \"frequency_penalty\": 0}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_AliAppLLM', 'LLM', 'AliAppLLM', '通义百炼', 1, 0, '{\"type\": \"AliBL\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"app_id\": \"\", \"api_key\": \"\", \"is_no_prompt\": true, \"ali_memory_id\": false}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_DoubaoLLM', 'LLM', 'DoubaoLLM', '豆包大模型', 1, 0, '{\"type\": \"openai\", \"base_url\": \"https://ark.cn-beijing.volces.com/api/v3\", \"model_name\": \"doubao-pro-32k-functioncall-241028\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_DeepSeekLLM', 'LLM', 'DeepSeekLLM', 'DeepSeek', 1, 0, '{\"type\": \"openai\", \"model_name\": \"deepseek-chat\", \"url\": \"https://api.deepseek.com\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_ChatGLMLLM', 'LLM', 'ChatGLMLLM', '智谱AI', 1, 1, '{\"type\": \"openai\", \"model_name\": \"glm-4-flash\", \"url\": \"https://open.bigmodel.cn/api/paas/v4/\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_OllamaLLM', 'LLM', 'OllamaLLM', 'Ollama本地模型', 1, 0, '{\"type\": \"ollama\", \"model_name\": \"qwen2.5\", \"base_url\": \"http://localhost:11434\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_DifyLLM', 'LLM', 'DifyLLM', 'Dify', 1, 0, '{\"type\": \"dify\", \"base_url\": \"https://api.dify.ai/v1\", \"api_key\": \"\", \"mode\": \"chat-messages\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_GeminiLLM', 'LLM', 'GeminiLLM', '谷歌Gemini', 1, 0, '{\"type\": \"gemini\", \"api_key\": \"\", \"model_name\": \"gemini-2.0-flash\", \"http_proxy\": \"\", \"https_proxy\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_CozeLLM', 'LLM', 'CozeLLM', 'Coze', 1, 0, '{\"type\": \"coze\", \"bot_id\": \"\", \"user_id\": \"\", \"personal_access_token\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_LMStudioLLM', 'LLM', 'LMStudioLLM', 'LM Studio', 1, 0, '{\"type\": \"openai\", \"model_name\": \"deepseek-r1-distill-llama-8b@q4_k_m\", \"url\": \"http://localhost:1234/v1\", \"api_key\": \"lm-studio\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_FastgptLLM', 'LLM', 'FastgptLLM', 'FastGPT', 1, 0, '{\"type\": \"fastgpt\", \"base_url\": \"https://host/api/v1\", \"api_key\": \"fastgpt-xxx\", \"variables\": {\"k\": \"v\", \"k2\": \"v2\"}}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceLLM', 'LLM', 'XinferenceLLM', 'Xinference大模型', 1, 0, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:72b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceSmallLLM', 'LLM', 'XinferenceSmallLLM', 'Xinference小模型', 1, 0, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:3b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); + +-- TTS模型配置 +INSERT INTO `ai_model_config` VALUES ('TTS_EdgeTTS', 'TTS', 'EdgeTTS', 'Edge语音合成', 1, 1, '{\"type\": \"edge\", \"voice\": \"zh-CN-XiaoxiaoNeural\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_DoubaoTTS', 'TTS', 'DoubaoTTS', '豆包语音合成', 1, 0, '{\"type\": \"doubao\", \"api_url\": \"https://openspeech.bytedance.com/api/v1/tts\", \"voice\": \"BV001_streaming\", \"output_dir\": \"tmp/\", \"authorization\": \"Bearer;\", \"appid\": \"\", \"access_token\": \"\", \"cluster\": \"volcano_tts\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_CosyVoiceSiliconflow', 'TTS', 'CosyVoiceSiliconflow', '硅基流动语音合成', 1, 0, '{\"type\": \"siliconflow\", \"model\": \"FunAudioLLM/CosyVoice2-0.5B\", \"voice\": \"FunAudioLLM/CosyVoice2-0.5B:alex\", \"output_dir\": \"tmp/\", \"access_token\": \"\", \"response_format\": \"wav\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_CozeCnTTS', 'TTS', 'CozeCnTTS', 'Coze中文语音合成', 1, 0, '{\"type\": \"cozecn\", \"voice\": \"7426720361733046281\", \"output_dir\": \"tmp/\", \"access_token\": \"\", \"response_format\": \"wav\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_FishSpeech', 'TTS', 'FishSpeech', 'FishSpeech语音合成', 1, 0, '{\"type\": \"fishspeech\", \"output_dir\": \"tmp/\", \"response_format\": \"wav\", \"reference_id\": null, \"reference_audio\": [\"/tmp/test.wav\"], \"reference_text\": [\"你弄来这些吟词宴曲来看,还是这些混话来欺负我。\"], \"normalize\": true, \"max_new_tokens\": 1024, \"chunk_length\": 200, \"top_p\": 0.7, \"repetition_penalty\": 1.2, \"temperature\": 0.7, \"streaming\": false, \"use_memory_cache\": \"on\", \"seed\": null, \"channels\": 1, \"rate\": 44100, \"api_key\": \"\", \"api_url\": \"http://127.0.0.1:8080/v1/tts\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V2', 'TTS', 'GPT_SOVITS_V2', 'GPT-SoVITS V2', 1, 0, '{\"type\": \"gpt_sovits_v2\", \"url\": \"http://127.0.0.1:9880/tts\", \"output_dir\": \"tmp/\", \"text_lang\": \"auto\", \"ref_audio_path\": \"caixukun.wav\", \"prompt_text\": \"\", \"prompt_lang\": \"zh\", \"top_k\": 5, \"top_p\": 1, \"temperature\": 1, \"text_split_method\": \"cut0\", \"batch_size\": 1, \"batch_threshold\": 0.75, \"split_bucket\": true, \"return_fragment\": false, \"speed_factor\": 1.0, \"streaming_mode\": false, \"seed\": -1, \"parallel_infer\": true, \"repetition_penalty\": 1.35, \"aux_ref_audio_paths\": []}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V3', 'TTS', 'GPT_SOVITS_V3', 'GPT-SoVITS V3', 1, 0, '{\"type\": \"gpt_sovits_v3\", \"url\": \"http://127.0.0.1:9880\", \"output_dir\": \"tmp/\", \"text_language\": \"auto\", \"refer_wav_path\": \"caixukun.wav\", \"prompt_language\": \"zh\", \"prompt_text\": \"\", \"top_k\": 15, \"top_p\": 1.0, \"temperature\": 1.0, \"cut_punc\": \"\", \"speed\": 1.0, \"inp_refs\": [], \"sample_steps\": 32, \"if_sr\": false}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_MinimaxTTS', 'TTS', 'MinimaxTTS', 'MiniMax语音合成', 1, 0, '{\"type\": \"minimax\", \"output_dir\": \"tmp/\", \"group_id\": \"\", \"api_key\": \"\", \"model\": \"speech-01-turbo\", \"voice_id\": \"female-shaonv\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_AliyunTTS', 'TTS', 'AliyunTTS', '阿里云语音合成', 1, 0, '{\"type\": \"aliyun\", \"output_dir\": \"tmp/\", \"appkey\": \"\", \"token\": \"\", \"voice\": \"xiaoyun\", \"access_key_id\": \"\", \"access_key_secret\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_TTS302AI', 'TTS', 'TTS302AI', '302AI语音合成', 1, 0, '{\"type\": \"doubao\", \"api_url\": \"https://api.302ai.cn/doubao/tts_hd\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_GizwitsTTS', 'TTS', 'GizwitsTTS', '机智云语音合成', 1, 0, '{\"type\": \"doubao\", \"api_url\": \"https://bytedance.gizwitsapi.com/api/v1/tts\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_ACGNTTS', 'TTS', 'ACGNTTS', 'ACGN语音合成', 1, 0, '{\"type\": \"ttson\", \"token\": \"\", \"voice_id\": 1695, \"speed_factor\": 1, \"pitch_factor\": 0, \"volume_change_dB\": 0, \"to_lang\": \"ZH\", \"url\": \"https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=\", \"format\": \"mp3\", \"output_dir\": \"tmp/\", \"emotion\": 1}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_OpenAITTS', 'TTS', 'OpenAITTS', 'OpenAI语音合成', 1, 0, '{\"type\": \"openai\", \"api_key\": \"\", \"api_url\": \"https://api.openai.com/v1/audio/speech\", \"model\": \"tts-1\", \"voice\": \"onyx\", \"speed\": 1, \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('TTS_CustomTTS', 'TTS', 'CustomTTS', '自定义语音合成', 1, 0, '{\"type\": \"custom\", \"url\": \"http://127.0.0.1:9880/tts\", \"params\": {}, \"headers\": {}, \"format\": \"wav\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); + +-- Memory模型配置 +INSERT INTO `ai_model_config` VALUES ('Memory_mem0ai', 'Memory', 'mem0ai', 'Mem0AI记忆', 1, 0, '{\"type\": \"mem0ai\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('Memory_nomem', 'Memory', 'nomem', '无记忆', 1, 1, '{\"type\": \"nomem\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('Memory_mem_local_short', 'Memory', 'mem_local_short', '本地短期记忆', 1, 0, '{\"type\": \"mem_local_short\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); + +-- Intent模型配置 +INSERT INTO `ai_model_config` VALUES ('Intent_nointent', 'Intent', 'nointent', '无意图识别', 1, 0, '{\"type\": \"nointent\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('Intent_intent_llm', 'Intent', 'intent_llm', 'LLM意图识别', 1, 0, '{\"type\": \"intent_llm\", \"llm\": \"ChatGLMLLM\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL); +INSERT INTO `ai_model_config` VALUES ('Intent_function_call', 'Intent', 'function_call', '函数调用意图识别', 1, 1, '{\"type\": \"function_call\", \"functions\": [\"change_role\", \"get_weather\", \"get_news\", \"play_music\"]}', NULL, NULL, 0, NULL, NULL, NULL, NULL); diff --git a/main/manager-api/src/main/resources/db/changelog/202504092313.sql b/main/manager-api/src/main/resources/db/changelog/202504092313.sql new file mode 100644 index 000000000..da924bdae --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202504092313.sql @@ -0,0 +1,61 @@ +-- 本文件用于初始化系统参数数据,无需手动执行,在项目启动时会自动执行 +-- -------------------------------------------------------- +-- 初始化参数管理配置 +DROP TABLE IF EXISTS sys_params; +-- 参数管理 +create table sys_params +( + id bigint NOT NULL COMMENT 'id', + param_code varchar(100) COMMENT '参数编码', + param_value varchar(2000) COMMENT '参数值', + value_type varchar(20) default 'string' COMMENT '值类型:string-字符串,number-数字,boolean-布尔,array-数组', + param_type tinyint unsigned default 1 COMMENT '类型 0:系统参数 1:非系统参数', + remark varchar(200) COMMENT '备注', + creator bigint COMMENT '创建者', + create_date datetime COMMENT '创建时间', + updater bigint COMMENT '更新者', + update_date datetime COMMENT '更新时间', + primary key (id), + unique key uk_param_code (param_code) +)ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='参数管理'; + +-- 服务器配置 +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (100, 'server.ip', '0.0.0.0', 'string', 1, '服务器监听IP地址'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (101, 'server.port', '8000', 'number', 1, '服务器监听端口'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (102, 'server.secret', 'null', 'string', 1, '服务器密钥'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (201, 'log.log_format', '{time:YYMMDD HH:mm:ss}[{version}_{selected_module}][{extra[tag]}]-{level}-{message}', 'string', 1, '控制台日志格式'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (202, 'log.log_format_file', '{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}', 'string', 1, '文件日志格式'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (203, 'log.log_level', 'INFO', 'string', 1, '日志级别'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (204, 'log.log_dir', 'tmp', 'string', 1, '日志目录'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (205, 'log.log_file', 'server.log', 'string', 1, '日志文件名'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (206, 'log.data_dir', 'data', 'string', 1, '数据目录'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (301, 'delete_audio', 'true', 'boolean', 1, '是否删除使用后的音频文件'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (302, 'close_connection_no_voice_time', '120', 'number', 1, '无语音输入断开连接时间(秒)'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (303, 'tts_timeout', '10', 'number', 1, 'TTS请求超时时间(秒)'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (304, 'enable_wakeup_words_response_cache', 'true', 'boolean', 1, '是否开启唤醒词加速'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (305, 'enable_greeting', 'true', 'boolean', 1, '是否开启开场回复'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (306, 'enable_stop_tts_notify', 'false', 'boolean', 1, '是否开启结束提示音'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (307, 'stop_tts_notify_voice', 'config/assets/tts_notify.mp3', 'string', 1, '结束提示音文件路径'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (308, 'exit_commands', '退出;关闭', 'array', 1, '退出命令列表'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (309, 'xiaozhi', '{ + "type": "hello", + "version": 1, + "transport": "websocket", + "audio_params": { + "format": "opus", + "sample_rate": 16000, + "channels": 1, + "frame_duration": 60 + } +}', 'string', 1, '小智类型'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (310, 'wakeup_words', '你好小智;你好小志;小爱同学;你好小鑫;你好小新;小美同学;小龙小龙;喵喵同学;小滨小滨;小冰小冰', 'array', 1, '唤醒词列表,用于识别唤醒词'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (400, 'plugin.weather.api_key', 'a861d0d5e7bf4ee1a83d9a9e4f96d4da', 'string', 1, '天气插件API密钥'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (401, 'plugin.weather.default_location', '广州', 'string', 1, '天气插件默认城市'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (410, 'plugin.news.default_rss_url', 'https://www.chinanews.com.cn/rss/society.xml', 'string', 1, '新闻插件默认RSS地址'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (411, 'plugin.news.category_urls', '{"society":"https://www.chinanews.com.cn/rss/society.xml","world":"https://www.chinanews.com.cn/rss/world.xml","finance":"https://www.chinanews.com.cn/rss/finance.xml"}', 'string', 1, '新闻插件分类RSS地址'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (421, 'plugin.home_assistant.devices', '客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1;卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1', 'array', 1, 'Home Assistant设备列表'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (422, 'plugin.home_assistant.base_url', 'http://homeassistant.local:8123', 'string', 1, 'Home Assistant服务器地址'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (423, 'plugin.home_assistant.api_key', '你的home assistant api访问令牌', 'string', 1, 'Home Assistant API密钥'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (430, 'plugin.music.music_dir', './music', 'string', 1, '音乐文件存放路径'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (431, 'plugin.music.music_ext', 'mp3;wav;p3', 'array', 1, '音乐文件类型'); +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (432, 'plugin.music.refresh_time', '300', 'number', 1, '音乐列表刷新间隔(秒)'); diff --git a/main/manager-api/src/main/resources/db/changelog/202504180757.sql b/main/manager-api/src/main/resources/db/changelog/202504180757.sql new file mode 100644 index 000000000..46afcb397 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202504180757.sql @@ -0,0 +1,18 @@ +-- 本文件用于初始化模型模版数据,无需手动执行,在项目启动时会自动执行 +-- ------------------------------------------------------- +-- 初始化智能体模板数据 +CREATE TABLE `ai_ota` ( + `id` varchar(32) NOT NULL COMMENT 'ID', + `firmware_name` varchar(100) DEFAULT NULL COMMENT '固件名称', + `type` varchar(50) DEFAULT NULL COMMENT '固件类型', + `version` varchar(50) DEFAULT NULL COMMENT '版本号', + `size` bigint DEFAULT NULL COMMENT '文件大小(字节)', + `remark` varchar(500) DEFAULT NULL COMMENT '备注/说明', + `firmware_path` varchar(255) DEFAULT NULL COMMENT '固件路径', + `sort` int unsigned DEFAULT '0' COMMENT '排序', + `updater` bigint DEFAULT NULL COMMENT '更新者', + `update_date` datetime DEFAULT NULL COMMENT '更新时间', + `creator` bigint DEFAULT NULL COMMENT '创建者', + `create_date` datetime DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='固件信息表'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index a2a322a8b..f0ac310f1 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -23,6 +23,13 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/2025_tts_voive.sql + - changeSet: + id: 202504082210 + author: John + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202504082210.sql - changeSet: id: 202504082211 author: John @@ -30,38 +37,17 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202504082211.sql + - changeSet: + id: 202504092313 + author: John + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202504092313.sql - changeSet: id: 202504092335 author: John changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202504092335.sql - - changeSet: - id: 202504112044 - author: John - changes: - - sqlFile: - encoding: utf8 - path: classpath:db/changelog/202504112044.sql - - changeSet: - id: 202504112058 - author: John - changes: - - sqlFile: - encoding: utf8 - path: classpath:db/changelog/202504112058.sql - - changeSet: - id: 202504151206 - author: John - changes: - - sqlFile: - encoding: utf8 - path: classpath:db/changelog/202504151206.sql - - changeSet: - id: 202504181534 - author: John - changes: - - sqlFile: - encoding: utf8 - path: classpath:db/changelog/202504181534.sql \ No newline at end of file + path: classpath:db/changelog/202504092335.sql \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages.properties b/main/manager-api/src/main/resources/i18n/messages.properties index 5126feb2b..ce6cf61ba 100644 --- a/main/manager-api/src/main/resources/i18n/messages.properties +++ b/main/manager-api/src/main/resources/i18n/messages.properties @@ -40,7 +40,3 @@ 10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false 10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F -10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F - -10041=\u8BBE\u5907\u672A\u627E\u5230 -10042={0} diff --git a/main/manager-api/src/main/resources/i18n/messages_en_US.properties b/main/manager-api/src/main/resources/i18n/messages_en_US.properties index 43781857e..d6c1bc0cb 100644 --- a/main/manager-api/src/main/resources/i18n/messages_en_US.properties +++ b/main/manager-api/src/main/resources/i18n/messages_en_US.properties @@ -39,8 +39,4 @@ 10036=Unsupported parameter type 10037=Parameter value must be a valid number 10038=Parameter value must be true or false -10039=Parameter value must be a valid JSON array format -10040=Parameter value must be a valid JSON format - -10041=Device not found -10042={0} \ No newline at end of file +10039=Parameter value must be a valid JSON array format \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties index 713ab96a2..566ca0c98 100644 --- a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties +++ b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties @@ -39,8 +39,4 @@ 10036=\u4E0D\u652F\u6301\u7684\u53C2\u6570\u7C7B\u578B 10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false -10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F -10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F - -10041=\u8BBE\u5907\u672A\u627E\u5230 -10042={0} \ No newline at end of file +10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties index b5847ec49..a5d81697f 100644 --- a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties +++ b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties @@ -39,8 +39,4 @@ 10036=\u4E0D\u652F\u63F4\u7684\u53C3\u6578\u985E\u578B 10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57 10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false -10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F -10040=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u683C\u5F0F - -10041=\u8A2D\u5099\u672A\u627E\u5230 -10042={0} \ No newline at end of file +10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation.properties b/main/manager-api/src/main/resources/i18n/validation.properties index 652ae2695..dd9b47e8c 100644 --- a/main/manager-api/src/main/resources/i18n/validation.properties +++ b/main/manager-api/src/main/resources/i18n/validation.properties @@ -33,5 +33,3 @@ timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4 timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A -ota.device.not.found=\u8BBE\u5907\u672A\u627E\u5230 -ota.device.need.bind={0} diff --git a/main/manager-api/src/main/resources/i18n/validation_en_US.properties b/main/manager-api/src/main/resources/i18n/validation_en_US.properties index fb6f38283..efb2c296b 100644 --- a/main/manager-api/src/main/resources/i18n/validation_en_US.properties +++ b/main/manager-api/src/main/resources/i18n/validation_en_US.properties @@ -32,5 +32,3 @@ timbre.ttsModelId.require=The TTS model ID of the timbre cannot be empty timbre.ttsVoice.require=The TTS voice of the timbre cannot be empty timbre.voiceDemo.require=The voice demo of the timbre cannot be empty -ota.device.not.found=Device not found -ota.device.need.bind={0} \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties index 1ff8a3bae..ebafda82c 100644 --- a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties +++ b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties @@ -32,5 +32,3 @@ timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u9375\u4E0D\u53EF\u4EE5\u7 timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653E\u5730\u5740\u4E0D\u53EF\u4EE5\u70BA\u7A7A -ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230 -ota.device.need.bind={0} \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties index dd6eab900..4a1aabd26 100644 --- a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties +++ b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties @@ -31,6 +31,3 @@ timbre.remark.require=\u97F3\u8272\u7684\u5907\u6CE8\u4E0D\u53EF\u4EE5\u4E3A\u7A timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A - -ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230 -ota.device.need.bind={0} \ No newline at end of file diff --git a/main/manager-web/src/apis/api.js b/main/manager-web/src/apis/api.js index 63977008a..1b9f0a9ed 100755 --- a/main/manager-web/src/apis/api.js +++ b/main/manager-web/src/apis/api.js @@ -5,6 +5,7 @@ import device from './module/device.js' import model from './module/model.js' import timbre from "./module/timbre.js" import user from './module/user.js' +import ota from './module/ota.js' /** * 接口地址 @@ -31,4 +32,5 @@ export default { device, model, timbre, + ota } diff --git a/main/manager-web/src/apis/module/ota.js b/main/manager-web/src/apis/module/ota.js new file mode 100644 index 000000000..cbb2c2fe1 --- /dev/null +++ b/main/manager-web/src/apis/module/ota.js @@ -0,0 +1,107 @@ +import { getServiceUrl } from '../api'; +import RequestService from '../httpRequest'; + +export default { + // 分页查询OTA固件信息 + getOtaList(params, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/ota/otas`) + .method('GET') + .data(params) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('获取OTA固件列表失败:', err); + RequestService.reAjaxFun(() => { + this.getOtaList(params, callback); + }); + }).send(); + }, + // 获取单个OTA固件信息 + getOtaInfo(id, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/ota/${id}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('获取OTA固件信息失败:', err); + RequestService.reAjaxFun(() => { + this.getOtaInfo(id, callback); + }); + }).send(); + }, + // 保存OTA固件信息 + saveOta(entity, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/ota`) + .method('POST') + .data(entity) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('保存OTA固件信息失败:', err); + RequestService.reAjaxFun(() => { + this.saveOta(entity, callback); + }); + }).send(); + }, + // 更新OTA固件信息 + updateOta(id, entity, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/ota/${id}`) + .method('PUT') + .data(entity) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('更新OTA固件信息失败:', err); + RequestService.reAjaxFun(() => { + this.updateOta(id, entity, callback); + }); + }).send(); + }, + // 删除OTA固件 + deleteOta(id, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/ota/${id}`) + .method('DELETE') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('删除OTA固件失败:', err); + RequestService.reAjaxFun(() => { + this.deleteOta(id, callback); + }); + }).send(); + }, + // 上传固件文件 + uploadFirmware(file, callback) { + const formData = new FormData(); + formData.append('file', file); + RequestService.sendRequest() + .url(`${getServiceUrl()}/ota/upload`) + .method('POST') + .data(formData) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('上传固件文件失败:', err); + RequestService.reAjaxFun(() => { + this.uploadFirmware(file, callback); + }); + }).send(); + } +} \ No newline at end of file diff --git a/main/manager-web/src/assets/header/firmware_update.png b/main/manager-web/src/assets/header/firmware_update.png new file mode 100644 index 000000000..bd3d73964 Binary files /dev/null and b/main/manager-web/src/assets/header/firmware_update.png differ diff --git a/main/manager-web/src/components/FirmwareDialog.vue b/main/manager-web/src/components/FirmwareDialog.vue new file mode 100644 index 000000000..59581b6e3 --- /dev/null +++ b/main/manager-web/src/components/FirmwareDialog.vue @@ -0,0 +1,137 @@ + + + + + \ No newline at end of file diff --git a/main/manager-web/src/components/HeaderBar.vue b/main/manager-web/src/components/HeaderBar.vue index 5ddcee556..8fece0a10 100644 --- a/main/manager-web/src/components/HeaderBar.vue +++ b/main/manager-web/src/components/HeaderBar.vue @@ -32,6 +32,12 @@ :style="{ filter: $route.path === '/params-management' ? 'brightness(0) invert(1)' : 'None' }" /> 参数管理 +
+ + OTA管理 +
@@ -105,6 +111,9 @@ export default { goParamManagement() { this.$router.push('/params-management') }, + goOtaManagement() { + this.$router.push('/ota-management') + }, // 获取用户信息 fetchUserInfo() { userApi.getUserInfo(({ data }) => { diff --git a/main/manager-web/src/router/index.js b/main/manager-web/src/router/index.js index 9a06b07b1..b3f3d859a 100644 --- a/main/manager-web/src/router/index.js +++ b/main/manager-web/src/router/index.js @@ -80,6 +80,17 @@ const routes = [ title: '参数管理' } }, + { + path: '/ota-management', + name: 'OtaManagement', + component: function () { + return import('../views/OtaManagement.vue') + }, + meta: { + requiresAuth: true, + title: 'OTA管理' + } + }, ] const router = new VueRouter({ diff --git a/main/manager-web/src/utils/format.js b/main/manager-web/src/utils/format.js new file mode 100644 index 000000000..97f20f033 --- /dev/null +++ b/main/manager-web/src/utils/format.js @@ -0,0 +1,21 @@ +// 日期格式化函数 +export function formatDate(date) { + if (!date) return ''; + const d = new Date(date); + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + const hour = String(d.getHours()).padStart(2, '0'); + const minute = String(d.getMinutes()).padStart(2, '0'); + const second = String(d.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; +} + +// 文件大小格式化函数 +export function formatFileSize(bytes) { + if (!bytes || bytes === 0) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + const k = 1024; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + units[i]; +} \ No newline at end of file diff --git a/main/manager-web/src/views/OtaManagement.vue b/main/manager-web/src/views/OtaManagement.vue new file mode 100644 index 000000000..845827185 --- /dev/null +++ b/main/manager-web/src/views/OtaManagement.vue @@ -0,0 +1,637 @@ + + + + + diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index 593362b18..ca3ab5453 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -7,7 +7,6 @@ from core.utils.util import check_ffmpeg_installed TAG = __name__ - async def wait_for_exit(): """Windows 和 Linux 兼容的退出监听""" loop = asyncio.get_running_loop() @@ -20,12 +19,10 @@ async def wait_for_exit(): # Linux/macOS: 用 signal 监听 Ctrl + C def stop(): stop_event.set() - loop.add_signal_handler(signal.SIGINT, stop) loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程 await stop_event.wait() - async def main(): check_config_file() check_ffmpeg_installed() @@ -47,7 +44,6 @@ async def main(): pass print("服务器已关闭,程序退出。") - if __name__ == "__main__": try: asyncio.run(main()) diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 0f694fba2..f1ac85c06 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -52,7 +52,7 @@ enable_stop_tts_notify: false # 说完话是否开启提示音,音效地址 stop_tts_notify_voice: "config/assets/tts_notify.mp3" -exit_commands: +CMD_exit: - "退出" - "关闭" @@ -147,7 +147,7 @@ selected_module: Memory: nomem # 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。 # 不想开通意图识别,就设置成:nointent - # 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,这个意图识别暂时不支持控制音量大小等iot操作 + # 意图识别可使用intent_llm,如果你的LLM是DifyLLM或CozeLLM,建议使用这个。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,这个意图识别暂时不支持控制音量大小等iot操作 # 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令 # 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028 Intent: function_call @@ -163,7 +163,7 @@ Intent: type: intent_llm # 配备意图识别独立的思考模型 # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 - # 如果你的不想使用selected_module.LLM意图识别,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM + # 如果你的selected_module.LLM选择了DifyLLM或CozeLLM,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM llm: ChatGLMLLM function_call: # 不需要动type @@ -222,7 +222,6 @@ ASR: output_dir: tmp/ VAD: SileroVAD: - type: silero threshold: 0.5 model_dir: models/snakers4_silero-vad min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些 diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py index 433422886..8647a0099 100644 --- a/main/xiaozhi-server/config/logger.py +++ b/main/xiaozhi-server/config/logger.py @@ -1,34 +1,9 @@ import os import sys from loguru import logger -from config.config_loader import load_config +from config.settings import load_config -SERVER_VERSION = "0.3.6" - - -def get_module_abbreviation(module_name, module_dict): - """获取模块名称的缩写,如果为空则返回00""" - return ( - module_dict.get(module_name, "")[:2] if module_dict.get(module_name) else "00" - ) - - -def build_module_string(selected_module): - """构建模块字符串""" - return ( - get_module_abbreviation("VAD", selected_module) - + get_module_abbreviation("ASR", selected_module) - + get_module_abbreviation("LLM", selected_module) - + get_module_abbreviation("TTS", selected_module) - + get_module_abbreviation("Memory", selected_module) - + get_module_abbreviation("Intent", selected_module) - ) - - -def formatter(record): - """为没有 tag 的日志添加默认值""" - record["extra"].setdefault("tag", record["name"]) - return record["message"] +SERVER_VERSION = "0.2.1" def setup_logging(): @@ -43,7 +18,11 @@ def setup_logging(): "log_format_file", "{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}", ) - selected_module_str = build_module_string(config.get("selected_module", {})) + + selected_module = config.get("selected_module") + selected_module_str = "".join( + [value[0] + value[1] for key, value in selected_module.items()] + ) log_format = log_format.replace("{version}", SERVER_VERSION) log_format = log_format.replace("{selected_module}", selected_module_str) @@ -62,14 +41,9 @@ def setup_logging(): logger.remove() # 输出到控制台 - logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter) + logger.add(sys.stdout, format=log_format, level=log_level) # 输出到文件 - logger.add( - os.path.join(log_dir, log_file), - format=log_format_file, - level=log_level, - filter=formatter, - ) + logger.add(os.path.join(log_dir, log_file), format=log_format_file, level=log_level) return logger diff --git a/main/xiaozhi-server/config/private_config.py b/main/xiaozhi-server/config/private_config.py new file mode 100644 index 000000000..f708a95b1 --- /dev/null +++ b/main/xiaozhi-server/config/private_config.py @@ -0,0 +1,241 @@ +import os +import time +import yaml +from config.logger import setup_logging +from typing import Dict, Any, Optional +from copy import deepcopy +from core.utils.util import get_project_dir +from core.utils import llm, tts +from core.utils.lock_manager import FileLockManager + +TAG = __name__ + +class PrivateConfig: + def __init__(self, device_id: str, default_config: Dict[str, Any], auth_code_gen=None): + self.device_id = device_id + self.default_config = default_config + self.config_path = get_project_dir() + 'data/.private_config.yaml' + self.logger = setup_logging() + self.private_config = {} + self.auth_code_gen = auth_code_gen + self.lock_manager = FileLockManager() + + async def load_or_create(self): + try: + await self.lock_manager.acquire_lock(self.config_path) + try: + if os.path.exists(self.config_path): + with open(self.config_path, 'r', encoding='utf-8') as f: + all_configs = yaml.safe_load(f) or {} + else: + all_configs = {} + + if self.device_id not in all_configs: + # Get selected module names + selected_modules = self.default_config['selected_module'] + selected_tts = selected_modules['TTS'] + selected_llm = selected_modules['LLM'] + selected_asr = selected_modules['ASR'] + selected_vad = selected_modules['VAD'] + + # 生成认证码 + auth_code = None + if self.auth_code_gen: + auth_code = self.auth_code_gen.generate_code() + + # Initialize device config with only necessary configurations + device_config = { + 'selected_module': deepcopy(selected_modules), + 'prompt': self.default_config['prompt'], + 'LLM': { + selected_llm: deepcopy(self.default_config['LLM'][selected_llm]) + }, + 'TTS': { + selected_tts: deepcopy(self.default_config['TTS'][selected_tts]) + }, + 'ASR': { + selected_asr: deepcopy(self.default_config['ASR'][selected_asr]) + }, + 'VAD': { + selected_vad: deepcopy(self.default_config['VAD'][selected_vad]) + }, + 'auth_code': auth_code # 添加认证码字段 + } + + all_configs[self.device_id] = device_config + + # Save updated configs + with open(self.config_path, 'w', encoding='utf-8') as f: + yaml.dump(all_configs, f, allow_unicode=True) + + self.private_config = all_configs[self.device_id] + + finally: + self.lock_manager.release_lock(self.config_path) + + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error handling private config: {e}") + self.private_config = {} + + async def update_config(self, selected_modules: Dict[str, str], prompt: str, nickname: str) -> bool: + """更新设备配置 + Args: + selected_modules: 选择的模块配置,格式如 {'LLM': 'AliLLM', 'TTS': 'EdgeTTS',...} + prompt: 提示词配置 + Returns: + bool: 更新是否成功 + """ + try: + await self.lock_manager.acquire_lock(self.config_path) + try: + # Read main config to get full module configurations + main_config = self.default_config + + # Create new device config + device_config = { + 'selected_module': selected_modules, + 'prompt': prompt, + 'nickname': nickname, + } + if self.private_config.get('last_chat_time'): + device_config['last_chat_time'] = self.private_config['last_chat_time'] + if self.private_config.get('owner'): + device_config['owner'] = self.private_config['owner'] + + # Copy full module configurations from main config + for module_type, selected_name in selected_modules.items(): + if selected_name and selected_name in main_config.get(module_type, {}): + device_config[module_type] = { + selected_name: main_config[module_type][selected_name] + } + + # Read all configs + if os.path.exists(self.config_path): + with open(self.config_path, 'r', encoding='utf-8') as f: + all_configs = yaml.safe_load(f) or {} + else: + all_configs = {} + + # Update device config + all_configs[self.device_id] = device_config + self.private_config = device_config + + # Save back to file + with open(self.config_path, 'w', encoding='utf-8') as f: + yaml.dump(all_configs, f, allow_unicode=True) + + return True + finally: + self.lock_manager.release_lock(self.config_path) + + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error updating config: {e}") + return False + + async def delete_config(self) -> bool: + """删除设备配置 + Returns: + bool: 删除是否成功 + """ + try: + await self.lock_manager.acquire_lock(self.config_path) + try: + # 读取所有配置 + if os.path.exists(self.config_path): + with open(self.config_path, 'r', encoding='utf-8') as f: + all_configs = yaml.safe_load(f) or {} + else: + return False + + # 删除设备配置 + if self.device_id in all_configs: + del all_configs[self.device_id] + + # 保存更新后的配置 + with open(self.config_path, 'w', encoding='utf-8') as f: + yaml.dump(all_configs, f, allow_unicode=True) + + self.private_config = {} + return True + + return False + finally: + self.lock_manager.release_lock(self.config_path) + + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error deleting config: {e}") + return False + + def create_private_instances(self): + # 判断存在私有配置,并且self.device_id在私有配置中 + if not self.private_config: + self.logger.bind(tag=TAG).error("Private config not found for device_id: {}", self.device_id) + return None, None + + """创建私有处理模块实例""" + config = self.private_config + selected_modules = config['selected_module'] + return ( + llm.create_instance( + selected_modules["LLM"] + if not 'type' in config["LLM"][selected_modules["LLM"]] + else + config["LLM"][selected_modules["LLM"]]['type'], + config["LLM"][selected_modules["LLM"]], + ), + tts.create_instance( + selected_modules["TTS"] + if not 'type' in config["TTS"][selected_modules["TTS"]] + else + config["TTS"][selected_modules["TTS"]]["type"], + config["TTS"][selected_modules["TTS"]], + self.default_config.get("delete_audio", True) # Using default_config for global settings + ) + ) + + async def update_last_chat_time(self, timestamp=None): + """更新设备最近一次的聊天时间 + Args: + timestamp: 指定的时间戳,不传则使用当前时间 + """ + if not self.private_config: + self.logger.bind(tag=TAG).error("Private config not found") + return False + + try: + await self.lock_manager.acquire_lock(self.config_path) + try: + if timestamp is None: + timestamp = int(time.time()) + + self.private_config['last_chat_time'] = timestamp + + # 读取所有配置 + with open(self.config_path, 'r', encoding='utf-8') as f: + all_configs = yaml.safe_load(f) or {} + + # 更新当前设备配置 + all_configs[self.device_id] = self.private_config + + # 保存回文件 + with open(self.config_path, 'w', encoding='utf-8') as f: + yaml.dump(all_configs, f, allow_unicode=True) + + return True + finally: + self.lock_manager.release_lock(self.config_path) + + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error updating last chat time: {e}") + return False + + def get_auth_code(self) -> str: + """获取设备的认证码 + Returns: + str: 认证码,如果没有返回空字符串 + """ + return self.private_config.get('auth_code', '') + + def get_owner(self) -> Optional[str]: + """获取设备当前所有者""" + return self.private_config.get('owner') \ No newline at end of file diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index 78338b6ff..bb81cfe95 100644 --- a/main/xiaozhi-server/config/settings.py +++ b/main/xiaozhi-server/config/settings.py @@ -1,11 +1,82 @@ import os +import argparse +from ruamel.yaml import YAML from collections.abc import Mapping -from config.config_loader import read_config, get_project_dir, load_config +from core.utils.util import read_config, get_project_dir default_config_file = "config.yaml" -def find_missing_keys(new_config, old_config, parent_key=""): +def ensure_directories(config): + """确保所有配置路径存在""" + dirs_to_create = set() + project_dir = get_project_dir() # 获取项目根目录 + # 日志文件目录 + log_dir = config.get('log', {}).get('log_dir', 'tmp') + dirs_to_create.add(os.path.join(project_dir, log_dir)) + + # ASR/TTS模块输出目录 + for module in ['ASR', 'TTS']: + for provider in config.get(module, {}).values(): + output_dir = provider.get('output_dir', '') + if output_dir: + dirs_to_create.add(output_dir) + + # 根据selected_module创建模型目录 + selected_modules = config.get('selected_module', {}) + for module_type in ['ASR', 'LLM', 'TTS']: + selected_provider = selected_modules.get(module_type) + if not selected_provider: + continue + provider_config = config.get(module_type, {}).get(selected_provider, {}) + output_dir = provider_config.get('output_dir') + if output_dir: + full_model_dir = os.path.join(project_dir, output_dir) + dirs_to_create.add(full_model_dir) + + # 统一创建目录(保留原data目录创建) + for dir_path in dirs_to_create: + try: + os.makedirs(dir_path, exist_ok=True) + except PermissionError: + print(f"警告:无法创建目录 {dir_path},请检查写入权限") + + +def get_config_file(): + global default_config_file + """获取配置文件路径,优先使用私有配置文件(若存在)。 + + Returns: + str: 配置文件路径(相对路径或默认路径) + """ + config_file = default_config_file + if os.path.exists(get_project_dir() + "data/." + default_config_file): + config_file = "data/." + default_config_file + return config_file + + +def load_config(): + """加载配置文件""" + parser = argparse.ArgumentParser(description="Server configuration") + config_file = get_config_file() + + parser.add_argument("--config_path", type=str, default=config_file) + args = parser.parse_args() + config = read_config(args.config_path) + # 初始化目录 + ensure_directories(config) + return config + + +def update_config(config): + yaml = YAML() + yaml.preserve_quotes = True + """将配置保存到YAML文件""" + with open(get_config_file(), 'w') as f: + yaml.dump(config, f) + + +def find_missing_keys(new_config, old_config, parent_key=''): """ 递归查找缺失的配置项 返回格式:[缺失配置路径] @@ -27,28 +98,28 @@ def find_missing_keys(new_config, old_config, parent_key=""): # 递归检查嵌套字典 if isinstance(value, Mapping): sub_missing = find_missing_keys( - value, old_config[key], parent_key=full_path + value, + old_config[key], + parent_key=full_path ) missing_keys.extend(sub_missing) + return missing_keys def check_config_file(): - old_config_file = get_project_dir() + "data/." + default_config_file - if not os.path.exists(old_config_file): + old_config_file = get_config_file() + global default_config_file + if not 'data' in old_config_file: return - old_config = load_config() + old_config = read_config(get_project_dir() + old_config_file) new_config = read_config(get_project_dir() + default_config_file) # 查找缺失的配置项 missing_keys = find_missing_keys(new_config, old_config) - read_config_from_api = old_config.get("read_config_from_api", False) - if read_config_from_api: - return if missing_keys: - missing_keys_str = "\n".join(f"- {key}" for key in missing_keys) error_msg = "您的配置文件太旧了,缺少了:\n" - error_msg += missing_keys_str + error_msg += "\n".join(f"- {key}" for key in missing_keys) error_msg += "\n建议您:\n" error_msg += "1、备份data/.config.yaml文件\n" error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n" diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index c77de6380..14a920607 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1,5 +1,4 @@ import os -import copy import json import uuid import time @@ -18,17 +17,16 @@ from core.utils.util import ( get_string_no_punctuation_or_emoji, extract_json_from_string, get_ip_info, - initialize_modules, ) from concurrent.futures import ThreadPoolExecutor, TimeoutError from core.handle.sendAudioHandle import sendAudioMessage from core.handle.receiveAudioHandle import handleAudioMessage from core.handle.functionHandler import FunctionHandler from plugins_func.register import Action, ActionResponse +from config.private_config import PrivateConfig from core.auth import AuthMiddleware, AuthenticationError +from core.utils.auth_code_gen import AuthCodeGenerator from core.mcp.manager import MCPManager -from config.config_loader import get_private_config_from_api -from config.manage_api_client import DeviceNotFoundException, DeviceBindException TAG = __name__ @@ -43,13 +41,10 @@ class ConnectionHandler: def __init__( self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent ): - self.config = copy.deepcopy(config) + self.config = config self.logger = setup_logging() self.auth = AuthMiddleware(config) - self.need_bind = False - self.bind_code = None - self.websocket = None self.headers = None self.client_ip = None @@ -100,45 +95,24 @@ class ConnectionHandler: self.iot_descriptors = {} self.func_handler = None - self.cmd_exit = self.config["exit_commands"] + self.cmd_exit = self.config["CMD_exit"] self.max_cmd_length = 0 for cmd in self.cmd_exit: if len(cmd) > self.max_cmd_length: self.max_cmd_length = len(cmd) + self.private_config = None + self.auth_code_gen = AuthCodeGenerator.get_instance() + self.is_device_verified = False # 添加设备验证状态标志 self.close_after_chat = False # 是否在聊天结束后关闭连接 self.use_function_call_mode = False - - self.timeout_task = None - self.timeout_seconds = ( - int(self.config.get("close_connection_no_voice_time", 120)) + 60 - ) # 在原来第一道关闭的基础上加60秒,进行二道关闭 + if self.config["selected_module"]["Intent"] == "function_call": + self.use_function_call_mode = True async def handle_connection(self, ws): try: # 获取并验证headers self.headers = dict(ws.request.headers) - - if self.headers.get("device-id", None) is None: - # 尝试从 URL 的查询参数中获取 device-id - from urllib.parse import parse_qs, urlparse - - # 从 WebSocket 请求中获取路径 - request_path = ws.request.path - if not request_path: - self.logger.bind(tag=TAG).error("无法获取请求路径") - return - parsed_url = urlparse(request_path) - query_params = parse_qs(parsed_url.query) - if "device-id" in query_params: - self.headers["device-id"] = query_params["device-id"][0] - self.headers["client-id"] = query_params["client-id"][0] - else: - self.logger.bind(tag=TAG).error( - "无法从请求头和URL查询参数中获取device-id" - ) - return - # 获取客户端ip地址 self.client_ip = ws.remote_address[0] self.logger.bind(tag=TAG).info( @@ -147,22 +121,51 @@ class ConnectionHandler: # 进行认证 await self.auth.authenticate(self.headers) + device_id = self.headers.get("device-id", None) # 认证通过,继续处理 self.websocket = ws self.session_id = str(uuid.uuid4()) - # 启动超时检查任务 - self.timeout_task = asyncio.create_task(self._check_timeout()) - self.welcome_msg = self.config["xiaozhi"] self.welcome_msg["session_id"] = self.session_id await self.websocket.send(json.dumps(self.welcome_msg)) + # Load private configuration if device_id is provided + bUsePrivateConfig = self.config.get("use_private_config", False) + if bUsePrivateConfig and device_id: + try: + self.private_config = PrivateConfig( + device_id, self.config, self.auth_code_gen + ) + await self.private_config.load_or_create() + # 判断是否已经绑定 + owner = self.private_config.get_owner() + self.is_device_verified = owner is not None + + if self.is_device_verified: + await self.private_config.update_last_chat_time() + + llm, tts = self.private_config.create_private_instances() + if all([llm, tts]): + self.llm = llm + self.tts = tts + self.logger.bind(tag=TAG).info( + f"Loaded private config and instances for device {device_id}" + ) + else: + self.logger.bind(tag=TAG).error( + f"Failed to create instances for device {device_id}" + ) + self.private_config = None + except Exception as e: + self.logger.bind(tag=TAG).error( + f"Error initializing private config: {e}" + ) + self.private_config = None + raise - # 获取差异化配置 - private_config = self._initialize_private_config() # 异步初始化 - self.executor.submit(self._initialize_components, private_config) + self.executor.submit(self._initialize_components) # tts 消化线程 self.tts_priority_thread = threading.Thread( target=self._tts_priority_thread, daemon=True @@ -202,183 +205,47 @@ class ConnectionHandler: async def _route_message(self, message): """消息路由""" - # 重置超时计时器 - if self.timeout_task: - self.timeout_task.cancel() - self.timeout_task = asyncio.create_task(self._check_timeout()) - if isinstance(message, str): await handleTextMessage(self, message) elif isinstance(message, bytes): await handleAudioMessage(self, message) - def _initialize_components(self, private_config): - """初始化组件""" - if private_config is not None: - self._initialize_models(private_config) - else: - self.prompt = self.config["prompt"] - self.change_system_prompt(self.prompt) + def _initialize_components(self): + """加载提示词""" + self.prompt = self.config["prompt"] + if self.private_config: + self.prompt = self.private_config.private_config.get("prompt", self.prompt) + self.dialogue.put(Message(role="system", content=self.prompt)) + """加载记忆""" self._initialize_memory() """加载意图识别""" self._initialize_intent() """加载位置信息""" - self.client_ip_info = get_ip_info(self.client_ip, self.logger) + self.client_ip_info = get_ip_info(self.client_ip) if self.client_ip_info is not None and "city" in self.client_ip_info: self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}") self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}" self.dialogue.update_system_message(self.prompt) - def _initialize_private_config(self): - read_config_from_api = self.config.get("read_config_from_api", False) - """如果是从配置文件获取,则进行二次实例化""" - if not read_config_from_api: - return - """从接口获取差异化的配置进行二次实例化,非全量重新实例化""" - try: - begin_time = time.time() - private_config = get_private_config_from_api( - self.config, - self.headers.get("device-id", None), - self.headers.get("client-id", None), - ) - private_config["delete_audio"] = bool(self.config.get("delete_audio", True)) - self.logger.bind(tag=TAG).info( - f"{time.time() - begin_time} 秒,获取差异化配置成功: {private_config}" - ) - except DeviceNotFoundException as e: - self.need_bind = True - private_config = {} - except DeviceBindException as e: - self.need_bind = True - self.bind_code = e.bind_code - private_config = {} - except Exception as e: - self.need_bind = True - self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}") - private_config = {} - - init_tts = False - if private_config.get("TTS", None) is not None: - init_tts = True - self.config["TTS"] = private_config["TTS"] - self.config["selected_module"]["TTS"] = private_config["selected_module"][ - "TTS" - ] - - try: - modules = initialize_modules( - self.logger, - private_config, - False, - False, - False, - init_tts, - False, - False, - ) - except Exception as e: - self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}") - modules = {} - if modules.get("tts", None) is not None: - self.tts = modules["tts"] - if modules.get("prompt", None) is not None: - self.change_system_prompt(modules["prompt"]) - private_config["prompt"] = None - return private_config - - def _initialize_models(self, private_config): - init_vad, init_asr, init_llm, init_memory, init_intent = ( - False, - False, - False, - False, - False, - ) - if private_config.get("VAD", None) is not None: - init_vad = True - self.config["VAD"] = private_config["VAD"] - self.config["selected_module"]["VAD"] = private_config["selected_module"][ - "VAD" - ] - if private_config.get("ASR", None) is not None: - init_asr = True - self.config["ASR"] = private_config["ASR"] - self.config["selected_module"]["ASR"] = private_config["selected_module"][ - "ASR" - ] - if private_config.get("LLM", None) is not None: - init_llm = True - self.config["LLM"] = private_config["LLM"] - self.config["selected_module"]["LLM"] = private_config["selected_module"][ - "LLM" - ] - - if private_config.get("Memory", None) is not None: - init_memory = True - self.config["Memory"] = private_config["Memory"] - self.config["selected_module"]["Memory"] = private_config[ - "selected_module" - ]["Memory"] - if private_config.get("Intent", None) is not None: - init_intent = True - self.config["Intent"] = private_config["Intent"] - self.config["selected_module"]["Intent"] = private_config[ - "selected_module" - ]["Intent"] - try: - modules = initialize_modules( - self.logger, - private_config, - init_vad, - init_asr, - init_llm, - False, - init_memory, - init_intent, - ) - except Exception as e: - self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}") - modules = {} - if modules.get("vad", None) is not None: - self.vad = modules["vad"] - if modules.get("asr", None) is not None: - self.asr = modules["asr"] - if modules.get("llm", None) is not None: - self.llm = modules["llm"] - if modules.get("intent", None) is not None: - self.intent = modules["intent"] - if modules.get("memory", None) is not None: - self.memory = modules["memory"] - def _initialize_memory(self): """初始化记忆模块""" device_id = self.headers.get("device-id", None) self.memory.init_memory(device_id, self.llm) def _initialize_intent(self): - if ( - self.config["Intent"][self.config["selected_module"]["Intent"]]["type"] - == "function_call" - ): - self.use_function_call_mode = True """初始化意图识别模块""" # 获取意图识别配置 intent_config = self.config["Intent"] - intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][ - "type" - ] + intent_type = self.config["selected_module"]["Intent"] # 如果使用 nointent,直接返回 if intent_type == "nointent": return # 使用 intent_llm 模式 elif intent_type == "intent_llm": - intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ - "llm" - ] + intent_llm_name = intent_config["intent_llm"]["llm"] if intent_llm_name and intent_llm_name in self.config["LLM"]: # 如果配置了专用LLM,则创建独立的LLM实例 @@ -409,16 +276,46 @@ class ConnectionHandler: def change_system_prompt(self, prompt): self.prompt = prompt - # 更新系统prompt至上下文 - self.dialogue.update_system_message(self.prompt) + # 找到原来的role==system,替换原来的系统提示 + for m in self.dialogue.dialogue: + if m.role == "system": + m.content = prompt + + async def _check_and_broadcast_auth_code(self): + """检查设备绑定状态并广播认证码""" + if not self.private_config.get_owner(): + auth_code = self.private_config.get_auth_code() + if auth_code: + # 发送验证码语音提示 + text = f"请在后台输入验证码:{' '.join(auth_code)}" + self.recode_first_last_text(text) + future = self.executor.submit(self.speak_and_play, text) + self.tts_queue.put(future) + return False + return True + + def isNeedAuth(self): + bUsePrivateConfig = self.config.get("use_private_config", False) + if not bUsePrivateConfig: + # 如果不使用私有配置,就不需要验证 + return False + return not self.is_device_verified def chat(self, query): + if self.isNeedAuth(): + self.llm_finish_task = True + future = asyncio.run_coroutine_threadsafe( + self._check_and_broadcast_auth_code(), self.loop + ) + future.result() + return True self.dialogue.put(Message(role="user", content=query)) response_message = [] processed_chars = 0 # 跟踪已处理的字符位置 try: + start_time = time.time() # 使用带记忆的对话 future = asyncio.run_coroutine_threadsafe( self.memory.query_memory(query), self.loop @@ -440,6 +337,9 @@ class ConnectionHandler: if self.client_abort: break + end_time = time.time() + # self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}") + # 合并当前全部文本并处理未分割部分 full_text = "".join(response_message) current_text = full_text[processed_chars:] # 从未处理的位置开始 @@ -491,6 +391,13 @@ class ConnectionHandler: def chat_with_function_calling(self, query, tool_call=False): self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}") """Chat with function calling for intent detection using streaming""" + if self.isNeedAuth(): + self.llm_finish_task = True + future = asyncio.run_coroutine_threadsafe( + self._check_and_broadcast_auth_code(), self.loop + ) + future.result() + return True if not tool_call: self.dialogue.put(Message(role="user", content=query)) @@ -532,19 +439,16 @@ class ConnectionHandler: function_id = None function_arguments = "" content_arguments = "" - for response in llm_responses: content, tools_call = response - if "content" in response: content = response["content"] tools_call = None if content is not None and len(content) > 0: - content_arguments += content - - if not tool_call_flag and content_arguments.startswith(""): - # print("content_arguments", content_arguments) - tool_call_flag = True + if len(response_message) <= 0 and ( + content == "```" or "" in content + ): + tool_call_flag = True if tools_call is not None: tool_call_flag = True @@ -556,7 +460,9 @@ class ConnectionHandler: function_arguments += tools_call[0].function.arguments if content is not None and len(content) > 0: - if not tool_call_flag: + if tool_call_flag: + content_arguments += content + else: response_message.append(content) if self.client_abort: @@ -617,8 +523,9 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error( f"function call error: {content_arguments}" ) + else: + function_arguments = json.loads(function_arguments) if not bHasError: - response_message.clear() self.logger.bind(tag=TAG).info( f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}" ) @@ -714,6 +621,7 @@ class ConnectionHandler: self.tts_queue.put(future) 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"] @@ -740,14 +648,18 @@ class ConnectionHandler: Message(role="tool", tool_call_id=function_id, content=text) ) self.chat_with_function_calling(text, tool_call=True) - elif result.action == Action.NOTFOUND or result.action == Action.ERROR: + elif result.action == Action.NOTFOUND: text = result.result self.recode_first_last_text(text, text_index) future = self.executor.submit(self.speak_and_play, text, text_index) self.tts_queue.put(future) self.dialogue.put(Message(role="assistant", content=text)) else: - pass + text = result.result + self.recode_first_last_text(text, text_index) + future = self.executor.submit(self.speak_and_play, text, text_index) + self.tts_queue.put(future) + self.dialogue.put(Message(role="assistant", content=text)) def _tts_priority_thread(self): while not self.stop_event.is_set(): @@ -765,7 +677,7 @@ class ConnectionHandler: opus_datas, text_index, tts_file = [], 0, None try: self.logger.bind(tag=TAG).debug("正在处理TTS任务...") - tts_timeout = int(self.config.get("tts_timeout", 10)) + tts_timeout = self.config.get("tts_timeout", 10) tts_file, text, text_index = future.result(timeout=tts_timeout) if text is None or len(text) <= 0: self.logger.bind(tag=TAG).error( @@ -861,11 +773,6 @@ class ConnectionHandler: async def close(self, ws=None): """资源清理方法""" - # 取消超时任务 - if self.timeout_task: - self.timeout_task.cancel() - self.timeout_task = None - # 清理MCP资源 if hasattr(self, "mcp_manager") and self.mcp_manager: await self.mcp_manager.cleanup_all() @@ -919,15 +826,3 @@ class ConnectionHandler: self.close_after_chat = True except Exception as e: self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") - - async def _check_timeout(self): - """检查连接超时""" - try: - while not self.stop_event.is_set(): - await asyncio.sleep(self.timeout_seconds) - if not self.stop_event.is_set(): - self.logger.bind(tag=TAG).info("连接超时,准备关闭") - await self.close(self.websocket) - break - except Exception as e: - self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}") diff --git a/main/xiaozhi-server/core/handle/functionHandler.py b/main/xiaozhi-server/core/handle/functionHandler.py index d1bf9b44b..cec9bd254 100644 --- a/main/xiaozhi-server/core/handle/functionHandler.py +++ b/main/xiaozhi-server/core/handle/functionHandler.py @@ -57,9 +57,7 @@ class FunctionHandler: def register_config_functions(self): """注册配置中的函数,可以不同客户端使用不同的配置""" - for func in self.config["Intent"][self.config["selected_module"]["Intent"]].get( - "functions", [] - ): + for func in self.config["Intent"]["function_call"].get("functions", []): self.function_registry.register_function(func) """home assistant需要初始化提示词""" diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 51782bb94..e0fbb3087 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -8,7 +8,6 @@ import os import random import time -TAG = __name__ logger = setup_logging() WAKEUP_CONFIG = { @@ -70,19 +69,9 @@ def getWakeupWordFile(file_name): async def wakeupWordsResponse(conn): - wait_max_time = 5 - while conn.llm is None or not conn.llm.response_no_stream: - await asyncio.sleep(1) - wait_max_time -= 1 - if wait_max_time <= 0: - logger.bind(tag=TAG).error("连接对象没有llm") - return - """唤醒词响应""" wakeup_word = random.choice(WAKEUP_CONFIG["words"]) result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word) - if result is None or result == "": - return tts_file = await asyncio.to_thread(conn.tts.to_tts, result) if tts_file is not None and os.path.exists(tts_file): diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 90d8e1d59..419f60810 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -76,11 +76,6 @@ async def process_intent_result(conn, intent_result, original_text): if function_name == "continue_chat": return False - if function_name == "play_music": - funcItem = conn.func_handler.get_function(function_name) - if not funcItem: - conn.func_handler.function_registry.register_function("play_music") - function_args = None if "arguments" in intent_data["function_call"]: function_args = intent_data["function_call"]["arguments"] diff --git a/main/xiaozhi-server/core/handle/iotHandle.py b/main/xiaozhi-server/core/handle/iotHandle.py index edb7d338b..76d8b4b73 100644 --- a/main/xiaozhi-server/core/handle/iotHandle.py +++ b/main/xiaozhi-server/core/handle/iotHandle.py @@ -144,35 +144,33 @@ class IotDescriptor: self.methods = [] # 根据描述创建属性 - if properties is not None: - for key, value in properties.items(): - property_item = globals()[key] = {} - property_item["name"] = key - property_item["description"] = value["description"] - if value["type"] == "number": - property_item["value"] = 0 - elif value["type"] == "boolean": - property_item["value"] = False - else: - property_item["value"] = "" - self.properties.append(property_item) + for key, value in properties.items(): + property_item = globals()[key] = {} + property_item["name"] = key + property_item["description"] = value["description"] + if value["type"] == "number": + property_item["value"] = 0 + elif value["type"] == "boolean": + property_item["value"] = False + else: + property_item["value"] = "" + self.properties.append(property_item) # 根据描述创建方法 - if methods is not None: - for key, value in methods.items(): - method = globals()[key] = {} - method["description"] = value["description"] - method["name"] = key - for k, v in value["parameters"].items(): - method[k] = {} - method[k]["description"] = v["description"] - if v["type"] == "number": - method[k]["value"] = 0 - elif v["type"] == "boolean": - method[k]["value"] = False - else: - method[k]["value"] = "" - self.methods.append(method) + for key, value in methods.items(): + method = globals()[key] = {} + method["description"] = value["description"] + method["name"] = key + for k, v in value["parameters"].items(): + method[k] = {} + method[k]["description"] = v["description"] + if v["type"] == "number": + method[k]["value"] = 0 + elif v["type"] == "boolean": + method[k]["value"] = False + else: + method[k]["value"] = "" + self.methods.append(method) def register_device_type(descriptor): @@ -271,12 +269,14 @@ def register_device_type(descriptor): # 用于接受前端设备推送的搜索iot描述 async def handleIotDescriptors(conn, descriptors): + if not conn.use_function_call_mode: + return wait_max_time = 5 while conn.func_handler is None or not conn.func_handler.finish_init: await asyncio.sleep(1) wait_max_time -= 1 if wait_max_time <= 0: - logger.bind(tag=TAG).debug("连接对象没有func_handler") + logger.bind(tag=TAG).error("连接对象没有func_handler") return """处理物联网描述""" functions_changed = False diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 09f342dc7..f798739ab 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -1,6 +1,5 @@ from config.logger import setup_logging import time -import asyncio from core.utils.util import remove_punctuation_and_length from core.handle.sendAudioHandle import send_stt_message from core.handle.intentHandler import handle_user_intent @@ -36,7 +35,9 @@ async def handleAudioMessage(conn, audio): if len(conn.asr_audio) < 15: conn.asr_server_receive = True else: - text, _ = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id) + text, file_path = await conn.asr.speech_to_text( + conn.asr_audio, conn.session_id + ) logger.bind(tag=TAG).info(f"识别文本: {text}") text_len, _ = remove_punctuation_and_length(text) if text_len > 0: @@ -48,9 +49,6 @@ async def handleAudioMessage(conn, audio): async def startToChat(conn, text): - if conn.need_bind: - await check_bind_device(conn) - return # 首先进行意图分析 intent_handled = await handle_user_intent(conn, text) @@ -73,8 +71,8 @@ async def no_voice_close_connect(conn): conn.client_no_voice_last_time = time.time() * 1000 else: no_voice_time = time.time() * 1000 - conn.client_no_voice_last_time - close_connection_no_voice_time = int( - conn.config.get("close_connection_no_voice_time", 120) + close_connection_no_voice_time = conn.config.get( + "close_connection_no_voice_time", 120 ) if ( not conn.close_after_chat @@ -87,44 +85,3 @@ async def no_voice_close_connect(conn): "请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。" ) await startToChat(conn, prompt) - - -async def check_bind_device(conn): - if conn.bind_code: - # 确保bind_code是6位数字 - if len(conn.bind_code) != 6: - logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}") - text = "绑定码格式错误,请检查配置。" - await send_stt_message(conn, text) - return - - text = f"请登录控制面板,输入{conn.bind_code},绑定设备。" - await send_stt_message(conn, text) - conn.tts_first_text_index = 0 - conn.tts_last_text_index = 6 - conn.llm_finish_task = True - - # 播放提示音 - music_path = "config/assets/bind_code.wav" - opus_packets, _ = conn.tts.audio_to_opus_data(music_path) - conn.audio_play_queue.put((opus_packets, text, 0)) - - # 逐个播放数字 - for i in range(6): # 确保只播放6位数字 - try: - digit = conn.bind_code[i] - num_path = f"config/assets/bind_code/{digit}.wav" - num_packets, _ = conn.tts.audio_to_opus_data(num_path) - conn.audio_play_queue.put((num_packets, None, i + 1)) - except Exception as e: - logger.bind(tag=TAG).error(f"播放数字音频失败: {e}") - continue - else: - text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。" - await send_stt_message(conn, text) - conn.tts_first_text_index = 0 - conn.tts_last_text_index = 0 - conn.llm_finish_task = True - music_path = "config/assets/bind_not_found.wav" - opus_packets, _ = conn.tts.audio_to_opus_data(music_path) - conn.audio_play_queue.put((opus_packets, text, 0)) diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index 1271e466e..3a1e84852 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -3,6 +3,7 @@ import json import asyncio import time from core.utils.util import ( + remove_punctuation_and_length, get_string_no_punctuation_or_emoji, ) diff --git a/main/xiaozhi-server/core/mcp/manager.py b/main/xiaozhi-server/core/mcp/manager.py index f212b67a4..28efd87db 100644 --- a/main/xiaozhi-server/core/mcp/manager.py +++ b/main/xiaozhi-server/core/mcp/manager.py @@ -1,30 +1,26 @@ """MCP服务管理器""" - import os, json from typing import Dict, Any, List from .MCPClient import MCPClient from config.logger import setup_logging -from plugins_func.register import register_function, ToolType -from config.config_loader import get_project_dir +from core.utils.util import get_project_dir +from plugins_func.register import register_function, ActionResponse, Action, ToolType TAG = __name__ - class MCPManager: """管理多个MCP服务的集中管理器""" - def __init__(self, conn) -> None: + def __init__(self,conn) -> None: """ 初始化MCP管理器 """ self.conn = conn self.logger = setup_logging() - self.config_path = get_project_dir() + "data/.mcp_server_settings.json" + self.config_path = get_project_dir() + 'data/.mcp_server_settings.json' if os.path.exists(self.config_path) == False: self.config_path = "" - self.logger.bind(tag=TAG).warning( - f"请检查mcp服务配置文件:data/.mcp_server_settings.json" - ) + self.logger.bind(tag=TAG).warning(f"请检查mcp服务配置文件:data/.mcp_server_settings.json") self.client: Dict[str, MCPClient] = {} self.tools = [] @@ -35,15 +31,13 @@ class MCPManager: """ if len(self.config_path) == 0: return {} - + try: - with open(self.config_path, "r", encoding="utf-8") as f: + with open(self.config_path, 'r', encoding='utf-8') as f: config = json.load(f) - return config.get("mcpServers", {}) + return config.get('mcpServers', {}) except Exception as e: - self.logger.bind(tag=TAG).error( - f"Error loading MCP config from {self.config_path}: {e}" - ) + self.logger.bind(tag=TAG).error(f"Error loading MCP config from {self.config_path}: {e}") return {} async def initialize_servers(self) -> None: @@ -51,9 +45,7 @@ class MCPManager: config = self.load_config() for name, srv_config in config.items(): if not srv_config.get("command"): - self.logger.bind(tag=TAG).warning( - f"Skipping server {name}: command not specified" - ) + self.logger.bind(tag=TAG).warning(f"Skipping server {name}: command not specified") continue try: @@ -64,18 +56,12 @@ class MCPManager: client_tools = client.get_available_tools() self.tools.extend(client_tools) for tool in client_tools: - func_name = "mcp_" + tool["function"]["name"] - register_function(func_name, tool, ToolType.MCP_CLIENT)( - self.execute_tool - ) - self.conn.func_handler.function_registry.register_function( - func_name - ) + func_name = "mcp_"+tool["function"]["name"] + register_function(func_name, tool, ToolType.MCP_CLIENT)(self.execute_tool) + self.conn.func_handler.function_registry.register_function(func_name) except Exception as e: - self.logger.bind(tag=TAG).error( - f"Failed to initialize MCP server {name}: {e}" - ) + self.logger.bind(tag=TAG).error(f"Failed to initialize MCP server {name}: {e}") self.conn.func_handler.upload_functions_desc() def get_all_tools(self) -> List[Dict[str, Any]]: @@ -93,10 +79,7 @@ class MCPManager: bool: 是否是MCP工具 """ for tool in self.tools: - if ( - tool.get("function") != None - and tool["function"].get("name") == tool_name - ): + if tool.get("function") != None and tool["function"].get("name") == tool_name: return True return False @@ -104,19 +87,17 @@ class MCPManager: """执行工具调用 Args: tool_name: 工具名称 - arguments: 工具参数 + arguments: 工具参数 Returns: Any: 工具执行结果 Raises: ValueError: 工具未找到时抛出 """ - self.logger.bind(tag=TAG).info( - f"Executing tool {tool_name} with arguments: {arguments}" - ) + self.logger.bind(tag=TAG).info(f"Executing tool {tool_name} with arguments: {arguments}") for client in self.client.values(): if client.has_tool(tool_name): return await client.call_tool(tool_name, arguments) - + raise ValueError(f"Tool {tool_name} not found in any MCP server") async def cleanup_all(self) -> None: @@ -125,7 +106,5 @@ class MCPManager: await client.cleanup() self.logger.bind(tag=TAG).info(f"Cleaned up MCP client: {name}") except Exception as e: - self.logger.bind(tag=TAG).error( - f"Error cleaning up MCP client {name}: {e}" - ) + self.logger.bind(tag=TAG).error(f"Error cleaning up MCP client {name}: {e}") self.client.clear() diff --git a/main/xiaozhi-server/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py index 97d0d8e72..d39a8589c 100644 --- a/main/xiaozhi-server/core/providers/llm/base.py +++ b/main/xiaozhi-server/core/providers/llm/base.py @@ -35,5 +35,4 @@ class LLMProviderBase(ABC): """ # For providers that don't support functions, just return regular response for token in self.response(session_id, dialogue): - yield token, None - + yield {"type": "content", "content": token} \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py index 416d4ce34..b1b14d91d 100644 --- a/main/xiaozhi-server/core/providers/llm/coze/coze.py +++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py @@ -4,11 +4,9 @@ import json import re from core.providers.llm.base import LLMProviderBase import os - # official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py) from cozepy import COZE_CN_BASE_URL from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType # noqa -from core.providers.llm.system_prompt import get_system_prompt_for_function TAG = __name__ logger = setup_logging() @@ -17,8 +15,8 @@ logger = setup_logging() class LLMProvider(LLMProviderBase): def __init__(self, config): self.personal_access_token = config.get("personal_access_token") - self.bot_id = str(config.get("bot_id")) - self.user_id = str(config.get("user_id")) + self.bot_id = config.get("bot_id") + self.user_id = config.get("user_id") self.session_conversation_map = {} # 存储session_id和conversation_id的映射 def response(self, session_id, dialogue): @@ -26,13 +24,16 @@ class LLMProvider(LLMProviderBase): coze_api_base = COZE_CN_BASE_URL last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") - + coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base) conversation_id = self.session_conversation_map.get(session_id) # 如果没有找到conversation_id,则创建新的对话 if not conversation_id: - conversation = coze.conversations.create(messages=[]) + conversation = coze.conversations.create( + messages=[ + ] + ) conversation_id = conversation.id self.session_conversation_map[session_id] = conversation_id # 更新映射 @@ -46,24 +47,4 @@ class LLMProvider(LLMProviderBase): ): if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA: print(event.message.content, end="", flush=True) - yield event.message.content - - def response_with_functions(self, session_id, dialogue, functions=None): - if len(dialogue) == 2 and functions is not None and len(functions) > 0: - # 第一次调用llm, 取最后一条用户消息,附加tool提示词 - last_msg = dialogue[-1]["content"] - function_str = json.dumps(functions, ensure_ascii=False) - modify_msg = get_system_prompt_for_function(function_str) + last_msg - dialogue[-1]["content"] = modify_msg - - # 如果最后一个是 role="tool",附加到user上 - if len(dialogue) > 1 and dialogue[-1]["role"] == "tool": - assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n" - while len(dialogue) > 1 : - if dialogue[-1]["role"] == "user": - dialogue[-1]["content"] = assistant_msg + dialogue[-1]["content"] - break - dialogue.pop() - - for token in self.response(session_id, dialogue): - yield token, None + yield event.message.content \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py index 09f0739e1..26bb48b7d 100644 --- a/main/xiaozhi-server/core/providers/llm/dify/dify.py +++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py @@ -2,7 +2,6 @@ import json from config.logger import setup_logging import requests from core.providers.llm.base import LLMProviderBase -from core.providers.llm.system_prompt import get_system_prompt_for_function TAG = __name__ logger = setup_logging() @@ -59,8 +58,7 @@ class LLMProvider(LLMProviderBase): self.session_conversation_map[session_id] = ( conversation_id # 更新映射 ) - # 过滤 message_replace 事件,此事件会全量推一次 - if event.get("event") != "message_replace" and event.get("answer"): + if event.get("answer"): yield event["answer"] elif self.mode == "workflows/run": for line in r.iter_lines(): @@ -75,30 +73,9 @@ class LLMProvider(LLMProviderBase): for line in r.iter_lines(): if line.startswith(b"data: "): event = json.loads(line[6:]) - # 过滤 message_replace 事件,此事件会全量推一次 - if event.get("event") != "message_replace" and event.get("answer"): + if event.get("answer"): yield event["answer"] except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") yield "【服务响应异常】" - - def response_with_functions(self, session_id, dialogue, functions=None): - if len(dialogue) == 2 and functions is not None and len(functions) > 0: - # 第一次调用llm, 取最后一条用户消息,附加tool提示词 - last_msg = dialogue[-1]["content"] - function_str = json.dumps(functions, ensure_ascii=False) - modify_msg = get_system_prompt_for_function(function_str) + last_msg - dialogue[-1]["content"] = modify_msg - - # 如果最后一个是 role="tool",附加到user上 - if len(dialogue) > 1 and dialogue[-1]["role"] == "tool": - assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n" - while len(dialogue) > 1 : - if dialogue[-1]["role"] == "user": - dialogue[-1]["content"] = assistant_msg + dialogue[-1]["content"] - break - dialogue.pop() - - for token in self.response(session_id, dialogue): - yield token, None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py index ca78caa90..93c7dcb5f 100644 --- a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py +++ b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py @@ -4,17 +4,15 @@ from core.providers.llm.base import LLMProviderBase from config.logger import setup_logging import requests import json - TAG = __name__ logger = setup_logging() - class LLMProvider(LLMProviderBase): def __init__(self, config): """初始化Gemini LLM Provider""" self.model_name = config.get("model_name", "gemini-1.5-pro") self.api_key = config.get("api_key") - self.http_proxy = config.get("http_proxy") + self.http_proxy=config.get("http_proxy") self.https_proxy = config.get("https_proxy") have_key = check_model_key("LLM", self.api_key) @@ -24,7 +22,7 @@ class LLMProvider(LLMProviderBase): try: # 初始化Gemini客户端 # 配置代理(如果提供了代理配置) - self.proxies = None + self.proxies=None if self.http_proxy is not "" or self.https_proxy is not "": self.proxies = { @@ -64,16 +62,19 @@ class LLMProvider(LLMProviderBase): role = "model" if msg["role"] == "assistant" else "user" content = msg["content"].strip() if content: - chat_history.append({"role": role, "parts": [{"text": content}]}) + chat_history.append({ + "role": role, + "parts": [{"text":content}] + + }) # 获取当前消息 current_msg = dialogue[-1]["content"] # 构建请求体 request_body = { - "contents": chat_history - + [{"role": "user", "parts": [{"text": current_msg}]}], - "generationConfig": self.generation_config, + "contents": chat_history + [{"role": "user", "parts": [{"text":current_msg}]}], + "generationConfig": self.generation_config } # 构建请求URL @@ -86,17 +87,11 @@ class LLMProvider(LLMProviderBase): # 发送POST请求,经测试手动 request 无法使用 stream 模式 if self.proxies: - response = requests.post( - url, - headers=headers, - json=request_body, - stream=False, - proxies=self.proxies, - ) + response = requests.post(url, headers=headers, json=request_body, stream=False, proxies=self.proxies) try: data = response.json() # 直接解析JSON - if "candidates" in data and data["candidates"]: - yield data["candidates"][0]["content"]["parts"][0]["text"] + if 'candidates' in data and data['candidates']: + yield data['candidates'][0]['content']['parts'][0]['text'] else: yield "未找到候选回复。" except json.JSONDecodeError as e: @@ -109,11 +104,13 @@ class LLMProvider(LLMProviderBase): # 发送消息并获取流式响应 response = chat.send_message( - current_msg, stream=True, generation_config=self.generation_config + current_msg, + stream=True, + generation_config=self.generation_config ) # 处理流式响应 for chunk in response: - if hasattr(chunk, "text") and chunk.text: + if hasattr(chunk, 'text') and chunk.text: yield chunk.text except Exception as e: @@ -128,6 +125,9 @@ class LLMProvider(LLMProviderBase): else: yield f"【Gemini服务响应异常: {error_msg}】" + + + except requests.exceptions.RequestException as e: yield f"请求失败:{e}" except json.JSONDecodeError as e: diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py index fb34ced5d..179a85b1e 100644 --- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py +++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py @@ -63,4 +63,4 @@ class LLMProvider(LLMProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}") - yield f"【Ollama服务响应异常: {str(e)}】", None + yield {"type": "content", "content": f"【Ollama服务响应异常: {str(e)}】"} diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 2c04662ba..c3732a221 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -11,19 +11,11 @@ class LLMProvider(LLMProviderBase): def __init__(self, config): self.model_name = config.get("model_name") self.api_key = config.get("api_key") - if "base_url" in config: + if 'base_url' in config: self.base_url = config.get("base_url") else: self.base_url = config.get("url") - max_tokens = config.get("max_tokens") - if max_tokens is None or max_tokens == "": - max_tokens = 500 - - try: - max_tokens = int(max_tokens) - except (ValueError, TypeError): - max_tokens = 500 - self.max_tokens = max_tokens + self.max_tokens = config.get("max_tokens", 500) check_model_key("LLM", self.api_key) self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url) @@ -41,22 +33,18 @@ class LLMProvider(LLMProviderBase): for chunk in responses: try: # 检查是否存在有效的choice且content不为空 - delta = ( - chunk.choices[0].delta - if getattr(chunk, "choices", None) - else None - ) - content = delta.content if hasattr(delta, "content") else "" + delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None + content = delta.content if hasattr(delta, 'content') else '' except IndexError: - content = "" + content = '' if content: # 处理标签跨多个chunk的情况 - if "" in content: + if '' in content: is_active = False - content = content.split("")[0] - if "" in content: + content = content.split('')[0] + if '' in content: is_active = True - content = content.split("")[-1] + content = content.split('')[-1] if is_active: yield content @@ -66,7 +54,10 @@ class LLMProvider(LLMProviderBase): def response_with_functions(self, session_id, dialogue, functions=None): try: stream = self.client.chat.completions.create( - model=self.model_name, messages=dialogue, stream=True, tools=functions + model=self.model_name, + messages=dialogue, + stream=True, + tools=functions ) for chunk in stream: @@ -74,4 +65,4 @@ class LLMProvider(LLMProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"Error in function call streaming: {e}") - yield f"【OpenAI服务响应异常: {e}】", None + yield {"type": "content", "content": f"【OpenAI服务响应异常: {e}】"} diff --git a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py index cc12a9c1c..9a82efe58 100644 --- a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py +++ b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py @@ -6,14 +6,13 @@ from core.utils.util import check_model_key TAG = __name__ - class MemoryProvider(MemoryProviderBase): def __init__(self, config): super().__init__(config) self.api_key = config.get("api_key", "") self.api_version = config.get("api_version", "v1.1") have_key = check_model_key("Mem0ai", self.api_key) - if not have_key: + if not have_key : self.use_mem0 = False return else: @@ -31,55 +30,54 @@ class MemoryProvider(MemoryProviderBase): return None if len(msgs) < 2: return None - + try: # Format the content as a message list for mem0 messages = [ {"role": message.role, "content": message.content} - for message in msgs - if message.role != "system" + for message in msgs if message.role != "system" ] - result = self.client.add( - messages, user_id=self.role_id, output_format=self.api_version - ) + result = self.client.add(messages, user_id=self.role_id, output_format=self.api_version) logger.bind(tag=TAG).debug(f"Save memory result: {result}") except Exception as e: logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") return None - async def query_memory(self, query: str) -> str: + async def query_memory(self, query: str)-> str: if not self.use_mem0: return "" try: results = self.client.search( - query, user_id=self.role_id, output_format=self.api_version + query, + user_id=self.role_id, + output_format=self.api_version ) - if not results or "results" not in results: + if not results or 'results' not in results: return "" - + # Format each memory entry with its update time up to minutes memories = [] - for entry in results["results"]: - timestamp = entry.get("updated_at", "") + for entry in results['results']: + timestamp = entry.get('updated_at', '') if timestamp: try: # Parse and reformat the timestamp - dt = timestamp.split(".")[0] # Remove milliseconds - formatted_time = dt.replace("T", " ") + dt = timestamp.split('.')[0] # Remove milliseconds + formatted_time = dt.replace('T', ' ') except: formatted_time = timestamp - memory = entry.get("memory", "") + memory = entry.get('memory', '') if timestamp and memory: # Store tuple of (timestamp, formatted_string) for sorting memories.append((timestamp, f"[{formatted_time}] {memory}")) - + # Sort by timestamp in descending order (newest first) memories.sort(key=lambda x: x[0], reverse=True) - + # Extract only the formatted strings memories_str = "\n".join(f"- {memory[1]}" for memory in memories) logger.bind(tag=TAG).debug(f"Query results: {memories_str}") return memories_str except Exception as e: logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") - return "" + return "" \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py index fca7c228a..c66438615 100644 --- a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py +++ b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py @@ -3,8 +3,7 @@ import time import json import os import yaml -from config.config_loader import get_project_dir - +from core.utils.util import get_project_dir short_term_memory_prompt = """ # 时空记忆编织者 @@ -72,12 +71,11 @@ short_term_memory_prompt = """ ``` """ - def extract_json_data(json_code): start = json_code.find("```json") # 从start开始找到下一个```结束 - end = json_code.find("```", start + 1) - # print("start:", start, "end:", end) + end = json_code.find("```", start+1) + #print("start:", start, "end:", end) if start == -1 or end == -1: try: jsonData = json.loads(json_code) @@ -85,76 +83,74 @@ def extract_json_data(json_code): except Exception as e: print("Error:", e) return "" - jsonData = json_code[start + 7 : end] + jsonData = json_code[start+7:end] return jsonData - TAG = __name__ - class MemoryProvider(MemoryProviderBase): def __init__(self, config): super().__init__(config) self.short_momery = "" - self.memory_path = get_project_dir() + "data/.memory.yaml" + self.memory_path = get_project_dir() + 'data/.memory.yaml' self.load_memory() def init_memory(self, role_id, llm): super().init_memory(role_id, llm) self.load_memory() - + def load_memory(self): all_memory = {} if os.path.exists(self.memory_path): - with open(self.memory_path, "r", encoding="utf-8") as f: + with open(self.memory_path, 'r', encoding='utf-8') as f: all_memory = yaml.safe_load(f) or {} if self.role_id in all_memory: self.short_momery = all_memory[self.role_id] - + def save_memory_to_file(self): all_memory = {} if os.path.exists(self.memory_path): - with open(self.memory_path, "r", encoding="utf-8") as f: - all_memory = yaml.safe_load(f) or {} + with open(self.memory_path, 'r', encoding='utf-8') as f: + all_memory = yaml.safe_load(f) or {} all_memory[self.role_id] = self.short_momery - with open(self.memory_path, "w", encoding="utf-8") as f: + with open(self.memory_path, 'w', encoding='utf-8') as f: yaml.dump(all_memory, f, allow_unicode=True) - + async def save_memory(self, msgs): if self.llm is None: logger.bind(tag=TAG).error("LLM is not set for memory provider") return None - + if len(msgs) < 2: return None - + msgStr = "" for msg in msgs: if msg.role == "user": msgStr += f"User: {msg.content}\n" - elif msg.role == "assistant": + elif msg.role== "assistant": msgStr += f"Assistant: {msg.content}\n" if len(self.short_momery) > 0: - msgStr += "历史记忆:\n" - msgStr += self.short_momery - - # 当前时间 + msgStr+="历史记忆:\n" + msgStr+=self.short_momery + + #当前时间 time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) msgStr += f"当前时间:{time_str}" result = self.llm.response_no_stream(short_term_memory_prompt, msgStr) - + json_str = extract_json_data(result) try: - json_data = json.loads(json_str) # 检查json格式是否正确 + json_data = json.loads(json_str) # 检查json格式是否正确 self.short_momery = json_str except Exception as e: print("Error:", e) - + self.save_memory_to_file() logger.bind(tag=TAG).info(f"Save memory successful - Role: {self.role_id}") return self.short_momery - - async def query_memory(self, query: str) -> str: - return self.short_momery + + async def query_memory(self, query: str)-> str: + return self.short_momery \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/cozecn.py b/main/xiaozhi-server/core/providers/tts/cozecn.py index 1f9244f65..74de9ab3b 100644 --- a/main/xiaozhi-server/core/providers/tts/cozecn.py +++ b/main/xiaozhi-server/core/providers/tts/cozecn.py @@ -12,20 +12,14 @@ class TTSProvider(TTSProviderBase): super().__init__(config, delete_audio_file) self.model = config.get("model") self.access_token = config.get("access_token") - if config.get("private_voice"): - self.voice = config.get("private_voice") - else: - self.voice = config.get("voice") + self.voice = config.get("voice") self.response_format = config.get("response_format") self.host = "api.coze.cn" self.api_url = f"https://{self.host}/v1/audio/speech" def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): request_json = { @@ -36,11 +30,9 @@ class TTSProvider(TTSProviderBase): } headers = { "Authorization": f"Bearer {self.access_token}", - "Content-Type": "application/json", + "Content-Type": "application/json" } - response = requests.request( - "POST", self.api_url, json=request_json, headers=headers - ) + response = requests.request("POST", self.api_url, json=request_json, headers=headers) data = response.content file_to_save = open(output_file, "wb") file_to_save.write(data) diff --git a/main/xiaozhi-server/core/providers/tts/doubao.py b/main/xiaozhi-server/core/providers/tts/doubao.py index 0051d53e9..55438a0c2 100644 --- a/main/xiaozhi-server/core/providers/tts/doubao.py +++ b/main/xiaozhi-server/core/providers/tts/doubao.py @@ -6,10 +6,6 @@ import requests from datetime import datetime from core.utils.util import check_model_key from core.providers.tts.base import TTSProviderBase -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() class TTSProvider(TTSProviderBase): @@ -18,31 +14,25 @@ class TTSProvider(TTSProviderBase): self.appid = config.get("appid") self.access_token = config.get("access_token") self.cluster = config.get("cluster") - - if config.get("private_voice"): - self.voice = config.get("private_voice") - else: - self.voice = config.get("voice") - + self.voice = config.get("voice") self.api_url = config.get("api_url") self.authorization = config.get("authorization") self.header = {"Authorization": f"{self.authorization}{self.access_token}"} check_model_key("TTS", self.access_token) def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): request_json = { "app": { "appid": f"{self.appid}", "token": "access_token", - "cluster": self.cluster, + "cluster": self.cluster + }, + "user": { + "uid": "1" }, - "user": {"uid": "1"}, "audio": { "voice_type": self.voice, "encoding": "wav", @@ -56,21 +46,17 @@ class TTSProvider(TTSProviderBase): "text_type": "plain", "operation": "query", "with_frontend": 1, - "frontend_type": "unitTson", - }, + "frontend_type": "unitTson" + } } try: - resp = requests.post( - self.api_url, json.dumps(request_json), headers=self.header - ) + resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header) if "data" in resp.json(): data = resp.json()["data"] file_to_save = open(output_file, "wb") file_to_save.write(base64.b64decode(data)) else: - raise Exception( - f"{__name__} status_code: {resp.status_code} response: {resp.content}" - ) + raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}") except Exception as e: raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py index b86e4087c..289961cbe 100644 --- a/main/xiaozhi-server/core/providers/tts/edge.py +++ b/main/xiaozhi-server/core/providers/tts/edge.py @@ -8,26 +8,20 @@ from core.providers.tts.base import TTSProviderBase class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) - if config.get("private_voice"): - self.voice = config.get("private_voice") - else: - self.voice = config.get("voice") + self.voice = config.get("voice") def generate_filename(self, extension=".mp3"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): communicate = edge_tts.Communicate(text, voice=self.voice) # 确保目录存在并创建空文件 os.makedirs(os.path.dirname(output_file), exist_ok=True) - with open(output_file, "wb") as f: + with open(output_file, 'wb') as f: pass - + # 流式写入音频数据 - with open(output_file, "ab") as f: # 改为追加模式避免覆盖 + with open(output_file, 'ab') as f: # 改为追加模式避免覆盖 async for chunk in communicate.stream(): if chunk["type"] == "audio": # 只处理音频数据块 f.write(chunk["data"]) diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py index 30fee3c99..e8af4eb48 100644 --- a/main/xiaozhi-server/core/providers/tts/fishspeech.py +++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py @@ -8,7 +8,7 @@ from pydantic import BaseModel, Field, conint, model_validator from typing_extensions import Annotated from datetime import datetime from typing import Literal -from core.utils.util import check_model_key, parse_string_to_list +from core.utils.util import check_model_key from core.providers.tts.base import TTSProviderBase from config.logger import setup_logging @@ -24,7 +24,7 @@ class ServeReferenceAudio(BaseModel): def decode_audio(cls, values): audio = values.get("audio") if ( - isinstance(audio, str) and len(audio) > 255 + isinstance(audio, str) and len(audio) > 255 ): # Check if audio is a string (Base64) try: values["audio"] = base64.b64decode(audio) @@ -86,35 +86,28 @@ class TTSProvider(TTSProviderBase): super().__init__(config, delete_audio_file) self.reference_id = config.get("reference_id") - self.reference_audio = parse_string_to_list(config.get("reference_audio")) - self.reference_text = parse_string_to_list(config.get("reference_text")) + self.reference_audio = config.get("reference_audio", []) + self.reference_text = config.get("reference_text", []) self.format = config.get("format", "wav") - self.channels = int(config.get("channels", 1)) - self.rate = int(config.get("rate", 44100)) + self.channels = config.get("channels", 1) + self.rate = config.get("rate", 44100) self.api_key = config.get("api_key", "YOUR_API_KEY") have_key = check_model_key("FishSpeech TTS", self.api_key) if not have_key: return self.normalize = config.get("normalize", True) - self.max_new_tokens = int(config.get("max_new_tokens", 1024)) - self.chunk_length = int(config.get("chunk_length", 200)) - self.top_p = float(config.get("top_p", 0.7)) - self.repetition_penalty = float(config.get("repetition_penalty", 1.2)) - self.temperature = float(config.get("temperature", 0.7)) - self.streaming = str(config.get("streaming", False)).lower() in ( - "true", - "1", - "yes", - ) + self.max_new_tokens = config.get("max_new_tokens", 1024) + self.chunk_length = config.get("chunk_length", 200) + self.top_p = config.get("top_p", 0.7) + self.repetition_penalty = config.get("repetition_penalty", 1.2) + self.temperature = config.get("temperature", 0.7) + self.streaming = config.get("streaming", False) self.use_memory_cache = config.get("use_memory_cache", "on") - self.seed = config.get("seed") or None + self.seed = config.get("seed") self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts") def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): # Prepare reference data @@ -124,7 +117,9 @@ class TTSProvider(TTSProviderBase): data = { "text": text, "references": [ - ServeReferenceAudio(audio=audio if audio else b"", text=text) + ServeReferenceAudio( + audio=audio if audio else b"", text=text + ) for text, audio in zip(ref_texts, byte_audios) ], "reference_id": self.reference_id, @@ -144,9 +139,7 @@ class TTSProvider(TTSProviderBase): response = requests.post( self.api_url, - data=ormsgpack.packb( - pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC - ), + data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC), headers={ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/msgpack", @@ -159,6 +152,8 @@ class TTSProvider(TTSProviderBase): with open(output_file, "wb") as audio_file: audio_file.write(audio_content) + + else: print(f"Request failed with status code {response.status_code}") print(response.json()) diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py index ec6c20530..ae20beb62 100644 --- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py +++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py @@ -6,12 +6,10 @@ import requests from config.logger import setup_logging from datetime import datetime from core.providers.tts.base import TTSProviderBase -from core.utils.util import parse_string_to_list TAG = __name__ logger = setup_logging() - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) @@ -20,45 +18,23 @@ class TTSProvider(TTSProviderBase): self.ref_audio_path = config.get("ref_audio_path") self.prompt_text = config.get("prompt_text") self.prompt_lang = config.get("prompt_lang", "zh") - self.top_k = int(config.get("top_k", 5)) - self.top_p = float(config.get("top_p", 1)) - self.temperature = float(config.get("temperature", 1)) + self.top_k = config.get("top_k", 5) + self.top_p = config.get("top_p", 1) + self.temperature = config.get("temperature", 1) self.text_split_method = config.get("text_split_method", "cut0") - self.batch_size = int(config.get("batch_size", 1)) - self.batch_threshold = float(config.get("batch_threshold", 0.75)) - - self.split_bucket = str(config.get("split_bucket", True)).lower() in ( - "true", - "1", - "yes", - ) - self.return_fragment = str(config.get("return_fragment", False)).lower() in ( - "true", - "1", - "yes", - ) - self.speed_factor = float(config.get("speed_factor", 1.0)) - self.streaming_mode = str(config.get("streaming_mode", False)).lower() in ( - "true", - "1", - "yes", - ) - self.seed = int(config.get("seed", -1)) - self.parallel_infer = str(config.get("parallel_infer", True)).lower() in ( - "true", - "1", - "yes", - ) - self.repetition_penalty = float(config.get("repetition_penalty", 1.35)) - self.aux_ref_audio_paths = parse_string_to_list( - config.get("aux_ref_audio_paths") - ) + self.batch_size = config.get("batch_size", 1) + self.batch_threshold = config.get("batch_threshold", 0.75) + self.split_bucket = config.get("split_bucket", True) + self.return_fragment = config.get("return_fragment", False) + self.speed_factor = config.get("speed_factor", 1.0) + self.streaming_mode = config.get("streaming_mode", False) + self.seed = config.get("seed", -1) + self.parallel_infer = config.get("parallel_infer", True) + self.repetition_penalty = config.get("repetition_penalty", 1.35) + self.aux_ref_audio_paths = config.get("aux_ref_audio_paths", []) def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): request_json = { @@ -80,7 +56,7 @@ class TTSProvider(TTSProviderBase): "streaming_mode": self.streaming_mode, "seed": self.seed, "parallel_infer": self.parallel_infer, - "repetition_penalty": self.repetition_penalty, + "repetition_penalty": self.repetition_penalty } resp = requests.post(self.url, json=request_json) @@ -88,6 +64,4 @@ class TTSProvider(TTSProviderBase): with open(output_file, "wb") as file: file.write(resp.content) else: - logger.bind(tag=TAG).error( - f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}" - ) + logger.bind(tag=TAG).error(f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}") diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py index b2746acfc..ebfb12f17 100644 --- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py +++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py @@ -4,12 +4,10 @@ import requests from config.logger import setup_logging from datetime import datetime from core.providers.tts.base import TTSProviderBase -from core.utils.util import parse_string_to_list TAG = __name__ logger = setup_logging() - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) @@ -18,20 +16,18 @@ class TTSProvider(TTSProviderBase): self.prompt_text = config.get("prompt_text") self.prompt_language = config.get("prompt_language") self.text_language = config.get("text_language", "audo") - self.top_k = int(config.get("top_k", 15)) - self.top_p = float(config.get("top_p", 1.0)) - self.temperature = float(config.get("temperature", 1.0)) - self.cut_punc = config.get("cut_punc", "") - self.speed = float(config.get("speed", 1.0)) - self.inp_refs = parse_string_to_list(config.get("inp_refs")) - self.sample_steps = int(config.get("sample_steps", 32)) - self.if_sr = str(config.get("if_sr", False)).lower() in ("true", "1", "yes") + self.top_k = config.get("top_k", 15) + self.top_p = config.get("top_p", 1.0) + self.temperature = config.get("temperature", 1.0) + self.cut_punc = config.get("cut_punc","") + self.speed = config.get("speed", 1.0) + self.inp_refs = config.get("inp_refs",[]) + self.sample_steps = config.get("sample_steps",32) + self.if_sr = config.get("if_sr",False) + def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): request_params = { @@ -55,6 +51,4 @@ class TTSProvider(TTSProviderBase): with open(output_file, "wb") as file: file.write(resp.content) else: - logger.bind(tag=TAG).error( - f"GPT_SoVITS_V3 TTS请求失败: {resp.status_code} - {resp.text}" - ) + logger.bind(tag=TAG).error(f"GPT_SoVITS_V3 TTS请求失败: {resp.status_code} - {resp.text}") diff --git a/main/xiaozhi-server/core/providers/tts/minimax.py b/main/xiaozhi-server/core/providers/tts/minimax.py index dd406b64a..1fe7be502 100644 --- a/main/xiaozhi-server/core/providers/tts/minimax.py +++ b/main/xiaozhi-server/core/providers/tts/minimax.py @@ -4,7 +4,6 @@ import json import requests from datetime import datetime from core.providers.tts.base import TTSProviderBase -from core.utils.util import parse_string_to_list class TTSProvider(TTSProviderBase): @@ -13,35 +12,30 @@ class TTSProvider(TTSProviderBase): self.group_id = config.get("group_id") self.api_key = config.get("api_key") self.model = config.get("model") - if config.get("private_voice"): - self.voice_id = config.get("private_voice") - else: - self.voice_id = config.get("voice_id") + self.voice_id = config.get("voice_id") default_voice_setting = { "voice_id": "female-shaonv", "speed": 1, "vol": 1, "pitch": 0, - "emotion": "happy", + "emotion": "happy" + } + default_pronunciation_dict = { + "tone": [ + "处理/(chu3)(li3)", "危险/dangerous" + ] } - default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} defult_audio_setting = { "sample_rate": 32000, "bitrate": 128000, "format": "mp3", - "channel": 1, - } - self.voice_setting = { - **default_voice_setting, - **config.get("voice_setting", {}), - } - self.pronunciation_dict = { - **default_pronunciation_dict, - **config.get("pronunciation_dict", {}), + "channel": 1 } + self.voice_setting = {**default_voice_setting, **config.get("voice_setting", {})} + self.pronunciation_dict = {**default_pronunciation_dict, **config.get("pronunciation_dict", {})} self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})} - self.timber_weights = parse_string_to_list(config.get("timber_weights")) + self.timber_weights = config.get("timber_weights", []) if self.voice_id: self.voice_setting["voice_id"] = self.voice_id @@ -50,14 +44,11 @@ class TTSProvider(TTSProviderBase): self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}" self.header = { "Content-Type": "application/json", - "Authorization": f"Bearer {self.api_key}", + "Authorization": f"Bearer {self.api_key}" } def generate_filename(self, extension=".mp3"): - return os.path.join( - self.output_file, - f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): request_json = { @@ -74,17 +65,13 @@ class TTSProvider(TTSProviderBase): request_json["voice_setting"]["voice_id"] = "" try: - resp = requests.post( - self.api_url, json.dumps(request_json), headers=self.header - ) + resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header) # 检查返回请求数据的status_code是否为0 if resp.json()["base_resp"]["status_code"] == 0: - data = resp.json()["data"]["audio"] + data = resp.json()['data']['audio'] file_to_save = open(output_file, "wb") file_to_save.write(bytes.fromhex(data)) else: - raise Exception( - f"{__name__} status_code: {resp.status_code} response: {resp.content}" - ) + raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}") except Exception as e: - raise Exception(f"{__name__} error: {e}") + raise Exception(f"{__name__} error: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/openai.py b/main/xiaozhi-server/core/providers/tts/openai.py index a5d48057f..1849c128e 100644 --- a/main/xiaozhi-server/core/providers/tts/openai.py +++ b/main/xiaozhi-server/core/providers/tts/openai.py @@ -4,11 +4,6 @@ import requests from datetime import datetime from core.utils.util import check_model_key from core.providers.tts.base import TTSProviderBase -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): @@ -16,38 +11,30 @@ class TTSProvider(TTSProviderBase): self.api_key = config.get("api_key") self.api_url = config.get("api_url", "https://api.openai.com/v1/audio/speech") self.model = config.get("model", "tts-1") - if config.get("private_voice"): - self.voice = config.get("private_voice") - else: - self.voice = config.get("voice", "alloy") + self.voice = config.get("voice", "alloy") self.response_format = "wav" - self.speed = float(config.get("speed", 1.0)) + self.speed = config.get("speed", 1.0) self.output_file = config.get("output_dir", "tmp/") check_model_key("TTS", self.api_key) def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): headers = { "Authorization": f"Bearer {self.api_key}", - "Content-Type": "application/json", + "Content-Type": "application/json" } data = { "model": self.model, "input": text, "voice": self.voice, "response_format": "wav", - "speed": self.speed, + "speed": self.speed } response = requests.post(self.api_url, json=data, headers=headers) if response.status_code == 200: with open(output_file, "wb") as audio_file: audio_file.write(response.content) else: - raise Exception( - f"OpenAI TTS请求失败: {response.status_code} - {response.text}" - ) + raise Exception(f"OpenAI TTS请求失败: {response.status_code} - {response.text}") diff --git a/main/xiaozhi-server/core/providers/tts/siliconflow.py b/main/xiaozhi-server/core/providers/tts/siliconflow.py index b2f564cc4..4c0cc3562 100644 --- a/main/xiaozhi-server/core/providers/tts/siliconflow.py +++ b/main/xiaozhi-server/core/providers/tts/siliconflow.py @@ -10,23 +10,17 @@ class TTSProvider(TTSProviderBase): super().__init__(config, delete_audio_file) self.model = config.get("model") self.access_token = config.get("access_token") - if config.get("private_voice"): - self.voice = config.get("private_voice") - else: - self.voice = config.get("voice") + self.voice = config.get("voice") self.response_format = config.get("response_format") self.sample_rate = config.get("sample_rate") - self.speed = float(config.get("speed", 1.0)) + self.speed = config.get("speed") self.gain = config.get("gain") self.host = "api.siliconflow.cn" self.api_url = f"https://{self.host}/v1/audio/speech" def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): request_json = { @@ -37,11 +31,9 @@ class TTSProvider(TTSProviderBase): } headers = { "Authorization": f"Bearer {self.access_token}", - "Content-Type": "application/json", + "Content-Type": "application/json" } - response = requests.request( - "POST", self.api_url, json=request_json, headers=headers - ) + response = requests.request("POST", self.api_url, json=request_json, headers=headers) data = response.content file_to_save = open(output_file, "wb") file_to_save.write(data) diff --git a/main/xiaozhi-server/core/providers/tts/tencent.py b/main/xiaozhi-server/core/providers/tts/tencent.py index f2501e2fc..ed4db622b 100644 --- a/main/xiaozhi-server/core/providers/tts/tencent.py +++ b/main/xiaozhi-server/core/providers/tts/tencent.py @@ -16,10 +16,7 @@ class TTSProvider(TTSProviderBase): self.appid = config.get("appid") self.secret_id = config.get("secret_id") self.secret_key = config.get("secret_key") - if config.get("private_voice"): - self.voice = config.get("private_voice") - else: - self.voice = int(config.get("voice")) + self.voice = config.get("voice") self.api_url = "https://tts.tencentcloudapi.com" # 正确的API端点 self.region = config.get("region") self.output_file = config.get("output_dir") @@ -28,36 +25,35 @@ class TTSProvider(TTSProviderBase): """生成鉴权请求头""" # 获取当前UTC时间戳 timestamp = int(time.time()) - + # 使用UTC时间计算日期 - utc_date = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime( - "%Y-%m-%d" - ) - + utc_date = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime('%Y-%m-%d') + # 服务名称必须是 "tts" service = "tts" - + # 拼接凭证范围 credential_scope = f"{utc_date}/{service}/tc3_request" - + # 使用TC3-HMAC-SHA256签名方法 algorithm = "TC3-HMAC-SHA256" - + # 构建规范请求字符串 http_request_method = "POST" canonical_uri = "/" canonical_querystring = "" - + # 请求头必须包含host和content-type,且按字典序排列 canonical_headers = ( - f"content-type:application/json\n" f"host:tts.tencentcloudapi.com\n" + f"content-type:application/json\n" + f"host:tts.tencentcloudapi.com\n" ) signed_headers = "content-type;host" - + # 请求体哈希值 payload = json.dumps(request_body) - payload_hash = hashlib.sha256(payload.encode("utf-8")).hexdigest() - + payload_hash = hashlib.sha256(payload.encode('utf-8')).hexdigest() + # 构建规范请求字符串 canonical_request = ( f"{http_request_method}\n" @@ -67,12 +63,10 @@ class TTSProvider(TTSProviderBase): f"{signed_headers}\n" f"{payload_hash}" ) - + # 计算规范请求的哈希值 - hashed_canonical_request = hashlib.sha256( - canonical_request.encode("utf-8") - ).hexdigest() - + hashed_canonical_request = hashlib.sha256(canonical_request.encode('utf-8')).hexdigest() + # 构建待签名字符串 string_to_sign = ( f"{algorithm}\n" @@ -80,19 +74,19 @@ class TTSProvider(TTSProviderBase): f"{credential_scope}\n" f"{hashed_canonical_request}" ) - + # 计算签名密钥 - secret_date = self._hmac_sha256( - f"TC3{self.secret_key}".encode("utf-8"), utc_date - ) + secret_date = self._hmac_sha256(f"TC3{self.secret_key}".encode('utf-8'), utc_date) secret_service = self._hmac_sha256(secret_date, service) secret_signing = self._hmac_sha256(secret_service, "tc3_request") - + # 计算签名 signature = hmac.new( - secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256 + secret_signing, + string_to_sign.encode('utf-8'), + hashlib.sha256 ).hexdigest() - + # 构建授权头 authorization = ( f"{algorithm} " @@ -100,7 +94,7 @@ class TTSProvider(TTSProviderBase): f"SignedHeaders={signed_headers}, " f"Signature={signature}" ) - + # 构建请求头 headers = { "Content-Type": "application/json", @@ -110,22 +104,19 @@ class TTSProvider(TTSProviderBase): "X-TC-Timestamp": str(timestamp), "X-TC-Version": "2019-08-23", "X-TC-Region": self.region, - "X-TC-Language": "zh-CN", + "X-TC-Language": "zh-CN" } - + return headers - + def _hmac_sha256(self, key, msg): """HMAC-SHA256加密""" if isinstance(msg, str): - msg = msg.encode("utf-8") + msg = msg.encode('utf-8') return hmac.new(key, msg, hashlib.sha256).digest() def generate_filename(self, extension=".wav"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): # 构建请求体 @@ -138,23 +129,19 @@ class TTSProvider(TTSProviderBase): try: # 获取请求头(每次请求都重新生成,以确保时间戳和签名是最新的) headers = self._get_auth_headers(request_json) - + # 发送请求 - resp = requests.post( - self.api_url, json.dumps(request_json), headers=headers - ) - + resp = requests.post(self.api_url, json.dumps(request_json), headers=headers) + # 检查响应 if resp.status_code == 200: response_data = resp.json() - + # 检查是否成功 if response_data.get("Response", {}).get("Error") is not None: error_info = response_data["Response"]["Error"] - raise Exception( - f"API返回错误: {error_info['Code']}: {error_info['Message']}" - ) - + raise Exception(f"API返回错误: {error_info['Code']}: {error_info['Message']}") + # 提取音频数据 audio_data = response_data["Response"].get("Audio") if audio_data: @@ -164,8 +151,6 @@ class TTSProvider(TTSProviderBase): else: raise Exception(f"{__name__}: 没有返回音频数据: {response_data}") else: - raise Exception( - f"{__name__} status_code: {resp.status_code} response: {resp.content}" - ) + raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}") except Exception as e: - raise Exception(f"{__name__} error: {e}") + raise Exception(f"{__name__} error: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/ttson.py b/main/xiaozhi-server/core/providers/tts/ttson.py index c2b78557b..e9fee1091 100644 --- a/main/xiaozhi-server/core/providers/tts/ttson.py +++ b/main/xiaozhi-server/core/providers/tts/ttson.py @@ -10,62 +10,48 @@ from core.providers.tts.base import TTSProviderBase class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) - self.url = config.get( - "url", - "https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=", - ) - if config.get("private_voice"): - self.voice_id = int(config.get("private_voice")) - else: - self.voice_id = int(config.get("voice_id", 1695)) + self.url = config.get("url", "https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=") + self.voice_id = config.get("voice_id", 1695) self.token = config.get("token") self.to_lang = config.get("to_lang") - self.volume_change_dB = int(config.get("volume_change_dB", 0)) - self.speed_factor = int(config.get("speed_factor", 1)) - self.stream = str(config.get("stream", False)).lower() in ("true", "1", "yes") + self.volume_change_dB = config.get("volume_change_dB", 0) + self.speed_factor = config.get("speed_factor", 1) + self.stream = config.get("stream", False) self.output_file = config.get("output_dir") - self.pitch_factor = int(config.get("pitch_factor", 0)) + self.pitch_factor = config.get("pitch_factor", 0) self.format = config.get("format", "mp3") - self.emotion = int(config.get("emotion", 1)) - self.header = {"Content-Type": "application/json"} + self.emotion = config.get("emotion", 1) + self.header = { + "Content-Type": "application/json" + } def generate_filename(self, extension=".mp3"): - return os.path.join( - self.output_file, - f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", - ) + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") async def text_to_speak(self, text, output_file): - url = f"{self.url}{self.token}" + url = f'{self.url}{self.token}' result = "firefly" - payload = json.dumps( - { - "to_lang": self.to_lang, - "text": text, - "emotion": self.emotion, - "format": self.format, - "volume_change_dB": self.volume_change_dB, - "voice_id": self.voice_id, - "pitch_factor": self.pitch_factor, - "speed_factor": self.speed_factor, - "token": self.token, - } - ) + payload = json.dumps({ + "to_lang": self.to_lang, + "text": text, + "emotion": self.emotion, + "format": self.format, + "volume_change_dB": self.volume_change_dB, + "voice_id": self.voice_id, + "pitch_factor": self.pitch_factor, + "speed_factor": self.speed_factor, + "token": self.token + }) resp = requests.request("POST", url, data=payload) if resp.status_code != 200: return None resp_json = resp.json() try: - result = ( - resp_json["url"] - + ":" - + str(resp_json["port"]) - + "/flashsummary/retrieveFileData?stream=True&token=" - + self.token - + "&voice_audio_path=" - + resp_json["voice_path"] - ) + result = resp_json['url'] + ':' + str( + resp_json[ + 'port']) + '/flashsummary/retrieveFileData?stream=True&token=' + self.token + '&voice_audio_path=' + \ + resp_json['voice_path'] except Exception as e: print("error:", e) diff --git a/main/xiaozhi-server/core/utils/auth_code_gen.py b/main/xiaozhi-server/core/utils/auth_code_gen.py new file mode 100644 index 000000000..c61024dd7 --- /dev/null +++ b/main/xiaozhi-server/core/utils/auth_code_gen.py @@ -0,0 +1,97 @@ +import random +import threading +import time +from typing import Set + +class AuthCodeGenerator: + _instance = None + _instance_lock = threading.Lock() + + def __new__(cls): + if not cls._instance: + with cls._instance_lock: + if not cls._instance: + cls._instance = super(AuthCodeGenerator, cls).__new__(cls) + # 初始化随机种子 + random.seed(time.time()) + return cls._instance + + def __init__(self): + # 确保 __init__ 只被调用一次 + if not hasattr(self, '_initialized'): + self._used_codes: Set[str] = set() + self._code_timestamps = {} + self._lock = threading.Lock() + self._code_timeout = 3 * 24 * 60 * 60 + self._initialized = True + + @classmethod + def get_instance(cls): + """获取AuthCodeGenerator的单例实例""" + return cls() + + def generate_code(self) -> str: + """ + 生成6位数字认证码,确保不重复 + 返回: 6位数字字符串 + """ + with self._lock: + self._clean_expired_codes() # 清理过期code + while True: + # 使用时间戳和已用码数量作为种子,确保每次生成不同的随机数 + seed = int(time.time() * 1000) + len(self._used_codes) + random.seed(seed) + + # 生成6位随机数字 + code = ''.join(str(random.randint(0, 9)) for _ in range(6)) + + # 检查是否已存在 + if code not in self._used_codes: + self._used_codes.add(code) + self._code_timestamps[code] = time.time() + return code + + def remove_code(self, code: str) -> bool: + """ + 删除已使用的认证码 + 参数: + code: 要删除的认证码 + 返回: + bool: 删除成功返回True,码不存在返回False + """ + print('remove_code', code) + with self._lock: + if code in self._used_codes: + self._used_codes.remove(code) + if code in self._code_timestamps: + del self._code_timestamps[code] + return True + return False + + def is_code_used(self, code: str) -> bool: + """ + 检查认证码是否已被使用 + 参数: + code: 要检查的认证码 + 返回: + bool: 如果码存在返回True,否则返回False + """ + with self._lock: + return code in self._used_codes + + def clear_codes(self): + """清空所有已使用的认证码""" + with self._lock: + self._used_codes.clear() + self._code_timestamps.clear() + + def _clean_expired_codes(self): + """清理过期的认证码""" + current_time = time.time() + expired_codes = [ + code for code, timestamp in self._code_timestamps.items() + if (current_time - timestamp) > self._code_timeout + ] + for code in expired_codes: + self._used_codes.remove(code) + del self._code_timestamps[code] diff --git a/main/xiaozhi-server/core/utils/lock_manager.py b/main/xiaozhi-server/core/utils/lock_manager.py new file mode 100644 index 000000000..f1db6fc73 --- /dev/null +++ b/main/xiaozhi-server/core/utils/lock_manager.py @@ -0,0 +1,39 @@ +import asyncio +from typing import Dict +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +class FileLockManager: + _instance = None + _locks: Dict[str, asyncio.Lock] = {} + + def __new__(cls): + if cls._instance is None: + cls._instance = super(FileLockManager, cls).__new__(cls) + return cls._instance + + @classmethod + def get_lock(cls, file_path: str) -> asyncio.Lock: + """获取指定文件的锁""" + if file_path not in cls._locks: + cls._locks[file_path] = asyncio.Lock() + return cls._locks[file_path] + + @classmethod + async def acquire_lock(cls, file_path: str): + """获取锁""" + lock = cls.get_lock(file_path) + await lock.acquire() + logger.bind(tag=TAG).debug(f"Acquired lock for {file_path}") + + @classmethod + def release_lock(cls, file_path: str): + """释放锁""" + if file_path in cls._locks: + try: + cls._locks[file_path].release() + logger.bind(tag=TAG).debug(f"Released lock for {file_path}") + except RuntimeError as e: + logger.bind(tag=TAG).warning(f"Failed to release lock for {file_path}: {e}") diff --git a/main/xiaozhi-server/core/utils/memory.py b/main/xiaozhi-server/core/utils/memory.py index ff43b220c..c750e9aa7 100644 --- a/main/xiaozhi-server/core/utils/memory.py +++ b/main/xiaozhi-server/core/utils/memory.py @@ -2,17 +2,16 @@ import os import sys import importlib from config.logger import setup_logging +from core.utils.util import read_config, get_project_dir logger = setup_logging() - def create_instance(class_name, *args, **kwargs): - if os.path.exists( - os.path.join("core", "providers", "memory", class_name, f"{class_name}.py") - ): - lib_name = f"core.providers.memory.{class_name}.{class_name}" + if os.path.exists(os.path.join('core', 'providers', 'memory', class_name, f'{class_name}.py')): + lib_name = f'core.providers.memory.{class_name}.{class_name}' if lib_name not in sys.modules: - sys.modules[lib_name] = importlib.import_module(f"{lib_name}") + sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].MemoryProvider(*args, **kwargs) raise ValueError(f"不支持的记忆服务类型: {class_name}") + diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index e9e6795a8..14d71fb20 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -1,12 +1,19 @@ +import os import json +import yaml import socket import subprocess +import logging import re import requests -from typing import Dict, Any -from core.utils import tts, llm, intent, memory, vad, asr -TAG = __name__ + +def get_project_dir(): + """获取项目根目录""" + return ( + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + "/" + ) def get_local_ip(): @@ -65,7 +72,7 @@ def is_private_ip(ip_addr): return False # IP address format error or insufficient segments -def get_ip_info(ip_addr, logger): +def get_ip_info(ip_addr): try: if is_private_ip(ip_addr): ip_addr = "" @@ -74,10 +81,16 @@ def get_ip_info(ip_addr, logger): ip_info = {"city": resp.get("city")} return ip_info except Exception as e: - logger.bind(tag=TAG).error(f"Error getting client ip info: {e}") + logging.error(f"Error getting client ip info: {e}") return {} +def read_config(config_path): + with open(config_path, "r", encoding="utf-8") as file: + config = yaml.safe_load(file) + return config + + def write_json_file(file_path, data): """将数据写入 JSON 文件""" with open(file_path, "w", encoding="utf-8") as file: @@ -156,31 +169,15 @@ def remove_punctuation_and_length(text): def check_model_key(modelType, modelKey): if "你" in modelKey: - raise ValueError( - "你还没配置" + modelType + "的密钥,请检查一下所使用的LLM是否配置了密钥" + logging.error( + "你还没配置" + + modelType + + "的密钥,请在配置文件中配置密钥,否则无法正常工作" ) return False return True -def parse_string_to_list(value, separator=";"): - """ - 将输入值转换为列表 - Args: - value: 输入值,可以是 None、字符串或列表 - separator: 分隔符,默认为分号 - Returns: - list: 处理后的列表 - """ - if value is None or value == "": - return [] - elif isinstance(value, str): - return [item.strip() for item in value.split(separator) if item.strip()] - elif isinstance(value, list): - return value - return [] - - def check_ffmpeg_installed(): ffmpeg_installed = False try: @@ -211,122 +208,7 @@ def check_ffmpeg_installed(): def extract_json_from_string(input_string): """提取字符串中的 JSON 部分""" pattern = r"(\{.*\})" - match = re.search(pattern, input_string, re.DOTALL) #添加 re.DOTALL + match = re.search(pattern, input_string) if match: return match.group(1) # 返回提取的 JSON 字符串 return None - - -def initialize_modules( - logger, - config: Dict[str, Any], - init_vad=False, - init_asr=False, - init_llm=False, - init_tts=False, - init_memory=False, - init_intent=False, -) -> Dict[str, Any]: - """ - 初始化所有模块组件 - - Args: - config: 配置字典 - - Returns: - Dict[str, Any]: 包含所有初始化后的模块的字典 - """ - modules = {} - - # 初始化TTS模块 - if init_tts: - select_tts_module = config["selected_module"]["TTS"] - tts_type = ( - select_tts_module - if "type" not in config["TTS"][select_tts_module] - else config["TTS"][select_tts_module]["type"] - ) - modules["tts"] = tts.create_instance( - tts_type, - config["TTS"][select_tts_module], - str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"), - ) - logger.bind(tag=TAG).info(f"初始化组件: tts成功 {select_tts_module}") - - # 初始化LLM模块 - if init_llm: - select_llm_module = config["selected_module"]["LLM"] - llm_type = ( - select_llm_module - if "type" not in config["LLM"][select_llm_module] - else config["LLM"][select_llm_module]["type"] - ) - modules["llm"] = llm.create_instance( - llm_type, - config["LLM"][select_llm_module], - ) - logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}") - - # 初始化Intent模块 - if init_intent: - select_intent_module = config["selected_module"]["Intent"] - intent_type = ( - select_intent_module - if "type" not in config["Intent"][select_intent_module] - else config["Intent"][select_intent_module]["type"] - ) - modules["intent"] = intent.create_instance( - intent_type, - config["Intent"][select_intent_module], - ) - logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}") - - # 初始化Memory模块 - if init_memory: - select_memory_module = config["selected_module"]["Memory"] - memory_type = ( - select_memory_module - if "type" not in config["Memory"][select_memory_module] - else config["Memory"][select_memory_module]["type"] - ) - modules["memory"] = memory.create_instance( - memory_type, - config["Memory"][select_memory_module], - ) - logger.bind(tag=TAG).info(f"初始化组件: memory成功 {select_memory_module}") - - # 初始化VAD模块 - if init_vad: - select_vad_module = config["selected_module"]["VAD"] - vad_type = ( - select_vad_module - if "type" not in config["VAD"][select_vad_module] - else config["VAD"][select_vad_module]["type"] - ) - modules["vad"] = vad.create_instance( - vad_type, - config["VAD"][select_vad_module], - ) - logger.bind(tag=TAG).info(f"初始化组件: vad成功 {select_vad_module}") - - # 初始化ASR模块 - if init_asr: - select_asr_module = config["selected_module"]["ASR"] - asr_type = ( - select_asr_module - if "type" not in config["ASR"][select_asr_module] - else config["ASR"][select_asr_module]["type"] - ) - modules["asr"] = asr.create_instance( - asr_type, - config["ASR"][select_asr_module], - str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"), - ) - logger.bind(tag=TAG).info(f"初始化组件: asr成功 {select_asr_module}") - - # 初始化自定义prompt - if config.get("prompt", None) is not None: - modules["prompt"] = config["prompt"] - logger.bind(tag=TAG).info(f"初始化组件: prompt成功 {modules['prompt'][:50]}...") - - return modules diff --git a/main/xiaozhi-server/core/utils/vad.py b/main/xiaozhi-server/core/utils/vad.py index b1dd1faf8..2079b3540 100644 --- a/main/xiaozhi-server/core/utils/vad.py +++ b/main/xiaozhi-server/core/utils/vad.py @@ -1,19 +1,77 @@ -import importlib -import os -import sys -from core.providers.vad.base import VADProviderBase +from abc import ABC, abstractmethod from config.logger import setup_logging +import opuslib_next +import time +import numpy as np +import torch TAG = __name__ logger = setup_logging() +class VAD(ABC): + @abstractmethod + def is_vad(self, conn, data): + """检测音频数据中的语音活动""" + pass -def create_instance(class_name: str, *args, **kwargs) -> VADProviderBase: - """工厂方法创建VAD实例""" - if os.path.exists(os.path.join("core", "providers", "vad", f"{class_name}.py")): - lib_name = f"core.providers.vad.{class_name}" - if lib_name not in sys.modules: - sys.modules[lib_name] = importlib.import_module(f"{lib_name}") - return sys.modules[lib_name].VADProvider(*args, **kwargs) - raise ValueError(f"不支持的VAD类型: {class_name},请检查该配置的type是否设置正确") +class SileroVAD(VAD): + def __init__(self, config): + logger.bind(tag=TAG).info("SileroVAD", config) + self.model, self.utils = torch.hub.load(repo_or_dir=config["model_dir"], + source='local', + model='silero_vad', + force_reload=False) + (get_speech_timestamps, _, _, _, _) = self.utils + + self.decoder = opuslib_next.Decoder(16000, 1) + self.vad_threshold = config.get("threshold") + self.silence_threshold_ms = config.get("min_silence_duration_ms") + + def is_vad(self, conn, opus_packet): + try: + pcm_frame = self.decoder.decode(opus_packet, 960) + conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区 + + # 处理缓冲区中的完整帧(每次处理512采样点) + client_have_voice = False + while len(conn.client_audio_buffer) >= 512 * 2: + # 提取前512个采样点(1024字节) + chunk = conn.client_audio_buffer[:512 * 2] + conn.client_audio_buffer = conn.client_audio_buffer[512 * 2:] + + # 转换为模型需要的张量格式 + audio_int16 = np.frombuffer(chunk, dtype=np.int16) + audio_float32 = audio_int16.astype(np.float32) / 32768.0 + audio_tensor = torch.from_numpy(audio_float32) + + # 检测语音活动 + speech_prob = self.model(audio_tensor, 16000).item() + client_have_voice = speech_prob >= self.vad_threshold + + # 如果之前有声音,但本次没有声音,且与上次有声音的时间查已经超过了静默阈值,则认为已经说完一句话 + if conn.client_have_voice and not client_have_voice: + stop_duration = time.time() * 1000 - conn.client_have_voice_last_time + if stop_duration >= self.silence_threshold_ms: + conn.client_voice_stop = True + if client_have_voice: + conn.client_have_voice = True + conn.client_have_voice_last_time = time.time() * 1000 + + return client_have_voice + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).info(f"解码错误: {e}") + except Exception as e: + logger.bind(tag=TAG).error(f"Error processing audio packet: {e}") + + +def create_instance(class_name, *args, **kwargs) -> VAD: + # 获取类对象 + cls_map = { + "SileroVAD": SileroVAD, + # 可扩展其他SileroVAD实现 + } + + if cls := cls_map.get(class_name): + return cls(*args, **kwargs) + raise ValueError(f"不支持的SileroVAD类型: {class_name}") diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index cb4dee08a..98b601339 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -2,7 +2,8 @@ import asyncio import websockets from config.logger import setup_logging from core.connection import ConnectionHandler -from core.utils.util import get_local_ip, initialize_modules +from core.utils.util import get_local_ip +from core.utils import asr, vad, llm, tts, memory, intent TAG = __name__ @@ -11,21 +12,79 @@ class WebSocketServer: def __init__(self, config: dict): self.config = config self.logger = setup_logging() - modules = initialize_modules( - self.logger, self.config, True, True, True, True, True, True + self._vad, self._asr, self._llm, self._tts, self._memory, self.intent = ( + self._create_processing_instances() + ) + self.active_connections = set() # 添加全局连接记录 + + def _create_processing_instances(self): + memory_cls_name = self.config["selected_module"].get( + "Memory", "nomem" + ) # 默认使用nomem + has_memory_cfg = ( + self.config.get("Memory") and memory_cls_name in self.config["Memory"] + ) + memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {} + + """创建处理模块实例""" + return ( + vad.create_instance( + self.config["selected_module"]["VAD"], + self.config["VAD"][self.config["selected_module"]["VAD"]], + ), + asr.create_instance( + ( + self.config["selected_module"]["ASR"] + if not "type" + in self.config["ASR"][self.config["selected_module"]["ASR"]] + else self.config["ASR"][self.config["selected_module"]["ASR"]][ + "type" + ] + ), + self.config["ASR"][self.config["selected_module"]["ASR"]], + self.config["delete_audio"], + ), + llm.create_instance( + ( + self.config["selected_module"]["LLM"] + if not "type" + in self.config["LLM"][self.config["selected_module"]["LLM"]] + else self.config["LLM"][self.config["selected_module"]["LLM"]][ + "type" + ] + ), + self.config["LLM"][self.config["selected_module"]["LLM"]], + ), + tts.create_instance( + ( + self.config["selected_module"]["TTS"] + if not "type" + in self.config["TTS"][self.config["selected_module"]["TTS"]] + else self.config["TTS"][self.config["selected_module"]["TTS"]][ + "type" + ] + ), + self.config["TTS"][self.config["selected_module"]["TTS"]], + self.config["delete_audio"], + ), + memory.create_instance(memory_cls_name, memory_cfg), + intent.create_instance( + ( + self.config["selected_module"]["Intent"] + if not "type" + in self.config["Intent"][self.config["selected_module"]["Intent"]] + else self.config["Intent"][ + self.config["selected_module"]["Intent"] + ]["type"] + ), + self.config["Intent"][self.config["selected_module"]["Intent"]], + ), ) - self._vad = modules["vad"] - self._asr = modules["asr"] - self._tts = modules["tts"] - self._llm = modules["llm"] - self._intent = modules["intent"] - self._memory = modules["memory"] - self.active_connections = set() async def start(self): server_config = self.config["server"] host = server_config["ip"] - port = int(server_config.get("port", 8000)) + port = server_config["port"] self.logger.bind(tag=TAG).info( "Server is running at ws://{}:{}/xiaozhi/v1/", get_local_ip(), port @@ -52,7 +111,7 @@ class WebSocketServer: self._llm, self._tts, self._memory, - self._intent, + self.intent, ) self.active_connections.add(handler) try: diff --git a/main/xiaozhi-server/docker-compose.yml b/main/xiaozhi-server/docker-compose.yml index 34bd1c3e4..609fcbc11 100644 --- a/main/xiaozhi-server/docker-compose.yml +++ b/main/xiaozhi-server/docker-compose.yml @@ -1,4 +1,16 @@ -# Docker安装Server +# 1、安装mysql +# |- 如果本机已经安装了MySQL,可以直接在数据库中创建名为`xiaozhi_esp32_server`的数据库。 +# |- 如果还没有MySQL,你可以通过docker安装mysql,执行以下一句话 +# |- docker run --name xiaozhi-esp32-server-db -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -e MYSQL_DATABASE=xiaozhi_esp32_server -e MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci" -d mysql:latest +# |- 如果你的mysql账号和密码有修改过,记得修改下方数据库的账号和密码 +# |- 记得修改下方SPRING_DATASOURCE_DRUID_URL的IP,ip不能写127.0.0.1或localhost,否则容器无法访问,要写你电脑局域网ip + +# 2、安装redis +# |- 如果本机已经安装了Redis,看一下你安装的redis端口、密码,然后修改下方redis的地址和端口 +# |- 如果还没有Redis,你可以通过docker安装redis,执行以下一句话 +# |- docker run --name xiaozhi-esp32-server-redis -d -p 6379:6379 redis +# |- 记得修改SPRING_DATA_REDIS_HOST的IP,ip不能写127.0.0.1或localhost,否则容器无法访问,要写你电脑局域网ip + version: '3' services: @@ -17,4 +29,20 @@ services: # 配置文件目录 - ./data:/opt/xiaozhi-esp32-server/data # 模型文件挂接,很重要 - - ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt \ No newline at end of file + - ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt + +# #智控台还没开发好,还不能完全使用,会报很多错误,如果是非技术人员,请不要启用智控台服务 +# xiaozhi-esp32-server-web: +# image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest +# container_name: xiaozhi-esp32-server-web +# restart: always +# ports: +# - "8002:8002" +# environment: +# - TZ=Asia/Shanghai +# ##记得改mysql和redis IP 密码 +# - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://192.168.1.20:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai +# - SPRING_DATASOURCE_DRUID_USERNAME=root +# - SPRING_DATASOURCE_DRUID_PASSWORD=123456 +# - SPRING_DATA_REDIS_HOST=192.168.1.20 +# - SPRING_DATA_REDIS_PORT=6379 diff --git a/main/xiaozhi-server/performance_tester.py b/main/xiaozhi-server/performance_tester.py index 38daea009..8bae2df09 100644 --- a/main/xiaozhi-server/performance_tester.py +++ b/main/xiaozhi-server/performance_tester.py @@ -5,8 +5,9 @@ from tabulate import tabulate from typing import Dict, List from core.utils.llm import create_instance as create_llm_instance from core.utils.tts import create_instance as create_tts_instance +from core.utils.util import read_config import statistics -from config.settings import load_config +from config.settings import get_config_file import inspect import os import logging @@ -17,16 +18,17 @@ logging.basicConfig(level=logging.WARNING) class AsyncPerformanceTester: def __init__(self): - self.config = load_config() + self.config = read_config(get_config_file()) self.test_sentences = self.config.get("module_test", {}).get( "test_sentences", - [ - "你好,请介绍一下你自己", - "What's the weather like today?", - "请用100字概括量子计算的基本原理和应用前景", - ], + ["你好,请介绍一下你自己", "What's the weather like today?", + "请用100字概括量子计算的基本原理和应用前景"] ) - self.results = {"llm": {}, "tts": {}, "combinations": []} + self.results = { + "llm": {}, + "tts": {}, + "combinations": [] + } async def _check_ollama_service(self, base_url: str, model_name: str) -> bool: """异步检查Ollama服务状态""" @@ -44,9 +46,7 @@ class AsyncPerformanceTester: data = await response.json() models = data.get("models", []) if not any(model["name"] == model_name for model in models): - print( - f"🚫 Ollama模型 {model_name} 未找到,请先使用 ollama pull {model_name} 下载" - ) + print(f"🚫 Ollama模型 {model_name} 未找到,请先使用 ollama pull {model_name} 下载") return False else: print(f"🚫 无法获取Ollama模型列表") @@ -62,16 +62,17 @@ class AsyncPerformanceTester: logging.getLogger("core.providers.tts.base").setLevel(logging.WARNING) token_fields = ["access_token", "api_key", "token"] - if any( - field in config - and any(x in config[field] for x in ["你的", "placeholder"]) - for field in token_fields - ): + if any(field in config and any(x in config[field] for x in ["你的", "placeholder"]) for field in + token_fields): print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过") return {"name": tts_name, "type": "tts", "errors": 1} - module_type = config.get("type", tts_name) - tts = create_tts_instance(module_type, config, delete_audio_file=True) + module_type = config.get('type', tts_name) + tts = create_tts_instance( + module_type, + config, + delete_audio_file=True + ) print(f"🎵 测试 TTS: {tts_name}") @@ -102,7 +103,7 @@ class AsyncPerformanceTester: "name": tts_name, "type": "tts", "avg_time": total_time / test_count, - "errors": 0, + "errors": 0 } except Exception as e: @@ -114,8 +115,8 @@ class AsyncPerformanceTester: try: # 对于Ollama,跳过api_key检查并进行特殊处理 if llm_name == "Ollama": - base_url = config.get("base_url", "http://localhost:11434") - model_name = config.get("model_name") + base_url = config.get('base_url', 'http://localhost:11434') + model_name = config.get('model_name') if not model_name: print(f"🚫 Ollama未配置model_name") return {"name": llm_name, "type": "llm", "errors": 1} @@ -123,27 +124,21 @@ class AsyncPerformanceTester: if not await self._check_ollama_service(base_url, model_name): return {"name": llm_name, "type": "llm", "errors": 1} else: - if "api_key" in config and any( - x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"] - ): + if "api_key" in config and any(x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]): print(f"🚫 跳过未配置的LLM: {llm_name}") return {"name": llm_name, "type": "llm", "errors": 1} # 获取实际类型(兼容旧配置) - module_type = config.get("type", llm_name) + module_type = config.get('type', llm_name) llm = create_llm_instance(module_type, config) # 统一使用UTF-8编码 - test_sentences = [ - s.encode("utf-8").decode("utf-8") for s in self.test_sentences - ] + test_sentences = [s.encode('utf-8').decode('utf-8') for s in self.test_sentences] # 创建所有句子的测试任务 sentence_tasks = [] for sentence in test_sentences: - sentence_tasks.append( - self._test_single_sentence(llm_name, llm, sentence) - ) + sentence_tasks.append(self._test_single_sentence(llm_name, llm, sentence)) # 并发执行所有句子测试 sentence_results = await asyncio.gather(*sentence_tasks) @@ -171,15 +166,9 @@ class AsyncPerformanceTester: "type": "llm", "avg_response": sum(response_times) / len(response_times), "avg_first_token": sum(first_token_times) / len(first_token_times), - "std_first_token": ( - statistics.stdev(first_token_times) - if len(first_token_times) > 1 - else 0 - ), - "std_response": ( - statistics.stdev(response_times) if len(response_times) > 1 else 0 - ), - "errors": 0, + "std_first_token": statistics.stdev(first_token_times) if len(first_token_times) > 1 else 0, + "std_response": statistics.stdev(response_times) if len(response_times) > 1 else 0, + "errors": 0 } except Exception as e: print(f"LLM {llm_name} 测试失败: {str(e)}") @@ -195,10 +184,8 @@ class AsyncPerformanceTester: async def process_response(): nonlocal first_token_received, first_token_time - for chunk in llm.response( - "perf_test", [{"role": "user", "content": sentence}] - ): - if not first_token_received and chunk.strip() != "": + for chunk in llm.response("perf_test", [{"role": "user", "content": sentence}]): + if not first_token_received and chunk.strip() != '': first_token_time = time.time() - sentence_start first_token_received = True print(f"✓ {llm_name} 首个Token: {first_token_time:.3f}s") @@ -212,15 +199,13 @@ class AsyncPerformanceTester: print(f"✓ {llm_name} 完成响应: {response_time:.3f}s") if first_token_time is None: - first_token_time = ( - response_time # 如果没有检测到first token,使用总响应时间 - ) + first_token_time = response_time # 如果没有检测到first token,使用总响应时间 return { "name": llm_name, "type": "llm", "first_token_time": first_token_time, - "response_time": response_time, + "response_time": response_time } except Exception as e: print(f"⚠️ {llm_name} 句子测试失败: {str(e)}") @@ -229,37 +214,24 @@ class AsyncPerformanceTester: def _generate_combinations(self): """生成最佳组合建议""" valid_llms = [ - k - for k, v in self.results["llm"].items() + k for k, v in self.results["llm"].items() if v["errors"] == 0 and v["avg_first_token"] >= 0.05 ] valid_tts = [k for k, v in self.results["tts"].items() if v["errors"] == 0] # 找出基准值 - min_first_token = ( - min([self.results["llm"][llm]["avg_first_token"] for llm in valid_llms]) - if valid_llms - else 1 - ) - min_tts_time = ( - min([self.results["tts"][tts]["avg_time"] for tts in valid_tts]) - if valid_tts - else 1 - ) + min_first_token = min([self.results["llm"][llm]["avg_first_token"] for llm in valid_llms]) if valid_llms else 1 + min_tts_time = min([self.results["tts"][tts]["avg_time"] for tts in valid_tts]) if valid_tts else 1 for llm in valid_llms: for tts in valid_tts: # 计算相对性能分数(越小越好) - llm_score = ( - self.results["llm"][llm]["avg_first_token"] / min_first_token - ) + llm_score = self.results["llm"][llm]["avg_first_token"] / min_first_token tts_score = self.results["tts"][tts]["avg_time"] / min_tts_time # 计算稳定性分数(标准差/平均值,越小越稳定) - llm_stability = ( - self.results["llm"][llm]["std_first_token"] - / self.results["llm"][llm]["avg_first_token"] - ) + llm_stability = self.results["llm"][llm]["std_first_token"] / self.results["llm"][llm][ + "avg_first_token"] # 综合得分(考虑性能和稳定性) # 性能权重0.7,稳定性权重0.3 @@ -268,20 +240,16 @@ class AsyncPerformanceTester: # 总分 = LLM得分(70%) + TTS得分(30%) total_score = llm_final_score * 0.7 + tts_score * 0.3 - self.results["combinations"].append( - { - "llm": llm, - "tts": tts, - "score": total_score, - "details": { - "llm_first_token": self.results["llm"][llm][ - "avg_first_token" - ], - "llm_stability": llm_stability, - "tts_time": self.results["tts"][tts]["avg_time"], - }, + self.results["combinations"].append({ + "llm": llm, + "tts": tts, + "score": total_score, + "details": { + "llm_first_token": self.results["llm"][llm]["avg_first_token"], + "llm_stability": llm_stability, + "tts_time": self.results["tts"][tts]["avg_time"] } - ) + }) # 分数越小越好 self.results["combinations"].sort(key=lambda x: x["score"]) @@ -292,45 +260,42 @@ class AsyncPerformanceTester: for name, data in self.results["llm"].items(): if data["errors"] == 0: stability = data["std_first_token"] / data["avg_first_token"] - llm_table.append( - [ - name, # 不需要固定宽度,让tabulate自己处理对齐 - f"{data['avg_first_token']:.3f}秒", - f"{data['avg_response']:.3f}秒", - f"{stability:.3f}", - ] - ) + llm_table.append([ + name, # 不需要固定宽度,让tabulate自己处理对齐 + f"{data['avg_first_token']:.3f}秒", + f"{data['avg_response']:.3f}秒", + f"{stability:.3f}" + ]) if llm_table: print("\nLLM 性能排行:") - print( - tabulate( - llm_table, - headers=["模型名称", "首字耗时", "总耗时", "稳定性"], - tablefmt="github", - colalign=("left", "right", "right", "right"), - disable_numparse=True, - ) - ) + print(tabulate( + llm_table, + headers=["模型名称", "首字耗时", "总耗时", "稳定性"], + tablefmt="github", + colalign=("left", "right", "right", "right"), + disable_numparse=True + )) else: print("\n⚠️ 没有可用的LLM模块进行测试。") tts_table = [] for name, data in self.results["tts"].items(): if data["errors"] == 0: - tts_table.append([name, f"{data['avg_time']:.3f}秒"]) # 不需要固定宽度 + tts_table.append([ + name, # 不需要固定宽度 + f"{data['avg_time']:.3f}秒" + ]) if tts_table: print("\nTTS 性能排行:") - print( - tabulate( - tts_table, - headers=["模型名称", "合成耗时"], - tablefmt="github", - colalign=("left", "right"), - disable_numparse=True, - ) - ) + print(tabulate( + tts_table, + headers=["模型名称", "合成耗时"], + tablefmt="github", + colalign=("left", "right"), + disable_numparse=True + )) else: print("\n⚠️ 没有可用的TTS模块进行测试。") @@ -338,31 +303,21 @@ class AsyncPerformanceTester: print("\n推荐配置组合 (得分越小越好):") combo_table = [] for combo in self.results["combinations"][:5]: - combo_table.append( - [ - f"{combo['llm']} + {combo['tts']}", # 不需要固定宽度 - f"{combo['score']:.3f}", - f"{combo['details']['llm_first_token']:.3f}秒", - f"{combo['details']['llm_stability']:.3f}", - f"{combo['details']['tts_time']:.3f}秒", - ] - ) + combo_table.append([ + f"{combo['llm']} + {combo['tts']}", # 不需要固定宽度 + f"{combo['score']:.3f}", + f"{combo['details']['llm_first_token']:.3f}秒", + f"{combo['details']['llm_stability']:.3f}", + f"{combo['details']['tts_time']:.3f}秒" + ]) - print( - tabulate( - combo_table, - headers=[ - "组合方案", - "综合得分", - "LLM首字耗时", - "稳定性", - "TTS合成耗时", - ], - tablefmt="github", - colalign=("left", "right", "right", "right", "right"), - disable_numparse=True, - ) - ) + print(tabulate( + combo_table, + headers=["组合方案", "综合得分", "LLM首字耗时", "稳定性", "TTS合成耗时"], + tablefmt="github", + colalign=("left", "right", "right", "right", "right"), + disable_numparse=True + )) else: print("\n⚠️ 没有可用的模块组合建议。") @@ -386,21 +341,18 @@ class AsyncPerformanceTester: for llm_name, config in self.config.get("LLM", {}).items(): # 检查配置有效性 if llm_name == "CozeLLM": - if any(x in config.get("bot_id", "") for x in ["你的"]) or any( - x in config.get("user_id", "") for x in ["你的"] - ): + if any(x in config.get("bot_id", "") for x in ["你的"]) \ + or any(x in config.get("user_id", "") for x in ["你的"]): print(f"⏭️ LLM {llm_name} 未配置bot_id/user_id,已跳过") continue - elif "api_key" in config and any( - x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"] - ): + elif "api_key" in config and any(x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]): print(f"⏭️ LLM {llm_name} 未配置api_key,已跳过") continue # 对于Ollama,先检查服务状态 if llm_name == "Ollama": - base_url = config.get("base_url", "http://localhost:11434") - model_name = config.get("model_name") + base_url = config.get('base_url', 'http://localhost:11434') + model_name = config.get('model_name') if not model_name: print(f"🚫 Ollama未配置model_name") continue @@ -409,33 +361,27 @@ class AsyncPerformanceTester: continue print(f"📋 添加LLM测试任务: {llm_name}") - module_type = config.get("type", llm_name) + module_type = config.get('type', llm_name) llm = create_llm_instance(module_type, config) # 为每个句子创建独立任务 for sentence in self.test_sentences: - sentence = sentence.encode("utf-8").decode("utf-8") + sentence = sentence.encode('utf-8').decode('utf-8') all_tasks.append(self._test_single_sentence(llm_name, llm, sentence)) # TTS测试任务 for tts_name, config in self.config.get("TTS", {}).items(): token_fields = ["access_token", "api_key", "token"] - if any( - field in config - and any(x in config[field] for x in ["你的", "placeholder"]) - for field in token_fields - ): + if any(field in config and any(x in config[field] for x in ["你的", "placeholder"]) for field in + token_fields): print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过") continue print(f"🎵 添加TTS测试任务: {tts_name}") all_tasks.append(self._test_tts(tts_name, config)) print( - f"\n✅ 找到 {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} 个可用LLM模块" - ) - print( - f"✅ 找到 {len([t for t in all_tasks if '_test_tts' in str(t)])} 个可用TTS模块" - ) + f"\n✅ 找到 {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} 个可用LLM模块") + print(f"✅ 找到 {len([t for t in all_tasks if '_test_tts' in str(t)])} 个可用TTS模块") print("\n⏳ 开始并发测试所有模块...\n") # 并发执行所有测试任务 @@ -443,11 +389,7 @@ class AsyncPerformanceTester: # 处理LLM结果 llm_results = {} - for result in [ - r - for r in all_results - if r and isinstance(r, dict) and r.get("type") == "llm" - ]: + for result in [r for r in all_results if r and isinstance(r, dict) and r.get("type") == "llm"]: llm_name = result["name"] if llm_name not in llm_results: llm_results[llm_name] = { @@ -455,11 +397,9 @@ class AsyncPerformanceTester: "type": "llm", "first_token_times": [], "response_times": [], - "errors": 0, + "errors": 0 } - llm_results[llm_name]["first_token_times"].append( - result["first_token_time"] - ) + llm_results[llm_name]["first_token_times"].append(result["first_token_time"]) llm_results[llm_name]["response_times"].append(result["response_time"]) # 计算LLM平均值和标准差 @@ -468,29 +408,16 @@ class AsyncPerformanceTester: self.results["llm"][llm_name] = { "name": llm_name, "type": "llm", - "avg_response": sum(data["response_times"]) - / len(data["response_times"]), - "avg_first_token": sum(data["first_token_times"]) - / len(data["first_token_times"]), - "std_first_token": ( - statistics.stdev(data["first_token_times"]) - if len(data["first_token_times"]) > 1 - else 0 - ), - "std_response": ( - statistics.stdev(data["response_times"]) - if len(data["response_times"]) > 1 - else 0 - ), - "errors": 0, + "avg_response": sum(data["response_times"]) / len(data["response_times"]), + "avg_first_token": sum(data["first_token_times"]) / len(data["first_token_times"]), + "std_first_token": statistics.stdev(data["first_token_times"]) if len( + data["first_token_times"]) > 1 else 0, + "std_response": statistics.stdev(data["response_times"]) if len(data["response_times"]) > 1 else 0, + "errors": 0 } # 处理TTS结果 - for result in [ - r - for r in all_results - if r and isinstance(r, dict) and r.get("type") == "tts" - ]: + for result in [r for r in all_results if r and isinstance(r, dict) and r.get("type") == "tts"]: if result["errors"] == 0: self.results["tts"][result["name"]] = result @@ -506,4 +433,4 @@ async def main(): if __name__ == "__main__": - asyncio.run(main()) + asyncio.run(main()) \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py index affa8af2f..e4769d00e 100644 --- a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py +++ b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py @@ -1,43 +1,34 @@ -from plugins_func.register import register_function, ToolType, ActionResponse, Action +from plugins_func.register import register_function,ToolType, ActionResponse, Action from config.logger import setup_logging TAG = __name__ logger = setup_logging() handle_exit_intent_function_desc = { - "type": "function", - "function": { - "name": "handle_exit_intent", - "description": "当用户想结束对话或需要退出系统时调用", - "parameters": { - "type": "object", - "properties": { - "say_goodbye": { - "type": "string", - "description": "和用户友好结束对话的告别语", + "type": "function", + "function": { + "name": "handle_exit_intent", + "description": "当用户想结束对话或需要退出系统时调用", + "parameters": { + "type": "object", + "properties": { + "say_goodbye": { + "type": "string", + "description": "和用户友好结束对话的告别语" + } + }, + "required": ["say_goodbye"] + } } - }, - "required": ["say_goodbye"], - }, - }, -} + } - -@register_function( - "handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL -) -def handle_exit_intent(conn, say_goodbye: str | None = None): +@register_function('handle_exit_intent', handle_exit_intent_function_desc, ToolType.SYSTEM_CTL) +def handle_exit_intent(conn, say_goodbye: str): # 处理退出意图 try: - if say_goodbye is None: - say_goodbye = "再见,祝您生活愉快!" conn.close_after_chat = True logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}") - return ActionResponse( - action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye - ) + return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye) except Exception as e: logger.bind(tag=TAG).error(f"处理退出意图错误: {e}") - return ActionResponse( - action=Action.NONE, result="退出意图处理失败", response="" - ) + return ActionResponse(action=Action.NONE, result="退出意图处理失败", response="") \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py index 4bd2f2eca..17846cfaf 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_init.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py @@ -9,9 +9,7 @@ HASS_CACHE = {} def append_devices_to_prompt(conn): if conn.use_function_call_mode: - funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get( - "functions", [] - ) + funcs = conn.config["Intent"]["function_call"].get("functions", []) if "hass_get_state" in funcs or "hass_set_state" in funcs: prompt = "下面是我家智能设备,可以通过homeassistant控制\n" devices = conn.config["plugins"]["home_assistant"].get("devices", []) @@ -28,9 +26,7 @@ def initialize_hass_handler(conn): global HASS_CACHE if HASS_CACHE == {}: if conn.use_function_call_mode: - funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get( - "functions", [] - ) + funcs = conn.config["Intent"]["function_call"].get("functions", []) if "hass_get_state" in funcs or "hass_set_state" in funcs: HASS_CACHE["base_url"] = conn.config["plugins"]["home_assistant"].get( "base_url" diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 0b283c8e6..20148b5f5 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -9,7 +9,7 @@ import traceback from pathlib import Path from core.utils import p3 from core.handle.sendAudioHandle import send_stt_message -from plugins_func.register import register_function, ToolType, ActionResponse, Action +from plugins_func.register import register_function,ToolType, ActionResponse, Action TAG = __name__ @@ -18,41 +18,38 @@ logger = setup_logging() MUSIC_CACHE = {} play_music_function_desc = { - "type": "function", - "function": { - "name": "play_music", - "description": "唱歌、听歌、播放音乐的方法。", - "parameters": { - "type": "object", - "properties": { - "song_name": { - "type": "string", - "description": "歌曲名称,如果用户没有指定具体歌名则为'random', 明确指定的时返回音乐的名字 示例: ```用户:播放两只老虎\n参数:两只老虎``` ```用户:播放音乐 \n参数:random ```", + "type": "function", + "function": { + "name": "play_music", + "description": "唱歌、听歌、播放音乐的方法。", + "parameters": { + "type": "object", + "properties": { + "song_name": { + "type": "string", + "description": "歌曲名称,如果用户没有指定具体歌名则为'random', 明确指定的时返回音乐的名字 示例: ```用户:播放两只老虎\n参数:两只老虎``` ```用户:播放音乐 \n参数:random ```" + } + }, + "required": ["song_name"] + } } - }, - "required": ["song_name"], - }, - }, -} + } -@register_function("play_music", play_music_function_desc, ToolType.SYSTEM_CTL) +@register_function('play_music', play_music_function_desc, ToolType.SYSTEM_CTL) def play_music(conn, song_name: str): try: - music_intent = ( - f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐" - ) + music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐" # 检查事件循环状态 if not conn.loop.is_running(): logger.bind(tag=TAG).error("事件循环未运行,无法提交任务") - return ActionResponse( - action=Action.RESPONSE, result="系统繁忙", response="请稍后再试" - ) + return ActionResponse(action=Action.RESPONSE, result="系统繁忙", response="请稍后再试") # 提交异步任务 future = asyncio.run_coroutine_threadsafe( - handle_music_command(conn, music_intent), conn.loop + handle_music_command(conn, music_intent), + conn.loop ) # 非阻塞回调处理 @@ -65,14 +62,10 @@ def play_music(conn, song_name: str): future.add_done_callback(handle_done) - return ActionResponse( - action=Action.NONE, result="指令已接收", response="正在为您播放音乐" - ) + return ActionResponse(action=Action.RESPONSE, result="指令已接收", response="正在为您播放音乐") except Exception as e: logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}") - return ActionResponse( - action=Action.RESPONSE, result=str(e), response="播放音乐时出错了" - ) + return ActionResponse(action=Action.RESPONSE, result=str(e), response="播放音乐时出错了") def _extract_song_name(text): @@ -112,9 +105,7 @@ def get_music_files(music_dir, music_ext): if ext in music_ext: # 添加相对路径 music_files.append(str(file.relative_to(music_dir))) - music_file_names.append( - os.path.splitext(str(file.relative_to(music_dir)))[0] - ) + music_file_names.append(os.path.splitext(str(file.relative_to(music_dir)))[0]) return music_files, music_file_names @@ -126,20 +117,15 @@ def initialize_music_handler(conn): MUSIC_CACHE["music_dir"] = os.path.abspath( MUSIC_CACHE["music_config"].get("music_dir", "./music") # 默认路径修改 ) - MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get( - "music_ext", (".mp3", ".wav", ".p3") - ) - MUSIC_CACHE["refresh_time"] = MUSIC_CACHE["music_config"].get( - "refresh_time", 60 - ) + MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get("music_ext", (".mp3", ".wav", ".p3")) + MUSIC_CACHE["refresh_time"] = MUSIC_CACHE["music_config"].get("refresh_time", 60) else: MUSIC_CACHE["music_dir"] = os.path.abspath("./music") MUSIC_CACHE["music_ext"] = (".mp3", ".wav", ".p3") MUSIC_CACHE["refresh_time"] = 60 # 获取音乐文件列表 - MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files( - MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"] - ) + MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(MUSIC_CACHE["music_dir"], + MUSIC_CACHE["music_ext"]) MUSIC_CACHE["scan_time"] = time.time() return MUSIC_CACHE @@ -149,16 +135,15 @@ async def handle_music_command(conn, text): global MUSIC_CACHE """处理音乐播放指令""" - clean_text = re.sub(r"[^\w\s]", "", text).strip() + clean_text = re.sub(r'[^\w\s]', '', text).strip() logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") # 尝试匹配具体歌名 if os.path.exists(MUSIC_CACHE["music_dir"]): if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]: # 刷新音乐文件列表 - MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = ( - get_music_files(MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"]) - ) + MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(MUSIC_CACHE["music_dir"], + MUSIC_CACHE["music_ext"]) MUSIC_CACHE["scan_time"] = time.time() potential_song = _extract_song_name(clean_text) @@ -173,23 +158,6 @@ async def handle_music_command(conn, text): return True -def _get_random_play_prompt(song_name): - """生成随机播放引导语""" - # 移除文件扩展名 - clean_name = os.path.splitext(song_name)[0] - prompts = [ - f"正在为您播放,{clean_name}", - f"请欣赏歌曲,{clean_name}", - f"即将为您播放,{clean_name}", - f"为您带来,{clean_name}", - f"让我们聆听,{clean_name}", - f"接下来请欣赏,{clean_name}", - f"为您献上,{clean_name}", - ] - # 直接使用random.choice,不设置seed - return random.choice(prompts) - - async def play_local_music(conn, specific_file=None): global MUSIC_CACHE """播放本地音乐文件""" @@ -212,25 +180,16 @@ async def play_local_music(conn, specific_file=None): if not os.path.exists(music_path): logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") return - text = _get_random_play_prompt(selected_music) + text = f"正在播放{selected_music}" await send_stt_message(conn, text) conn.tts_first_text_index = 0 conn.tts_last_text_index = 0 - - tts_file = await asyncio.to_thread(conn.tts.to_tts, text) - if tts_file is not None and os.path.exists(tts_file): - conn.tts_last_text_index = 1 - opus_packets, _ = conn.tts.audio_to_opus_data(tts_file) - conn.audio_play_queue.put((opus_packets, None, 0)) - os.remove(tts_file) - conn.llm_finish_task = True - if music_path.endswith(".p3"): - opus_packets, _ = p3.decode_opus_from_file(music_path) + opus_packets, duration = p3.decode_opus_from_file(music_path) else: - opus_packets, _ = conn.tts.audio_to_opus_data(music_path) - conn.audio_play_queue.put((opus_packets, None, conn.tts_last_text_index)) + opus_packets, duration = conn.tts.audio_to_opus_data(music_path) + conn.audio_play_queue.put((opus_packets, selected_music, 0)) except Exception as e: logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") diff --git a/main/xiaozhi-server/test/abbreviated_version/app.js b/main/xiaozhi-server/test/abbreviated_version/app.js index b22865241..59b756252 100644 --- a/main/xiaozhi-server/test/abbreviated_version/app.js +++ b/main/xiaozhi-server/test/abbreviated_version/app.js @@ -992,9 +992,7 @@ function connectToServer() { if(connectButton.id === "connectButton") { connectButton.textContent = '断开'; - // connectButton.onclick = disconnectFromServer; - connectButton.removeEventListener("click", connectToServer); - connectButton.addEventListener("click", disconnectFromServer); + connectButton.onclick = disconnectFromServer; } if(messageInput.id === "messageInput") { @@ -1013,9 +1011,7 @@ function connectToServer() { if(connectButton.id === "connectButton") { connectButton.textContent = '连接'; - // connectButton.onclick = connectToServer; - connectButton.removeEventListener("click", disconnectFromServer); - connectButton.addEventListener("click", connectToServer); + connectButton.onclick = connectToServer; } if(messageInput.id === "messageInput") { @@ -1179,7 +1175,7 @@ function updateStatus(message, type = 'info') { // 处理文本消息 function handleTextMessage(message) { if (message.type === 'hello') { - console.log(`服务器回应:${JSON.stringify(message, null, 2)}`); + console.log(`服务器回应:${message.message}`); } else if (message.type === 'tts') { // TTS状态消息 if (message.state === 'start') { diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index 65182c4d3..2735fb5af 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -42,50 +42,6 @@ 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 { @@ -114,8 +70,7 @@ cursor: not-allowed; } - #serverUrl, - #otaUrl { + #serverUrl { flex-grow: 1; padding: 8px; border: 1px solid #ddd; @@ -361,76 +316,6 @@ 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; - } @@ -441,56 +326,17 @@
正在加载Opus库...
-
-

- 设备配置 - - MAC: 00:11:22:33:44:55 - 客户端: web_test_client - - -

-
-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
-
- -
-

- 连接信息 - - OTA: ota未连接 - WS: ws未连接 - -

-
- - +

WebSocket连接 未连接

+
+
+

消息发送

@@ -629,36 +475,22 @@ // 日志函数 function log(message, type = 'info') { - // 将消息按换行符分割成多行 - const lines = message.split('\n'); - const now = new Date(); - // const timestamp = `[${now.toLocaleTimeString()}] `; - const timestamp = `[${now.toLocaleTimeString()}.${now.getMilliseconds().toString().padStart(3, '0')}] `; - // 为每一行创建日志条目 - lines.forEach((line, index) => { - const logEntry = document.createElement('div'); - logEntry.className = `log-entry log-${type}`; - // 如果是第一条日志,显示时间戳 - const prefix = index === 0 ? timestamp : ' '.repeat(timestamp.length); - logEntry.textContent = `${prefix}${line}`; - // logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`; - // logEntry.style 保留起始的空格 - logEntry.style.whiteSpace = 'pre'; - if (type === 'error') { - logEntry.style.color = 'red'; - } else if (type === 'debug') { - logEntry.style.color = 'gray'; - return; - } else if (type === 'warning') { - logEntry.style.color = 'orange'; - } else if (type === 'success') { - logEntry.style.color = 'green'; - } else { - logEntry.style.color = 'black'; - } - logContainer.appendChild(logEntry); - }); - + const logEntry = document.createElement('div'); + logEntry.className = `log-entry log-${type}`; + logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`; + if (type === 'error') { + logEntry.style.color = 'red'; + } else if (type === 'debug') { + logEntry.style.color = 'gray'; + return; + } else if (type === 'warning') { + logEntry.style.color = 'orange'; + } else if (type === 'success') { + logEntry.style.color = 'green'; + } else { + logEntry.style.color = 'black'; + } + logContainer.appendChild(logEntry); logContainer.scrollTop = logContainer.scrollHeight; } @@ -708,16 +540,16 @@ // 开始音频缓冲过程 function startAudioBuffering() { if (isAudioBuffering || isAudioPlaying) return; - + isAudioBuffering = true; log("开始音频缓冲...", 'info'); - + // 先尝试初始化解码器,以便在播放时已准备好 initOpusDecoder().catch(error => { log(`预初始化Opus解码器失败: ${error.message}`, 'warning'); // 继续缓冲,我们会在播放时再次尝试初始化 }); - + // 设置超时,如果在一定时间内没有收集到足够的音频包,就开始播放 setTimeout(() => { if (isAudioBuffering && audioBufferQueue.length > 0) { @@ -725,14 +557,14 @@ playBufferedAudio(); } }, 300); // 300ms超时 - + // 监控缓冲进度 const bufferCheckInterval = setInterval(() => { if (!isAudioBuffering) { clearInterval(bufferCheckInterval); return; } - + // 当累积了足够的音频包,开始播放 if (audioBufferQueue.length >= BUFFER_THRESHOLD) { clearInterval(bufferCheckInterval); @@ -745,10 +577,10 @@ // 播放已缓冲的音频 function playBufferedAudio() { if (isAudioPlaying || audioBufferQueue.length === 0) return; - + isAudioPlaying = true; isAudioBuffering = false; - + // 确保Opus解码器已初始化 const initDecoderAndPlay = async () => { try { @@ -759,7 +591,7 @@ }); log('创建音频上下文,采样率: ' + SAMPLE_RATE + 'Hz', 'debug'); } - + // 确保解码器已初始化 if (!opusDecoder) { log('初始化Opus解码器...', 'info'); @@ -775,7 +607,7 @@ return; } } - + // 创建流式播放上下文 if (!streamingContext) { streamingContext = { @@ -785,16 +617,16 @@ source: null, // 当前音频源 totalSamples: 0, // 累积的总样本数 lastPlayTime: 0, // 上次播放的时间戳 - + // 将Opus数据解码为PCM - decodeOpusFrames: async function (opusFrames) { + decodeOpusFrames: async function(opusFrames) { if (!opusDecoder) { log('Opus解码器未初始化,无法解码', 'error'); return; } - + let decodedSamples = []; - + for (const frame of opusFrames) { try { // 使用Opus解码器解码 @@ -808,12 +640,12 @@ log("Opus解码失败: " + error.message, 'error'); } } - + if (decodedSamples.length > 0) { // 添加到解码队列 this.queue.push(...decodedSamples); this.totalSamples += decodedSamples.length; - + // 如果累积了至少0.2秒的音频,开始播放 const minSamples = SAMPLE_RATE * MIN_AUDIO_DURATION; if (!this.playing && this.queue.length >= minSamples) { @@ -823,50 +655,50 @@ log('没有成功解码的样本', 'warning'); } }, - + // 开始播放音频 - startPlaying: function () { + startPlaying: function() { if (this.playing || this.queue.length === 0) return; - + this.playing = true; - + // 创建新的音频缓冲区 const minPlaySamples = Math.min(this.queue.length, SAMPLE_RATE); // 最多播放1秒 const currentSamples = this.queue.splice(0, minPlaySamples); - + const audioBuffer = audioContext.createBuffer(CHANNELS, currentSamples.length, SAMPLE_RATE); audioBuffer.copyToChannel(new Float32Array(currentSamples), 0); - + // 创建音频源 this.source = audioContext.createBufferSource(); this.source.buffer = audioBuffer; - + // 创建增益节点用于平滑过渡 const gainNode = audioContext.createGain(); - + // 应用淡入淡出效果避免爆音 const fadeDuration = 0.02; // 20毫秒 gainNode.gain.setValueAtTime(0, audioContext.currentTime); gainNode.gain.linearRampToValueAtTime(1, audioContext.currentTime + fadeDuration); - + const duration = audioBuffer.duration; if (duration > fadeDuration * 2) { gainNode.gain.setValueAtTime(1, audioContext.currentTime + duration - fadeDuration); gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + duration); } - + // 连接节点并开始播放 this.source.connect(gainNode); gainNode.connect(audioContext.destination); - + this.lastPlayTime = audioContext.currentTime; log(`开始播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / SAMPLE_RATE).toFixed(2)} 秒`, 'info'); - + // 播放结束后的处理 this.source.onended = () => { this.source = null; this.playing = false; - + // 如果队列中还有数据或者缓冲区有新数据,继续播放 if (this.queue.length > 0) { setTimeout(() => this.startPlaying(), 10); @@ -897,26 +729,26 @@ }, 500); // 500ms超时 } }; - + this.source.start(); } }; } - + // 开始处理缓冲的数据 const frames = [...audioBufferQueue]; audioBufferQueue = []; // 清空缓冲队列 - + // 解码并播放 await streamingContext.decodeOpusFrames(frames); - + } catch (error) { log(`播放已缓冲的音频出错: ${error.message}`, 'error'); isAudioPlaying = false; streamingContext = null; } }; - + // 执行初始化和播放 initDecoderAndPlay(); } @@ -934,7 +766,7 @@ // 初始化Opus解码器 - 确保完全初始化完成后才返回 async function initOpusDecoder() { if (opusDecoder) return opusDecoder; // 已经初始化 - + try { // 检查ModuleInstance是否存在 if (typeof window.ModuleInstance === 'undefined') { @@ -946,9 +778,9 @@ throw new Error('Opus库未加载,ModuleInstance和Module对象都不存在'); } } - + const mod = window.ModuleInstance; - + // 创建解码器对象 opusDecoder = { channels: CHANNELS, @@ -956,55 +788,55 @@ frameSize: FRAME_SIZE, module: mod, decoderPtr: null, // 初始为null - + // 初始化解码器 - init: function () { + 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) { + decode: function(opusData) { if (!this.decoderPtr) { if (!this.init()) { throw new Error("解码器未初始化且无法初始化"); } } - + try { 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, @@ -1014,46 +846,46 @@ 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; } catch (error) { log(`Opus解码错误: ${error.message}`, 'error'); return new Int16Array(0); } }, - + // 销毁方法 - destroy: function () { + destroy: function() { if (this.decoderPtr) { this.module._free(this.decoderPtr); this.decoderPtr = null; } } }; - + // 初始化解码器 if (!opusDecoder.init()) { throw new Error("Opus解码器初始化失败"); } - + return opusDecoder; - + } catch (error) { log(`Opus解码器初始化失败: ${error.message}`, 'error'); opusDecoder = null; // 重置为null,以便下次重试 @@ -1286,100 +1118,25 @@ } // 连接WebSocket服务器 - async function connectToServer() { + function connectToServer() { const url = serverUrlInput.value.trim(); if (url === '') return; try { - // 获取并验证配置 - const config = getConfig(); - if (!validateConfig(config)) { - return; - } - // 检查URL格式 if (!url.startsWith('ws://') && !url.startsWith('wss://')) { log('URL格式错误,必须以ws://或wss://开头', 'error'); return; } - // 先检查OTA状态 - log('正在检查OTA状态...', 'info'); - const otaUrl = document.getElementById('otaUrl').value.trim(); - - try { - const otaResponse = await fetch(otaUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Device-Id': config.deviceId, - 'Client-Id': config.clientId - }, - body: JSON.stringify({ - "version": 0, - "uuid": "", - "application": { - "name": "xiaozhi-web-test", - "version": "1.0.0", - "compile_time": "2025-04-16 10:00:00", - "idf_version": "4.4.3", - "elf_sha256": "1234567890abcdef1234567890abcdef1234567890abcdef" - }, - "ota": { - "label": "xiaozhi-web-test", - }, - "board": { - "type": "xiaozhi-web-test", - "ssid": "xiaozhi-web-test", - "rssi": 0, - "channel": 0, - "ip": "192.168.1.1", - "mac": config.deviceMac - }, - "flash_size": 0, - "minimum_free_heap_size": 0, - "mac_address": config.deviceMac, - "chip_model_name": "", - "chip_info": { - "model": 0, - "cores": 0, - "revision": 0, - "features": 0 - }, - "partition_table": [ - { - "label": "", - "type": 0, - "subtype": 0, - "address": 0, - "size": 0 - } - ] - }) - }); - - if (!otaResponse.ok) { - throw new Error(`OTA检查失败: ${otaResponse.status} ${otaResponse.statusText}`); - } - - const otaResult = await otaResponse.json(); - log(`OTA检查结果: ${JSON.stringify(otaResult)}`, 'info'); - - log('OTA检查通过,开始连接WebSocket...', 'success'); - document.getElementById('otaStatus').textContent = 'ota已连接'; - document.getElementById('otaStatus').style.color = 'green'; - } catch (error) { - log(`OTA检查错误: ${error.message}`, 'error'); - document.getElementById('otaStatus').textContent = 'ota未连接'; - document.getElementById('otaStatus').style.color = 'red'; - } - // 使用自定义WebSocket实现以添加认证头信息 + // 注意:浏览器原生WebSocket不支持自定义头,需要通过服务器添加一个代理层 + // 但我们可以通过URL参数模拟认证信息 let connUrl = new URL(url); // 添加认证参数 - connUrl.searchParams.append('device-id', config.deviceId); - connUrl.searchParams.append('client-id', config.clientId); + connUrl.searchParams.append('device_id', 'web_test_device'); + connUrl.searchParams.append('device_mac', '00:11:22:33:44:55'); log(`正在连接: ${connUrl.toString()}`, 'info'); websocket = new WebSocket(connUrl.toString()); @@ -1389,16 +1146,14 @@ websocket.onopen = async () => { log(`已连接到服务器: ${url}`, 'success'); - connectionStatus.textContent = 'ws已连接'; + connectionStatus.textContent = '已连接'; connectionStatus.style.color = 'green'; // 连接成功后发送hello消息 await sendHelloMessage(); connectButton.textContent = '断开'; - connectButton.removeEventListener('click', connectToServer); - connectButton.addEventListener('click', disconnectFromServer); - // connectButton.onclick = disconnectFromServer; + connectButton.onclick = disconnectFromServer; messageInput.disabled = false; sendTextButton.disabled = false; @@ -1410,13 +1165,11 @@ websocket.onclose = () => { log('已断开连接', 'info'); - connectionStatus.textContent = 'ws已断开'; + connectionStatus.textContent = '已断开'; connectionStatus.style.color = 'red'; connectButton.textContent = '连接'; - connectButton.removeEventListener('click', disconnectFromServer); - connectButton.addEventListener('click', connectToServer); - // connectButton.onclick = connectToServer; + connectButton.onclick = connectToServer; messageInput.disabled = true; sendTextButton.disabled = true; recordButton.disabled = true; @@ -1425,7 +1178,7 @@ websocket.onerror = (error) => { log(`WebSocket错误: ${error.message || '未知错误'}`, 'error'); - connectionStatus.textContent = 'ws未连接'; + connectionStatus.textContent = '连接错误'; connectionStatus.style.color = 'red'; }; @@ -1436,7 +1189,7 @@ const message = JSON.parse(event.data); if (message.type === 'hello') { - log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success'); + log(`服务器回应:${message.message}`, 'info'); } else if (message.type === 'tts') { // TTS状态消息 if (message.state === 'start') { @@ -1491,11 +1244,11 @@ } }; - connectionStatus.textContent = 'ws未连接'; + connectionStatus.textContent = '正在连接...'; connectionStatus.style.color = 'orange'; } catch (error) { log(`连接错误: ${error.message}`, 'error'); - connectionStatus.textContent = 'ws未连接'; + connectionStatus.textContent = '连接失败'; } } @@ -1504,15 +1257,13 @@ if (!websocket || websocket.readyState !== WebSocket.OPEN) return; try { - const config = getConfig(); - // 设置设备信息 const helloMessage = { type: 'hello', - device_id: config.deviceId, - device_name: config.deviceName, - device_mac: config.deviceMac, - token: config.token + device_id: 'web_test_device', + device_name: 'Web测试设备', + device_mac: '00:11:22:33:44:55', + token: 'your-token1' // 使用config.yaml中配置的token }; log('发送hello握手消息', 'info'); @@ -1587,34 +1338,6 @@ connectButton.addEventListener('click', connectToServer); document.getElementById('authTestButton').addEventListener('click', testAuthentication); - // 设备配置面板折叠/展开 - const toggleButton = document.getElementById('toggleConfig'); - const configPanel = document.getElementById('configPanel'); - const deviceMacInput = document.getElementById('deviceMac'); - const clientIdInput = document.getElementById('clientId'); - const displayMac = document.getElementById('displayMac'); - const displayClient = document.getElementById('displayClient'); - - // 更新显示的值 - function updateDisplayValues() { - displayMac.textContent = deviceMacInput.value; - displayClient.textContent = clientIdInput.value; - } - - // 监听输入变化 - deviceMacInput.addEventListener('input', updateDisplayValues); - clientIdInput.addEventListener('input', updateDisplayValues); - - // 初始更新显示值 - updateDisplayValues(); - - // 切换面板显示 - toggleButton.addEventListener('click', () => { - const isExpanded = configPanel.classList.contains('expanded'); - configPanel.classList.toggle('expanded'); - toggleButton.textContent = isExpanded ? '编辑' : '收起'; - }); - // 标签页切换 const tabs = document.querySelectorAll('.tab'); tabs.forEach(tab => { @@ -1649,14 +1372,12 @@ async function testAuthentication() { log('开始测试认证...', 'info'); - const config = getConfig(); - // 显示服务器配置 log('-------- 服务器认证配置检查 --------', 'info'); log('请确认config.yaml中的auth配置:', 'info'); log('1. server.auth.enabled 为 false 或服务器已正确配置认证', 'info'); log('2. 如果启用了认证,请确认使用了正确的token', 'info'); - log(`3. 或者在allowed_devices中添加了测试设备MAC:${config.deviceMac}`, 'info'); + log('3. 或者在allowed_devices中添加了测试设备MAC:00:11:22:33:44:55', 'info'); const serverUrl = serverUrlInput.value.trim(); if (!serverUrl) { @@ -1697,9 +1418,9 @@ log('测试2: 尝试带token参数连接...', 'info'); let url = new URL(serverUrl); - url.searchParams.append('token', config.token); - url.searchParams.append('device_id', config.deviceId); - url.searchParams.append('device_mac', config.deviceMac); + url.searchParams.append('token', 'your-token1'); + url.searchParams.append('device_id', 'web_test_device'); + url.searchParams.append('device_mac', '00:11:22:33:44:55'); const ws2 = new WebSocket(url.toString()); @@ -1709,9 +1430,9 @@ // 尝试发送hello消息 const helloMsg = { type: 'hello', - device_id: config.deviceId, - device_mac: config.deviceMac, - token: config.token + device_id: 'web_test_device', + device_mac: '00:11:22:33:44:55', + token: 'your-token1' }; ws2.send(JSON.stringify(helloMsg)); @@ -2353,19 +2074,19 @@ if (opusData.length > 0) { // 将数据添加到缓冲队列 audioBufferQueue.push(opusData); - + // 如果收到的是第一个音频包,开始缓冲过程 if (audioBufferQueue.length === 1 && !isAudioBuffering && !isAudioPlaying) { startAudioBuffering(); } } else { log('收到空音频数据帧,可能是结束标志', 'warning'); - + // 如果缓冲队列中有数据且没有在播放,立即开始播放 if (audioBufferQueue.length > 0 && !isAudioPlaying) { playBufferedAudio(); } - + // 如果正在播放,发送结束信号 if (isAudioPlaying && streamingContext) { streamingContext.endOfStream = true; @@ -2376,31 +2097,6 @@ } } - // 获取配置值 - 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() - }; - } - - // 验证配置 - function validateConfig(config) { - if (!config.deviceMac) { - log('设备MAC地址不能为空', 'error'); - return false; - } - if (!config.clientId) { - log('客户端ID不能为空', 'error'); - return false; - } - return true; - } - initApp();