mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
Merge branch 'main' of github.com:zhongpei/xiaozhi-esp32-server
This commit is contained in:
commit
7095ef50b4
48 changed files with 7283 additions and 1096 deletions
|
|
@ -5,7 +5,9 @@ __pycache__
|
||||||
Dockerfile
|
Dockerfile
|
||||||
docs/
|
docs/
|
||||||
tmp/
|
tmp/
|
||||||
|
data/
|
||||||
LICENSE
|
LICENSE
|
||||||
README.md
|
README.md
|
||||||
README_en.md
|
README_en.md
|
||||||
.config.yaml
|
manager/static
|
||||||
|
manager/static/webui/
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -143,3 +143,4 @@ tmp
|
||||||
.config.yaml
|
.config.yaml
|
||||||
.secrets.yaml
|
.secrets.yaml
|
||||||
.private_config.yaml
|
.private_config.yaml
|
||||||
|
docker-compose.yml
|
||||||
|
|
|
||||||
52
Dockerfile
52
Dockerfile
|
|
@ -1,41 +1,22 @@
|
||||||
# 第一阶段:前端构建
|
# 第一阶段:前端构建
|
||||||
FROM node:18 as frontend-builder
|
FROM node:18 AS frontend-builder
|
||||||
|
|
||||||
WORKDIR /app/ZhiKongTaiWeb
|
WORKDIR /app/ZhiKongTaiWeb
|
||||||
|
|
||||||
COPY ZhiKongTaiWeb/package*.json ./
|
RUN corepack enable && yarn config set registry https://registry.npmmirror.com
|
||||||
|
|
||||||
RUN npm install
|
COPY ZhiKongTaiWeb/package.json ZhiKongTaiWeb/yarn.lock ./
|
||||||
|
|
||||||
|
RUN mkdir node_modules && yarn install --frozen-lockfile
|
||||||
|
|
||||||
COPY ZhiKongTaiWeb .
|
COPY ZhiKongTaiWeb .
|
||||||
|
RUN yarn build
|
||||||
|
|
||||||
RUN npm run build
|
# 第二阶段:构建 Python 依赖
|
||||||
|
FROM ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest AS builder
|
||||||
# 第二阶段:构建Python依赖
|
|
||||||
FROM python:3.10-slim as builder
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
COPY pyproject.toml poetry.lock /app/
|
||||||
COPY requirements.txt .
|
RUN poetry install --no-root
|
||||||
|
|
||||||
# 使用清华源加速apt安装
|
|
||||||
RUN rm -rf /etc/apt/sources.list.d/* && \
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list && \
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
|
||||||
apt-get clean && \
|
|
||||||
apt-get update && \
|
|
||||||
apt-get install -y --no-install-recommends \
|
|
||||||
gcc \
|
|
||||||
libopus-dev \
|
|
||||||
ffmpeg && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
# 安装Python依赖到虚拟环境
|
|
||||||
RUN python -m venv /opt/venv
|
|
||||||
ENV PATH="/opt/venv/bin:$PATH"
|
|
||||||
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
|
||||||
|
|
||||||
# 第三阶段:生产镜像
|
# 第三阶段:生产镜像
|
||||||
FROM python:3.10-slim
|
FROM python:3.10-slim
|
||||||
|
|
@ -48,18 +29,13 @@ RUN rm -rf /etc/apt/sources.list.d/* && \
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
apt-get clean && \
|
|
||||||
apt-get update && \
|
apt-get update && \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
||||||
libopus0 \
|
apt-get clean
|
||||||
ffmpeg && \
|
|
||||||
apt-get clean && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
# 从构建阶段复制虚拟环境和前端构建产物
|
# 从构建阶段复制虚拟环境和前端构建产物
|
||||||
COPY --from=builder /opt/venv /opt/venv
|
COPY --from=builder /app/.venv /opt/venv
|
||||||
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /opt/xiaozhi-esp32-server/manager/static
|
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /opt/xiaozhi-esp32-server/manager/static/webui
|
||||||
|
|
||||||
# 设置虚拟环境路径
|
# 设置虚拟环境路径
|
||||||
ENV PATH="/opt/venv/bin:$PATH"
|
ENV PATH="/opt/venv/bin:$PATH"
|
||||||
|
|
||||||
|
|
|
||||||
557
README.md
557
README.md
|
|
@ -4,15 +4,17 @@
|
||||||
|
|
||||||
(中文 | [English](README_en.md))
|
(中文 | [English](README_en.md))
|
||||||
|
|
||||||
本项目为开源智能硬件项目 [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32)
|
本项目为开源智能硬件项目 [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) 提供后端服务。根据 [小智通信协议](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) 使用 `Python` 实现。
|
||||||
提供后端服务。根据[小智通信协议](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh)使用`Python`实现。
|
|
||||||
|
|
||||||
## 适用人群
|
---
|
||||||
|
|
||||||
本项目需要配合esp32硬件设备使用,如果童鞋们已经购买了esp32相关硬件,且成功对接虾哥部署的后端,并且想自己独立搭建
|
## 适用人群 👥
|
||||||
`xiaozhi-esp32`后端服务,可学习本项目。
|
|
||||||
|
|
||||||
想看使用效果,请猛戳这个视频
|
本项目需要配合 ESP32 硬件设备使用。如果您已经购买了 ESP32 相关硬件,且成功对接过虾哥部署的后端服务,并希望独立搭建自己的 `xiaozhi-esp32` 后端服务,那么本项目非常适合您。
|
||||||
|
|
||||||
|
跳转到[使用方式](#使用方式-)
|
||||||
|
|
||||||
|
想看使用效果?请猛戳这个视频 🎥
|
||||||
|
|
||||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX">
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX">
|
||||||
<picture>
|
<picture>
|
||||||
|
|
@ -20,525 +22,202 @@
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
要想完整体验本项目,需要以下总体步骤:
|
---
|
||||||
|
|
||||||
- 准备一套兼容`xiaozhi-esp32`
|
## 系统要求与部署前提 🖥️
|
||||||
项目的硬件设备,具体型号可[点击这里](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf)。
|
|
||||||
- 拥有一台至少4核CPU 8G内存的普通电脑或服务器,运行本项目。部署后可以在控制台看到本项目服务的接口地址。
|
|
||||||
- 下载`xiaozhi-esp32`项目,把`接口地址`修改成本项目地址,然后编译,把新固件烧录到硬件设备上。
|
|
||||||
- 启动设备,查看电脑或服务器的控制台,如果看到日志,说明成功连到本项目的接口了。
|
|
||||||
|
|
||||||
## 警告
|
- **硬件**:一套兼容 `xiaozhi-esp32` 的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
|
||||||
|
- **服务器**:至少 4 核 CPU、8G 内存的电脑或服务器。
|
||||||
|
- **固件编译**:请将后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译固件并烧录到设备上。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 警告 ⚠️
|
||||||
|
|
||||||
本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。
|
本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。
|
||||||
|
|
||||||
如果您在公网环境中部署学习本项目。请务必在配置文件`config.yaml`开启防护。
|
如果您在公网环境中部署学习本项目,请务必在配置文件 `config.yaml` 中开启防护:
|
||||||
|
|
||||||
```
|
```yaml
|
||||||
server:
|
server:
|
||||||
auth:
|
auth:
|
||||||
# 开启防护
|
# 开启防护
|
||||||
enabled: true
|
enabled: true
|
||||||
```
|
```
|
||||||
|
|
||||||
开启防护后,你要根据自己的情况,要么校验机器的token,要么校验机器的mac地址,详细可看配置。
|
开启防护后,您需要根据实际情况校验机器的 token 或 mac 地址,详细请参见配置说明。
|
||||||
|
|
||||||
## 功能清单
|
---
|
||||||
|
|
||||||
## 已实现
|
## 功能清单 ✨
|
||||||
|
|
||||||
- `xiaozhi-esp32` 通信 WebSocket 协议
|
### 已实现 ✅
|
||||||
- 支持唤醒对话、手动对话、实时打断对话
|
|
||||||
- 支持国语、粤语、英语、日语、韩语 5 种语言识别(FunASR(默认))
|
|
||||||
- 自由更换 LLM(openai接口支持ChatGLM(默认)、阿里百炼、DeepSeek等,dify接口支持Dify官方及私有化部署)
|
|
||||||
- 自由更换 TTS(支持EdgeTTS(默认)、火山引擎豆包TTS)
|
|
||||||
|
|
||||||
## 正在实现
|
- **通信协议**
|
||||||
|
基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。
|
||||||
|
- **对话交互**
|
||||||
|
支持唤醒对话、手动对话及实时打断。
|
||||||
|
- **多语言识别**
|
||||||
|
支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。
|
||||||
|
- **LLM 模块**
|
||||||
|
支持灵活切换 LLM 模块,默认使用 ChatGLMLLM,也可选用阿里百炼、DeepSeek、Ollama 等接口。
|
||||||
|
- **TTS 模块**
|
||||||
|
支持 EdgeTTS(默认)、火山引擎豆包 TTS 等多种 TTS 接口,满足语音合成需求。
|
||||||
|
|
||||||
- 长时间不聊天进入休眠状态
|
### 正在开发 🚧
|
||||||
- 对话记忆
|
|
||||||
- 更换心情模式
|
|
||||||
|
|
||||||
## 本项目支持的平台/组件列表
|
- 长时间无对话时自动休眠
|
||||||
|
- 对话记忆功能
|
||||||
|
- 多种心情模式
|
||||||
|
|
||||||
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
---
|
||||||
|:----|:----------|:----------:|:--------|:----------------------------------------------------------------|
|
|
||||||
| LLM | 阿里百炼 | openai接口调用 | 消耗token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) |
|
|
||||||
| LLM | 深度求索 | openai接口调用 | 消耗token | [点击申请密钥](https://platform.deepseek.com/) |
|
|
||||||
| LLM | 智谱 | openai接口调用 | 免费 | [点击创建密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) |
|
|
||||||
| LLM | Dify | dify接口调用 | 消耗token | 本地化部署 |
|
|
||||||
| TTS | 火山引擎 | 接口调用 | 消耗token | [点击创建密钥](https://console.volcengine.com/speech/service/8) |
|
|
||||||
| TTS | EdgeTTS | 接口调用 | 免费 | |
|
|
||||||
| VAD | SileroVAD | 本地使用 | 免费 | |
|
|
||||||
| ASR | FunASR | 本地使用 | 免费 | |
|
|
||||||
|
|
||||||
实际上,任何支持openai接口调用的LLM,都可以接入使用。
|
## 本项目支持的平台/组件列表 📋
|
||||||
|
|
||||||
# 部署方式
|
### LLM
|
||||||
|
|
||||||
本项目支持docker快速部署、借助docker环境运行部署和本地源码运行三种方式。三种方式怎么选,每个人的情况不一样,以下是一些推荐。
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|
|:----:|:-----------------------------:|:-------------------:|:--------:|:-----------------------------------------------------------------------------:|
|
||||||
|
| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) |
|
||||||
|
| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) |
|
||||||
|
| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) |
|
||||||
|
| LLM | OllamaLLM | ollama 接口调用 | 免费/自定义 | 需预先下载模型(`ollama pull`),服务地址:`http://localhost:11434` |
|
||||||
|
| LLM | DifyLLM | dify 接口调用 | 消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 |
|
||||||
|
| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) |
|
||||||
|
| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 |
|
||||||
|
|
||||||
如果您主要是想快速体验,推荐使用`方式一:docker快速部署`。
|
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
|
||||||
|
|
||||||
如果您已经安装docker,不想折腾环境,又想对代码进行DIY修改,推荐`方式二:借助docker环境运行部署`。
|
---
|
||||||
|
|
||||||
如果您对conda的使用得心应手,或想从零开始学习搭建环境,推荐`方式三:本地源码运行`。
|
### TTS
|
||||||
|
|
||||||
如果你对小智的回答速度非常的敏感,不希望有丝丝的性能损失,推荐`方式三:本地源码运行`。
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|
|:----:|:-----------------------------------:|:---------------:|:-------------:|:-------------------------------------------------------------------------------------------------------------------------:|
|
||||||
|
| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 |
|
||||||
|
| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 |
|
||||||
|
| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav |
|
||||||
|
| TTS | CozeCnTTS | 接口调用 | 消耗 token | 需提供 Coze API key;输出格式为 wav |
|
||||||
|
| TTS | FishSpeech | 接口调用 | 免费/自定义 | 本地启动 TTS 服务;启动方法见配置文件内说明 |
|
||||||
|
| TTS | GPT_SOVITS_V2 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 |
|
||||||
|
|
||||||
## 方式一:docker快速部署
|
---
|
||||||
|
|
||||||
docker镜像已支持x86架构、arm64架构的CPU,支持在国产操作系统上运行。
|
### VAD
|
||||||
|
|
||||||
### 1. 安装docker
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|
|:----:|:----------:|:---------:|:--------:|:----:|
|
||||||
|
| VAD | SileroVAD | 本地使用 | 免费 | |
|
||||||
|
|
||||||
如果您的电脑还没安装docker,可以按照这里的教程安装:[docker安装](https://www.runoob.com/docker/ubuntu-docker-install.html)
|
---
|
||||||
|
|
||||||
### 2. 创建目录
|
### ASR
|
||||||
|
|
||||||
安装完后,你需要为这个项目找一个安放配置文件的目录,我们暂且称它为`项目目录`,这个目录最好是一个新建的空的目录。
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|
|:----:|:--------:|:---------:|:--------:|:----:|
|
||||||
|
| ASR | FunASR | 本地使用 | 免费 | |
|
||||||
|
|
||||||
### 3. 下载配置文件
|
---
|
||||||
|
|
||||||
用浏览器打开[这个链接](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/config.yaml)。
|
## 使用方式 🚀
|
||||||
|
|
||||||
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config.yaml`文件。 把文件下载到你的
|
### 一、[部署文档](./docs/Deployment.md)
|
||||||
`项目目录`。
|
|
||||||
|
|
||||||
### 4. 修改配置文件
|
[精简版部署文档](./docs/Deployment-silm.md)
|
||||||
|
|
||||||
修改刚才你下载的`config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM`
|
本项目支持以下三种部署方式,您可根据实际需求选择:
|
||||||
,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。
|
|
||||||
|
|
||||||
默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。
|
1. **[Docker 快速部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%BF%AB%E9%80%9F%E9%83%A8%E7%BD%B2)**
|
||||||
|
适合快速体验,不需过多环境配置。
|
||||||
|
2. **[借助 Docker 环境运行部署](./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)**
|
||||||
|
适用于已安装 Docker 且希望对代码进行自定义修改的用户。
|
||||||
|
3. **[本地源码运行](./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)**
|
||||||
|
适合熟悉 Conda 环境或希望从零搭建运行环境的用户。
|
||||||
|
对于对响应速度要求较高的场景,推荐使用本地源码运行方式以降低额外开销。
|
||||||
|
|
||||||
配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。
|
|
||||||
|
|
||||||
本项目的默认配置原则是成本最低配置原则(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。
|
### 二、[固件编译](./docs/firmware-build.md)
|
||||||
|
|
||||||
```
|
点这里查看[固件编译](./docs/firmware-build.md)的详细过程。
|
||||||
selected_module:
|
|
||||||
ASR: FunASR
|
|
||||||
VAD: SileroVAD
|
|
||||||
LLM: ChatGLMLLM
|
|
||||||
TTS: EdgeTTS
|
|
||||||
```
|
|
||||||
|
|
||||||
比如修改`LLM`使用的组件,就看本项目支持哪些`LLM` API接口,当前支持的是`openai`、`dify`。欢迎验证和支持更多LLM平台的接口。
|
编译成功且联网成功后,通过唤醒词唤醒小智,留意server端输出的控制台信息。
|
||||||
|
|
||||||
使用时,在`selected_module`修改成对应的如下LLM配置的名称:
|
---
|
||||||
|
|
||||||
```
|
## 常见问题 ❓
|
||||||
LLM:
|
|
||||||
AliLLM:
|
|
||||||
type: openai
|
|
||||||
...
|
|
||||||
DeepSeekLLM:
|
|
||||||
type: openai
|
|
||||||
...
|
|
||||||
ChatGLMLLM:
|
|
||||||
type: openai
|
|
||||||
...
|
|
||||||
DifyLLM:
|
|
||||||
type: dify
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
有些服务,比如如果你使用`Dify`、`豆包的TTS`,是需要密钥的,记得在配置文件加上哦!
|
### 1、TTS 经常失败,经常超时 ⏰
|
||||||
|
|
||||||
### 5. 执行docker命令
|
建议:如果 `EdgeTTS` 经常失败,请先检查是否使用了代理(梯子)。如果使用了,请尝试关闭代理后再试;
|
||||||
|
如果用的是火山引擎的豆包 TTS,经常失败时建议使用付费版本,因为测试版本仅支持 2 个并发。
|
||||||
|
|
||||||
打开命令行工具,`cd` 进入到你的`项目目录`,执行以下命令
|
### 2、我想通过小智控制电灯、空调、远程开关机等操作 💡
|
||||||
|
|
||||||
```
|
建议:在配置文件中将 `LLM` 设置为 `DifyLLM`,并通过 `Dify` 编排智能体来实现相关控制。
|
||||||
#如果你是linux,执行
|
|
||||||
ls
|
|
||||||
#如果你是windows,执行
|
|
||||||
dir
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你能看到`config.yaml`文件,确确实实进入到了`项目目录`,接着执行以下命令:
|
### 3、我说话很慢,停顿时小智老是抢话 🗣️
|
||||||
|
|
||||||
```
|
建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`):
|
||||||
docker run -d --name xiaozhi-esp32-server --restart always --security-opt seccomp:unconfined -p 8000:8000 -v $(pwd)/config.yaml:/opt/xiaozhi-esp32-server/config.yaml ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
```yaml
|
||||||
```
|
|
||||||
|
|
||||||
如果首次执行,可能需要几分钟时间,你要耐心等待他完成拉取。正常拉取完成后,你可以在命令行执行以下命令查看服务是否启动成功
|
|
||||||
|
|
||||||
```
|
|
||||||
docker ps
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你能看到`xiaozhi-server`,说明服务启动成功。那你还可以进一步执行以下命令,查看服务的日志
|
|
||||||
|
|
||||||
```
|
|
||||||
docker logs -f xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
|
|
||||||
|
|
||||||
```
|
|
||||||
2025-xx-xx xx:51:59,492 - core.server - INFO - Server is running at ws://xx.xx.xx.xxx:8000
|
|
||||||
2025-xx-xx xx:51:59,516 - websockets.server - INFO - server listening on 0.0.0.0:8000
|
|
||||||
```
|
|
||||||
|
|
||||||
接下来,你就可以开始 `编译esp32固件`了,请往下翻,翻到编译`esp32固件`相关章节。那么由于你是用docker部署,你要自己查看自己本机电脑的ip是多少。
|
|
||||||
正常来说,假设你的ip是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。这个信息很有用的,后面`编译esp32固件`
|
|
||||||
需要用到。
|
|
||||||
|
|
||||||
请注意,你的接口地址是`websocket`协议的地址,你可以使用`apifox`等工具调试。但是不能直接用浏览器打开访问,如果用浏览器打开,日志会显示错误,会让你怀疑是否部署成功了。
|
|
||||||
|
|
||||||
后期如果想升级版本,可以这么操作
|
|
||||||
|
|
||||||
1、备份好`config.yaml`文件,一些关键的配置到时复制到新的`config.yaml`文件里。
|
|
||||||
|
|
||||||
2、执行以下命令
|
|
||||||
|
|
||||||
```
|
|
||||||
docker stop xiaozhi-esp32-server
|
|
||||||
docker rm xiaozhi-esp32-server
|
|
||||||
docker rmi ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
3.按本教程重新来一遍
|
|
||||||
|
|
||||||
## 方式二:借助docker环境运行部署
|
|
||||||
|
|
||||||
这个方法的原理,其实是和第一种方式类似。区别在于,第一种方式只要下载一个配置文件,而本方式要下载项目源码。
|
|
||||||
|
|
||||||
优点就是源码在你主机躺着,你可以使用本机的代码编辑器加载项目和修改源码。每次修改完项目,想要看效果,那就要重启docker。
|
|
||||||
|
|
||||||
缺点就要下载本项目的代码,还要下载模型文件,如果这个项目不常用,确实会占用您电脑的空间。
|
|
||||||
|
|
||||||
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
|
|
||||||
|
|
||||||
你可以用浏览器打开这个地址`https://github.com/xinnan-tech/xiaozhi-esp32-server.git`
|
|
||||||
|
|
||||||
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
|
|
||||||
|
|
||||||
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`xiaozhi-esp32-server-main`
|
|
||||||
你需要把它重命名成`xiaozhi-esp32-server`,好了请记住这个目录,我们暂且称它为`项目目录`。
|
|
||||||
|
|
||||||
下载源码后,需要下载模型文件。 默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
|
|
||||||
文件放在`model/SenseVoiceSmall`
|
|
||||||
目录下。下面两个下载路线任选一个。
|
|
||||||
|
|
||||||
- 线路一:阿里魔塔下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
|
||||||
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
|
|
||||||
`qvna`
|
|
||||||
|
|
||||||
下载模型后,需要按照`方式一:docker快速部署`修改配置文件`config.yaml`
|
|
||||||
|
|
||||||
修改完配置后,打开命令行工具,`cd`进入到你的项目目录下,执行以下命令
|
|
||||||
|
|
||||||
```
|
|
||||||
docker run -d --name xiaozhi-esp32-server --restart always --security-opt seccomp:unconfined \
|
|
||||||
-p 8000:8000 \
|
|
||||||
-v $(pwd):/opt/xiaozhi-esp32-server \
|
|
||||||
ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
```
|
|
||||||
docker logs -f xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
|
|
||||||
|
|
||||||
```
|
|
||||||
2025-xx-xx xx:51:59,492 - core.server - INFO - Server is running at ws://xx.xx.xx.xxx:8000
|
|
||||||
2025-xx-xx xx:51:59,516 - websockets.server - INFO - server listening on 0.0.0.0:8000
|
|
||||||
```
|
|
||||||
|
|
||||||
接下来,你就可以开始 `编译esp32固件`了,请往下翻,翻到编译`esp32固件`相关章节。那么由于你是用docker部署,你要自己查看自己本机电脑的ip是多少。
|
|
||||||
正常来说,假设你的ip是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。这个信息很有用的,后面`编译esp32固件`
|
|
||||||
需要用到。
|
|
||||||
|
|
||||||
请注意,你的接口地址是`websocket`协议的地址,你可以使用`apifox`等工具调试。但是不能直接用浏览器打开访问,如果用浏览器打开,日志会显示错误,会让你怀疑是否部署成功了。
|
|
||||||
|
|
||||||
后期,如果你修改了代码,想让新代码跑起来,可以用以下命令让docker容器重启:
|
|
||||||
|
|
||||||
```
|
|
||||||
docker restart xiaozhi-esp32-server
|
|
||||||
# 查看日志输出
|
|
||||||
docker logs -f xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
## 方式三:本地源码运行
|
|
||||||
|
|
||||||
### 1.安装基础环境
|
|
||||||
|
|
||||||
本项目使用`conda`管理依赖环境,安装好后,开始执行以下命令。
|
|
||||||
|
|
||||||
```
|
|
||||||
conda remove -n xiaozhi-esp32-server --all -y
|
|
||||||
conda create -n xiaozhi-esp32-server python=3.10 -y
|
|
||||||
conda activate xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
执行以上命令后, 如果你的电脑是Windows或Mac,执行下面的语句:
|
|
||||||
|
|
||||||
```
|
|
||||||
conda activate xiaozhi-esp32-server
|
|
||||||
conda install conda-forge::libopus
|
|
||||||
conda install conda-forge::ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你的电脑是ubuntu,执行下面的语句:
|
|
||||||
|
|
||||||
```
|
|
||||||
apt-get install libopus0 ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2.安装本项目依赖
|
|
||||||
|
|
||||||
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
|
|
||||||
|
|
||||||
你可以用浏览器打开这个地址`https://github.com/xinnan-tech/xiaozhi-esp32-server.git`
|
|
||||||
|
|
||||||
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
|
|
||||||
|
|
||||||
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`xiaozhi-esp32-server-main`
|
|
||||||
你需要把它重命名成`xiaozhi-esp32-server`,好了请记住这个目录,我们暂且称它为`项目目录`。
|
|
||||||
|
|
||||||
```
|
|
||||||
# 使用dos或者终端,进入到你的项目目录,执行以下命令
|
|
||||||
conda activate xiaozhi-esp32-server
|
|
||||||
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.下载语音识别模型
|
|
||||||
|
|
||||||
默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`文件放在`model/SenseVoiceSmall`
|
|
||||||
目录下。下面两个下载路线任选一个。
|
|
||||||
|
|
||||||
- 线路一:阿里魔塔下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
|
||||||
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
|
|
||||||
`qvna`
|
|
||||||
|
|
||||||
### 4.配置项目
|
|
||||||
|
|
||||||
修改`config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM`
|
|
||||||
,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。
|
|
||||||
默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。
|
|
||||||
|
|
||||||
```
|
|
||||||
# 如果您是一名开发者,建议阅读以下内容。如果不是开发者,可以忽略这部分内容。
|
|
||||||
在开发中,建议将【config.yaml】复制一份,改成【.config.yaml】。 系统会优先读取【.config.yaml】文件的配置。
|
|
||||||
这样做,可以避免在提交代码的时候,错误地提交密钥信息,保护您的密钥安全。
|
|
||||||
```
|
|
||||||
|
|
||||||
配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。
|
|
||||||
|
|
||||||
本项目的默认配置仅是成本最低配置(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。
|
|
||||||
|
|
||||||
```
|
|
||||||
selected_module:
|
|
||||||
ASR: FunASR
|
|
||||||
VAD: SileroVAD
|
|
||||||
LLM: ChatGLMLLM
|
|
||||||
TTS: EdgeTTS
|
|
||||||
```
|
|
||||||
|
|
||||||
比如修改`LLM`使用的组件,就看本项目支持哪些`LLM` API接口,当前支持的是`openai`、`dify`。欢迎验证和支持更多LLM平台的接口。
|
|
||||||
使用时,在`selected_module`修改成对应的如下LLM配置的名称:
|
|
||||||
|
|
||||||
```
|
|
||||||
LLM:
|
|
||||||
DeepSeekLLM:
|
|
||||||
type: openai
|
|
||||||
...
|
|
||||||
ChatGLMLLM:
|
|
||||||
type: openai
|
|
||||||
...
|
|
||||||
DifyLLM:
|
|
||||||
type: dify
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
有些服务,比如如果你使用`Dify`、`豆包的TTS`,是需要密钥的,记得在配置文件加上哦!
|
|
||||||
|
|
||||||
### 5.运行项目
|
|
||||||
|
|
||||||
启动项目
|
|
||||||
|
|
||||||
```
|
|
||||||
# 确保在本项目的根目录下执行
|
|
||||||
conda activate xiaozhi-esp32-server
|
|
||||||
python app.py
|
|
||||||
```
|
|
||||||
|
|
||||||
启动后,会看到类似以下日志
|
|
||||||
|
|
||||||
```
|
|
||||||
2025-xx-xx xx:51:59,492 - core.server - INFO - Server is running at ws://192.168.1.25:8000
|
|
||||||
2025-xx-xx xx:51:59,516 - websockets.server - INFO - server listening on 0.0.0.0:8000
|
|
||||||
```
|
|
||||||
|
|
||||||
其中上面的`ws://192.168.1.25:8000`就是本项目提供的接口地址了,当然你自己的机器和我的是不一样的,记得要找到自己的地址。
|
|
||||||
|
|
||||||
请注意,你的接口地址是`websocket`协议的地址,你可以使用`apifox`等工具调试。但是不能直接用浏览器打开访问,如果用浏览器打开,日志会显示错误,会让你怀疑是否部署成功了。
|
|
||||||
|
|
||||||
# 编译esp32固件
|
|
||||||
|
|
||||||
1. 下载`xiaozhi-esp32`
|
|
||||||
项目,按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf)
|
|
||||||
|
|
||||||
2. 打开`xiaozhi-esp32/main/Kconfig.projbuild`文件,找到`WEBSOCKET_URL`的`default`的内容,把`wss://api.tenclass.net`
|
|
||||||
改成你自己的地址,例如,我的接口地址是`ws://192.168.1.25:8000`,就把内容改成这个。
|
|
||||||
|
|
||||||
修改前:
|
|
||||||
|
|
||||||
```
|
|
||||||
config WEBSOCKET_URL
|
|
||||||
depends on CONNECTION_TYPE_WEBSOCKET
|
|
||||||
string "Websocket URL"
|
|
||||||
default "wss://api.tenclass.net/xiaozhi/v1/"
|
|
||||||
help
|
|
||||||
Communication with the server through websocket after wake up.
|
|
||||||
```
|
|
||||||
|
|
||||||
修改后(示例):
|
|
||||||
|
|
||||||
```
|
|
||||||
config WEBSOCKET_URL
|
|
||||||
depends on CONNECTION_TYPE_WEBSOCKET
|
|
||||||
string "Websocket URL"
|
|
||||||
default "ws://192.168.1.25:8000/xiaozhi/v1/"
|
|
||||||
help
|
|
||||||
Communication with the server through websocket after wake up.
|
|
||||||
```
|
|
||||||
|
|
||||||
注意:你的地址是`ws://`开头,不是`wss://`开头,一定不要写错了。
|
|
||||||
|
|
||||||
注意:你的地址是`ws://`开头,不是`wss://`开头,一定不要写错了。
|
|
||||||
|
|
||||||
注意:你的地址是`ws://`开头,不是`wss://`开头,一定不要写错了。
|
|
||||||
|
|
||||||
3. 设置编译参数
|
|
||||||
|
|
||||||
```
|
|
||||||
# 终端命令行进入xiaozhi-esp32的根目录
|
|
||||||
cd xiaozhi-esp32
|
|
||||||
# 例如我使用的板子是esp32s3,所以设置编译目标为esp32s3,如果你的板子是其他型号,请替换成对应的型号
|
|
||||||
idf.py set-target esp32s3
|
|
||||||
# 进入菜单配置
|
|
||||||
idf.py menuconfig
|
|
||||||
```
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
进入菜单配置后,再进入`Xiaozhi Assistant`,将`CONNECTION_TYPE`设置为`Websocket`
|
|
||||||
回退到主菜单,再进入`Xiaozhi Assistant`,将`BOARD_TYPE`设置你板子的具体型号
|
|
||||||
保存退出,回到终端命令行。
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
4. 编译固件
|
|
||||||
|
|
||||||
```
|
|
||||||
idf.py build
|
|
||||||
```
|
|
||||||
|
|
||||||
5. 打包bin固件
|
|
||||||
|
|
||||||
```
|
|
||||||
cd scripts
|
|
||||||
python release.py
|
|
||||||
```
|
|
||||||
|
|
||||||
编译成功后,会在项目根目录下的`build`目录下生成固件文件`merged-binary.bin`。
|
|
||||||
这个`merged-binary.bin`就是要烧录到硬件上的固件文件。
|
|
||||||
|
|
||||||
注意:如果执行到第二命令后,报了“zip”相关的错误,请忽略这个错误,只要`build`目录下生成固件文件`merged-binary.bin`
|
|
||||||
,对你没有太大影响,请继续。
|
|
||||||
|
|
||||||
6. 烧录固件
|
|
||||||
将esp32设备连接电脑,使用chrome浏览器,打开以下网址
|
|
||||||
|
|
||||||
```
|
|
||||||
https://espressif.github.io/esp-launchpad/
|
|
||||||
```
|
|
||||||
|
|
||||||
打开这个教程,[Flash工具/Web端烧录固件(无IDF开发环境)](https://ccnphfhqs21z.feishu.cn/wiki/Zpz4wXBtdimBrLk25WdcXzxcnNS)。
|
|
||||||
翻到:`方式二:ESP-Launchpad 浏览器WEB端烧录`,从`3. 烧录固件/下载到开发板`开始,按照教程操作。
|
|
||||||
|
|
||||||
# 常见问题
|
|
||||||
|
|
||||||
## 1、TTS 经常失败,经常超时
|
|
||||||
|
|
||||||
建议:如果`EdgeTTS`经常失败,先检查一下是否用了梯子,如果用了梯子,请把梯子关了试试。
|
|
||||||
如果用的是`火山引擎的豆包TTS`经常失败,最好使用付费版本,因为他们的测试版本只有2个并发。
|
|
||||||
|
|
||||||
## 2、我想通过小智控制电灯、空调、远程开关机等操作。
|
|
||||||
|
|
||||||
建议:在配置文件里,将`LLM`设置成`DifyLLM`,然后通过`Dify`编排智能体实现。
|
|
||||||
|
|
||||||
## 3、我说话很慢,我停顿一下,小智老是抢我的话,咋办。
|
|
||||||
|
|
||||||
建议:在配置文件里,找到这一段,将`min_silence_duration_ms`值改大一点,比如改成`1000`。
|
|
||||||
|
|
||||||
```
|
|
||||||
VAD:
|
VAD:
|
||||||
SileroVAD:
|
SileroVAD:
|
||||||
threshold: 0.5
|
threshold: 0.5
|
||||||
model_dir: models/snakers4_silero-vad
|
model_dir: models/snakers4_silero-vad
|
||||||
min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些
|
min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大
|
||||||
```
|
```
|
||||||
|
|
||||||
## 4、如何才能提高小智对话响应速度?
|
### 4、如何提高小智对话响应速度? ⚡
|
||||||
|
|
||||||
本项目的默认配置,是成本最低的配置。建议刚上手的童鞋,使用默认的免费模型,先解决了“跑得动”的问题,再解决“跑得快”的问题。
|
本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决“跑得动”的问题,再优化“跑得快”。
|
||||||
如果要提高响应速度,需要更换各组件来解决。以下是本项目各组件的响应速度测试Tip。
|
如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺):
|
||||||
|
|
||||||
以下内容和结论仅供参考,不构成任何形式的承诺或保证。
|
#### LLM 类组件
|
||||||
|
|
||||||
### LLM 类组件
|
|
||||||
|
|
||||||
| 排名 | 组件名称 | 响应速度(ms) |
|
| 排名 | 组件名称 | 响应速度(ms) |
|
||||||
|:---|:------------|:--------:|
|
|:---:|:---------------:|:------------:|
|
||||||
| 1 | AliLLM | 630 |
|
| 1 | AliLLM | 630 |
|
||||||
| 2 | ChatGLMLLM | 2000 |
|
| 2 | ChatGLMLLM | 2000 |
|
||||||
| 3 | DeepSeekLLM | 6800 |
|
| 3 | DeepSeekLLM | 6800 |
|
||||||
|
|
||||||
```
|
```
|
||||||
测试地点:广东省佛山市禅城区
|
测试地点:广东省佛山市禅城区
|
||||||
测试时间:2025年2月9日 16:12
|
测试时间:2025年2月9日 16:12
|
||||||
宽带运营商:中国移动
|
宽带运营商:中国移动
|
||||||
测试方法:更换配置后,执行core/utils/llm.py文件
|
测试方法:更换配置后,执行 core/utils/llm.py 文件
|
||||||
```
|
```
|
||||||
|
|
||||||
### TTS 类组件
|
#### TTS 类组件
|
||||||
|
|
||||||
| 排名 | 组件名称 | 响应速度(ms) |
|
| 排名 | 组件名称 | 响应速度(ms) |
|
||||||
|:---|:----------|:--------:|
|
|:---:|:--------------:|:------------:|
|
||||||
| 1 | DoubaoTTS | 645 |
|
| 1 | DoubaoTTS | 645 |
|
||||||
| 2 | EdgeTTS | 1019 |
|
| 2 | EdgeTTS | 1019 |
|
||||||
|
|
||||||
```
|
```
|
||||||
测试地点:广东省佛山市禅城区
|
测试地点:广东省佛山市禅城区
|
||||||
测试时间:2025年2月9日 16:12
|
测试时间:2025年2月9日 16:12
|
||||||
宽带运营商:中国移动
|
宽带运营商:中国移动
|
||||||
测试方法:更换配置后,执行core/utils/tts.py文件
|
测试方法:更换配置后,执行 core/utils/tts.py 文件
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 结论
|
### 结论 🔍
|
||||||
|
|
||||||
`2025年2月9日`,如果我的电脑在`广东省佛山市禅城区`,且使用的是`中国移动`网络,我会优先使用:
|
`2025年2月9日`,如果我的电脑在`广东省佛山市禅城区`,且使用的是`中国移动`网络,我会优先使用:
|
||||||
|
|
||||||
- LLM:`AliLLM`
|
- LLM:`AliLLM`
|
||||||
- TTS:`DoubaoTTS`
|
- TTS:`DoubaoTTS`
|
||||||
|
|
||||||
## 5、更多问题,可联系我们反馈
|
### 5、更多问题,可联系我们反馈 💬
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
# 鸣谢
|
---
|
||||||
|
|
||||||
- 本项目受[百聆语音对话机器人](https://github.com/wwbin2017/bailing)项目启发,基于该项目的基础思路完成实现。
|
## 鸣谢 🙏
|
||||||
- 感谢[腾讯云](https://cloud.tencent.com/)为本次项目提供免费docker镜像空间。
|
|
||||||
- 感谢[十方融海](https://www.tenclass.com/)在小智通讯协议上提供充分的文档支持。
|
- 本项目受 [百聆语音对话机器人](https://github.com/wwbin2017/bailing) 启发,并在其基础上实现。
|
||||||
|
- 感谢 [腾讯云](https://cloud.tencent.com/) 提供免费 Docker 镜像空间。
|
||||||
|
- 感谢 [十方融海](https://www.tenclass.com/) 对小智通讯协议提供的详尽文档支持。
|
||||||
|
|
||||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||||
<picture>
|
<picture>
|
||||||
|
|
|
||||||
|
|
@ -1 +1 @@
|
||||||
VITE_API_BASE_URL=''
|
VITE_API_BASE_URL='http://127.0.0.1:8002'
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,27 @@
|
||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en" style="height: 100%;">
|
<html lang="en" style="height: 100%;">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8"/>
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" href="/favicon.ico"/>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||||
<title>智控台</title>
|
<title>智控台</title>
|
||||||
<style>
|
<style>
|
||||||
html, body {
|
html, body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
#app {
|
|
||||||
height: 100%;
|
#app {
|
||||||
width: 100%;
|
height: 100%;
|
||||||
}
|
width: 100%;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script type="module" src="/src/main.js"></script>
|
<script type="module" src="/src/main.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,8 @@
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"vue": "^3.5.10"
|
"vue": "^3.5.10",
|
||||||
|
"vue-router": "^4.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-vue": "^5.1.4",
|
"@vitejs/plugin-vue": "^5.1.4",
|
||||||
|
|
|
||||||
BIN
ZhiKongTaiWeb/public/favicon.ico
Normal file
BIN
ZhiKongTaiWeb/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
|
|
@ -1,64 +1,19 @@
|
||||||
<template>
|
<template>
|
||||||
<div id="app">
|
<div id="app">
|
||||||
<div class="app-content" :class="{ 'auth-layout': !isLoggedIn }">
|
<div class="app-content">
|
||||||
<div v-if="!isLoggedIn">
|
<router-view></router-view>
|
||||||
<Login v-if="!showRegistration" @show-registration="showRegistration = true" @login-success="handleLoginSuccess" />
|
|
||||||
<Registration v-else @show-login="showRegistration = false" />
|
|
||||||
</div>
|
|
||||||
<div v-else class="main-layout">
|
|
||||||
<role-setting v-if="currentView === 'RoleSetting'"
|
|
||||||
:device-id="selectedDeviceId"
|
|
||||||
@back-to-panel="switchView('panel')"/>
|
|
||||||
<panel v-else-if="currentView === 'panel'"
|
|
||||||
@go-home="switchView('main')"
|
|
||||||
@show-role="handleShowRole"
|
|
||||||
/>
|
|
||||||
<main-page v-else @enter-panel="switchView('panel')"/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<Footer />
|
<Footer />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import Login from './components/Login.vue';
|
|
||||||
import Registration from './components/Registration.vue';
|
|
||||||
import panel from './components/panel.vue';
|
|
||||||
import MainPage from './components/Main.vue';
|
|
||||||
import RoleSetting from './components/RoleSetting.vue';
|
|
||||||
import Footer from './components/Footer.vue';
|
import Footer from './components/Footer.vue';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'App',
|
name: 'App',
|
||||||
components: {
|
components: {
|
||||||
Login,
|
|
||||||
Registration,
|
|
||||||
panel,
|
|
||||||
MainPage,
|
|
||||||
RoleSetting,
|
|
||||||
Footer
|
Footer
|
||||||
},
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
showRegistration: false,
|
|
||||||
isLoggedIn: false,
|
|
||||||
currentView: 'main',
|
|
||||||
selectedDeviceId: null // 添加selectedDeviceId状态
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
handleLoginSuccess() {
|
|
||||||
this.isLoggedIn = true;
|
|
||||||
this.currentView = 'panel';
|
|
||||||
},
|
|
||||||
switchView(view) {
|
|
||||||
console.log('Switching to view:', view); // 添加调试日志
|
|
||||||
this.currentView = view;
|
|
||||||
},
|
|
||||||
handleShowRole(deviceId) {
|
|
||||||
this.selectedDeviceId = deviceId;
|
|
||||||
this.switchView('RoleSetting');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
@ -69,17 +24,16 @@ export default {
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
-moz-osx-font-smoothing: grayscale;
|
-moz-osx-font-smoothing: grayscale;
|
||||||
color: #2c3e50;
|
color: #2c3e50;
|
||||||
width: 100%;
|
min-height: 100vh;
|
||||||
height: 100%;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
.app-content {
|
.app-content {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
width: 100%;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
min-height: 0; /* 允许内容区域收缩 */
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 登录注册页面的布局 */
|
/* 登录注册页面的布局 */
|
||||||
|
|
@ -92,8 +46,28 @@ export default {
|
||||||
/* 主要页面的布局 */
|
/* 主要页面的布局 */
|
||||||
.main-layout {
|
.main-layout {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
width: 100%;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
min-height: 0; /* 允许内容区域收缩 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 添加全局滚动条样式 */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: #f1f1f1;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #999;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
BIN
ZhiKongTaiWeb/src/assets/favicon.ico
Normal file
BIN
ZhiKongTaiWeb/src/assets/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
|
|
@ -16,7 +16,7 @@
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="device-actions">
|
<div class="device-actions">
|
||||||
<button class="action-btn primary" @click="$emit('configure')">配置角色</button>
|
<button class="action-btn primary" @click="handleConfigure">配置角色</button>
|
||||||
<button class="action-btn" @click="$emit('voiceprint')">声纹识别</button>
|
<button class="action-btn" @click="$emit('voiceprint')">声纹识别</button>
|
||||||
<button class="action-btn" @click="$emit('history')">历史对话</button>
|
<button class="action-btn" @click="$emit('history')">历史对话</button>
|
||||||
<div class="delete-container">
|
<div class="delete-container">
|
||||||
|
|
@ -81,6 +81,18 @@ const handleDelete = () => {
|
||||||
emit('delete');
|
emit('delete');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleConfigure = () => {
|
||||||
|
// 保存设备配置到 localStorage,确保 RoleSetting 可以访问
|
||||||
|
if (props.deviceId && props.deviceConfig) {
|
||||||
|
localStorage.setItem(`deviceConfig_${props.deviceId}`, JSON.stringify({
|
||||||
|
selected_module: props.selectedModules,
|
||||||
|
prompt: props.deviceConfig.prompt || '',
|
||||||
|
nickname: props.deviceConfig.nickname || '小智'
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
emit('configure');
|
||||||
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
|
||||||
|
|
@ -12,148 +12,138 @@
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" :disabled="isLoading">登录</button>
|
<button type="submit" :disabled="isLoading">登录</button>
|
||||||
</form>
|
</form>
|
||||||
<p>还没注册账户? <a href="#" @click.prevent="$emit('show-registration')">点击注册</a></p>
|
<p>还没注册账户? <router-link to="/register">点击注册</router-link></p>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script setup>
|
||||||
import { API_BASE_URL } from '../config/api';
|
import { ref } from 'vue';
|
||||||
|
import { useRouter } from 'vue-router';
|
||||||
|
import apiClient from '../utils/api';
|
||||||
|
|
||||||
export default {
|
const router = useRouter();
|
||||||
data() {
|
const username = ref('');
|
||||||
return {
|
const password = ref('');
|
||||||
username: '',
|
const isLoading = ref(false);
|
||||||
password: '',
|
|
||||||
isLoading: false
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
async handleLogin() {
|
|
||||||
if (!this.username || !this.password) {
|
|
||||||
alert('请输入用户名和密码!');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.isLoading = true;
|
const handleLogin = async () => {
|
||||||
try {
|
if (!username.value || !password.value) {
|
||||||
const response = await fetch(`${API_BASE_URL}/api/login`, {
|
alert('请输入用户名和密码!');
|
||||||
method: 'POST',
|
return;
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
username: this.username,
|
|
||||||
password: this.password
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (data.success) {
|
|
||||||
// 登录成功
|
|
||||||
this.$emit('login-success');
|
|
||||||
} else {
|
|
||||||
// 登录失败
|
|
||||||
alert(data.message || '登录失败');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Login error:', error);
|
|
||||||
alert('登录失败,请检查网络连接');
|
|
||||||
} finally {
|
|
||||||
this.isLoading = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.login-container {
|
|
||||||
max-width: 420px;
|
|
||||||
margin: 20px auto;
|
|
||||||
padding: 40px 50px;
|
|
||||||
border: none;
|
|
||||||
border-radius: 12px;
|
|
||||||
background-color: #ffffff;
|
|
||||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
|
||||||
transition: all 0.3s ease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
isLoading.value = true;
|
||||||
text-align: center;
|
try {
|
||||||
color: #2c3e50;
|
const response = await apiClient.post('/api/login', {
|
||||||
font-size: 28px;
|
username: username.value,
|
||||||
margin-bottom: 25px;
|
password: password.value
|
||||||
font-weight: 600;
|
});
|
||||||
}
|
|
||||||
|
|
||||||
.form-group {
|
const data = response.data;
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
if (data.success) {
|
||||||
display: block;
|
localStorage.setItem('session_id', data.session_id);
|
||||||
margin-bottom: 8px;
|
localStorage.setItem('isLoggedIn', 'true');
|
||||||
font-weight: 500;
|
router.push('/panel');
|
||||||
color: #4a5568;
|
} else {
|
||||||
|
alert(data.message || '登录失败');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Login error:', error);
|
||||||
|
alert('登录失败,请检查网络连接');
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false;
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
input {
|
<style scoped>
|
||||||
width: 100%;
|
.login-container {
|
||||||
padding: 12px 16px;
|
max-width: 420px;
|
||||||
border: 1px solid #e2e8f0;
|
margin: 20px auto;
|
||||||
border-radius: 8px;
|
padding: 40px 50px;
|
||||||
background-color: #f8fafc;
|
border: none;
|
||||||
transition: all 0.3s ease;
|
border-radius: 12px;
|
||||||
font-size: 15px;
|
background-color: #ffffff;
|
||||||
}
|
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
input:focus {
|
h1 {
|
||||||
outline: none;
|
text-align: center;
|
||||||
border-color: #28a745;
|
color: #2c3e50;
|
||||||
box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.2);
|
font-size: 28px;
|
||||||
}
|
margin-bottom: 25px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
button {
|
.form-group {
|
||||||
width: 100%;
|
margin-bottom: 20px;
|
||||||
padding: 12px;
|
}
|
||||||
background-color: #28a745;
|
|
||||||
color: white;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 16px;
|
|
||||||
font-weight: 500;
|
|
||||||
transition: all 0.3s ease;
|
|
||||||
margin-top: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:hover {
|
label {
|
||||||
background-color: #218838;
|
display: block;
|
||||||
transform: translateY(-1px);
|
margin-bottom: 8px;
|
||||||
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.2);
|
font-weight: 500;
|
||||||
}
|
color: #4a5568;
|
||||||
|
}
|
||||||
|
|
||||||
button:disabled {
|
input {
|
||||||
opacity: 0.7;
|
width: 100%;
|
||||||
cursor: not-allowed;
|
padding: 12px 16px;
|
||||||
}
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background-color: #f8fafc;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
p {
|
input:focus {
|
||||||
margin-top: 20px;
|
outline: none;
|
||||||
color: #666;
|
border-color: #28a745;
|
||||||
font-size: 14px;
|
box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
button {
|
||||||
color: #28a745;
|
width: 100%;
|
||||||
text-decoration: none;
|
padding: 12px;
|
||||||
font-weight: 500;
|
background-color: #28a745;
|
||||||
transition: color 0.3s ease;
|
color: white;
|
||||||
}
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
a:hover {
|
button:hover {
|
||||||
color: #218838;
|
background-color: #218838;
|
||||||
text-decoration: underline;
|
transform: translateY(-1px);
|
||||||
}
|
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.2);
|
||||||
</style>
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.7;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin-top: 20px;
|
||||||
|
color: #666;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: #28a745;
|
||||||
|
text-decoration: none;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: color 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
color: #218838;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -22,6 +22,10 @@
|
||||||
<i class="icon-github"></i> Github服务端
|
<i class="icon-github"></i> Github服务端
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<button class="action-button github-button" @click="openGithubWeb">
|
||||||
|
<i class="icon-github"></i> Web客户端
|
||||||
|
</button>
|
||||||
|
|
||||||
<button class="action-button control-panel-button" @click="enterPanel">
|
<button class="action-button control-panel-button" @click="enterPanel">
|
||||||
<i class="icon-control-panel"></i> 控制台
|
<i class="icon-control-panel"></i> 控制台
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -33,7 +37,9 @@
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import NavBar from './NavBar.vue';
|
import NavBar from './NavBar.vue';
|
||||||
const emit = defineEmits(['enter-panel']);
|
import { useRouter } from 'vue-router';
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
const openTutorial = () => {
|
const openTutorial = () => {
|
||||||
window.open('https://ccnphfhqs21z.feishu.cn/wiki/F5krwD16viZoF0kKkvDcrZNYnhb', '_blank');
|
window.open('https://ccnphfhqs21z.feishu.cn/wiki/F5krwD16viZoF0kKkvDcrZNYnhb', '_blank');
|
||||||
|
|
@ -47,13 +53,17 @@ const openGithubServer = () => {
|
||||||
window.open('https://github.com/xinnan-tech/xiaozhi-esp32-server', '_blank');
|
window.open('https://github.com/xinnan-tech/xiaozhi-esp32-server', '_blank');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openGithubWeb = () => {
|
||||||
|
window.open('https://github.com/TOM88812/xiaozhi-web-client', '_blank');
|
||||||
|
};
|
||||||
|
|
||||||
const enterPanel = () => {
|
const enterPanel = () => {
|
||||||
emit('enter-panel');
|
router.push('/panel');
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleTabChange = (tab) => {
|
const handleTabChange = (tab) => {
|
||||||
if (tab === 'device') {
|
if (tab === 'device') {
|
||||||
emit('enter-panel');
|
router.push('/panel');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
<template>
|
<template>
|
||||||
<header class="header">
|
<header class="header">
|
||||||
<div class="nav-item" :class="{ active: currentTab === 'home' }" @click="switchTab('home')">小智 AI</div>
|
<div class="nav-item" :class="{ active: $route.path === '/' }" @click="switchTab('/')">小智 AI</div>
|
||||||
<nav class="nav">
|
<nav class="nav">
|
||||||
<div class="nav-item" :class="{ active: currentTab === 'device' }" @click="switchTab('device')">
|
<div class="nav-item" :class="{ active: $route.path === '/panel' }" @click="switchTab('/panel')">
|
||||||
<i class="icon-device"></i> 设备管理
|
<i class="icon-device"></i> 设备管理
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
@ -10,14 +10,13 @@
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
const props = defineProps({
|
import { useRouter, useRoute } from 'vue-router';
|
||||||
currentTab: String
|
|
||||||
});
|
|
||||||
|
|
||||||
const emit = defineEmits(['tab-change']);
|
const router = useRouter();
|
||||||
|
const route = useRoute();
|
||||||
|
|
||||||
const switchTab = (tab) => {
|
const switchTab = (path) => {
|
||||||
emit('tab-change', tab);
|
router.push(path);
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,72 +18,66 @@
|
||||||
</form>
|
</form>
|
||||||
<p>
|
<p>
|
||||||
已有账号?
|
已有账号?
|
||||||
<a href="#" @click.prevent="$emit('show-login')">点击登录</a>
|
<router-link to="/login">点击登录</router-link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script setup>
|
||||||
|
import { ref } from 'vue';
|
||||||
|
import { useRouter } from 'vue-router';
|
||||||
import { API_BASE_URL } from '../config/api';
|
import { API_BASE_URL } from '../config/api';
|
||||||
|
|
||||||
export default {
|
const router = useRouter();
|
||||||
data() {
|
const username = ref('');
|
||||||
return {
|
const password = ref('');
|
||||||
username: '',
|
const confirmPassword = ref('');
|
||||||
password: '',
|
const isLoading = ref(false);
|
||||||
confirmPassword: '',
|
|
||||||
isLoading: false
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
async handleRegistration() {
|
|
||||||
if (this.password !== this.confirmPassword) {
|
|
||||||
alert('密码不匹配,请重试!');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.username || !this.password) {
|
const handleRegistration = async () => {
|
||||||
alert('用户名和密码不能为空!');
|
if (password.value !== confirmPassword.value) {
|
||||||
return;
|
alert('密码不匹配,请重试!');
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.isLoading = true;
|
if (!username.value || !password.value) {
|
||||||
try {
|
alert('用户名和密码不能为空!');
|
||||||
const response = await fetch(`${API_BASE_URL}/api/register`, {
|
return;
|
||||||
method: 'POST',
|
}
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
username: this.username,
|
|
||||||
password: this.password
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
isLoading.value = true;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/api/register`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: username.value,
|
||||||
|
password: password.value
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
if (data.success) {
|
const data = await response.json();
|
||||||
alert('注册成功!即将跳转到登录页面。');
|
|
||||||
// 清空表单数据
|
|
||||||
this.username = '';
|
|
||||||
this.password = '';
|
|
||||||
this.confirmPassword = '';
|
|
||||||
|
|
||||||
// 延迟跳转到登录页面
|
if (data.success) {
|
||||||
setTimeout(() => {
|
alert('注册成功!即将跳转到登录页面。');
|
||||||
this.$emit('show-login');
|
// 清空表单数据
|
||||||
}, 100);
|
username.value = '';
|
||||||
} else {
|
password.value = '';
|
||||||
alert(data.message || '注册失败');
|
confirmPassword.value = '';
|
||||||
}
|
|
||||||
} catch (error) {
|
// 使用路由导航到登录页面
|
||||||
console.error('Registration error:', error);
|
router.push('/login');
|
||||||
alert('注册失败,请检查网络连接');
|
} else {
|
||||||
} finally {
|
alert(data.message || '注册失败');
|
||||||
this.isLoading = false;
|
}
|
||||||
}
|
} catch (error) {
|
||||||
},
|
console.error('Registration error:', error);
|
||||||
},
|
alert('注册失败,请检查网络连接');
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@
|
||||||
|
|
||||||
<!-- Breadcrumb -->
|
<!-- Breadcrumb -->
|
||||||
<div class="breadcrumb">
|
<div class="breadcrumb">
|
||||||
<router-link to="/control-panel">控制台</router-link> /
|
<router-link to="/">首页</router-link> /
|
||||||
<router-link to="/device-management">设备管理</router-link> /
|
<router-link to="/panel">设备管理</router-link> /
|
||||||
<span>配置角色</span>
|
<span>配置角色</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -107,12 +107,16 @@
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted } from 'vue';
|
import { ref, onMounted } from 'vue';
|
||||||
|
import { useRouter, useRoute } from 'vue-router';
|
||||||
import NavBar from './NavBar.vue';
|
import NavBar from './NavBar.vue';
|
||||||
import RoleTemplates from '../utils/RoleTemplates';
|
import RoleTemplates from '../utils/RoleTemplates';
|
||||||
import { API_BASE_URL } from '../config/api';
|
import apiClient from '../utils/api'; // 替换 API_BASE_URL 导入
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
const route = useRoute();
|
||||||
|
const deviceId = ref(route.params.deviceId);
|
||||||
|
|
||||||
const roleTemplates = RoleTemplates.getTemplates();
|
const roleTemplates = RoleTemplates.getTemplates();
|
||||||
|
|
||||||
const nickname = ref('小智');
|
const nickname = ref('小智');
|
||||||
const selectedTemplate = ref('');
|
const selectedTemplate = ref('');
|
||||||
const selectedVoice = ref('qingchun');
|
const selectedVoice = ref('qingchun');
|
||||||
|
|
@ -121,7 +125,6 @@ const activeMemoryTab = ref('recent');
|
||||||
const memoryContent = ref('');
|
const memoryContent = ref('');
|
||||||
const selectedModel = ref('qianwen');
|
const selectedModel = ref('qianwen');
|
||||||
|
|
||||||
const baseUrl = API_BASE_URL;
|
|
||||||
const moduleOptions = ref({
|
const moduleOptions = ref({
|
||||||
LLM: [],
|
LLM: [],
|
||||||
TTS: [],
|
TTS: [],
|
||||||
|
|
@ -144,30 +147,12 @@ const selectTemplate = (templateId) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const emit = defineEmits(['back-to-panel']);
|
|
||||||
|
|
||||||
const handleBack = () => {
|
|
||||||
console.log('Triggering back-to-panel event'); // 添加调试日志
|
|
||||||
emit('back-to-panel');
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleTabChange = (tab) => {
|
const handleTabChange = (tab) => {
|
||||||
if (tab === 'device' || tab === 'home') {
|
if (tab === 'device' || tab === 'home') {
|
||||||
emit('back-to-panel');
|
router.push('/panel');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 修改deviceId的定义,接收props
|
|
||||||
const props = defineProps({
|
|
||||||
deviceId: {
|
|
||||||
type: String,
|
|
||||||
required: true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 使用props中的deviceId替换原来的静态值
|
|
||||||
const deviceId = ref(props.deviceId);
|
|
||||||
|
|
||||||
const loadModuleOptions = async () => {
|
const loadModuleOptions = async () => {
|
||||||
try {
|
try {
|
||||||
// First try to load from cache
|
// First try to load from cache
|
||||||
|
|
@ -184,15 +169,15 @@ const loadModuleOptions = async () => {
|
||||||
|
|
||||||
const refreshModuleOptions = async () => {
|
const refreshModuleOptions = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${baseUrl}/api/config/module-options`);
|
const response = await apiClient.get('/api/config/module-options');
|
||||||
const data = await response.json();
|
if (response.data.success) {
|
||||||
if (data.success) {
|
moduleOptions.value = response.data.data;
|
||||||
moduleOptions.value = data.data;
|
|
||||||
// Update cache
|
// Update cache
|
||||||
localStorage.setItem('moduleOptions', JSON.stringify(data.data));
|
localStorage.setItem('moduleOptions', JSON.stringify(response.data.data));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error refreshing module options:', error);
|
console.error('Error refreshing module options:', error);
|
||||||
|
alert(error.response?.data?.message || '刷新配置选项失败');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -208,7 +193,7 @@ const saveConfig = async () => {
|
||||||
|
|
||||||
// Prepare the configuration including full module settings
|
// Prepare the configuration including full module settings
|
||||||
const config = {
|
const config = {
|
||||||
id: props.deviceId,
|
id: deviceId.value,
|
||||||
config: {
|
config: {
|
||||||
selected_module: selectedModules.value,
|
selected_module: selectedModules.value,
|
||||||
prompt: processedDescription,
|
prompt: processedDescription,
|
||||||
|
|
@ -222,64 +207,68 @@ const saveConfig = async () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await fetch(`${baseUrl}/api/config/save_device_config`, {
|
const response = await apiClient.post('/api/config/save_device_config', config);
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify(config)
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
if (response.data.success) {
|
||||||
if (data.success) {
|
|
||||||
// Save the original description and nickname to local storage
|
// Save the original description and nickname to local storage
|
||||||
localStorage.setItem(`deviceConfig_${props.deviceId}`, JSON.stringify({
|
localStorage.setItem(`deviceConfig_${deviceId.value}`, JSON.stringify({
|
||||||
selected_module: selectedModules.value,
|
selected_module: selectedModules.value,
|
||||||
prompt: roleDescription.value,
|
prompt: roleDescription.value,
|
||||||
nickname: nickname.value
|
nickname: nickname.value
|
||||||
}));
|
}));
|
||||||
alert('保存成功');
|
alert('保存成功');
|
||||||
} else {
|
} else {
|
||||||
throw new Error(data.message || '保存失败');
|
throw new Error(response.data.message || '保存失败');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error saving config:', error);
|
console.error('Error saving config:', error);
|
||||||
alert(error.message || '保存失败');
|
alert(error.response?.data?.message || '保存失败');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadDeviceConfig = async () => {
|
const loadDeviceConfig = async () => {
|
||||||
try {
|
try {
|
||||||
// First try to get config from local storage
|
// 首先尝试从 localStorage 获取配置
|
||||||
const localConfig = localStorage.getItem(`deviceConfig_${props.deviceId}`);
|
const localConfig = localStorage.getItem(`deviceConfig_${deviceId.value}`);
|
||||||
if (localConfig) {
|
if (localConfig) {
|
||||||
const config = JSON.parse(localConfig);
|
const config = JSON.parse(localConfig);
|
||||||
selectedModules.value = config.selected_module || {};
|
selectedModules.value = config.selected_module || {
|
||||||
|
LLM: '',
|
||||||
|
TTS: '',
|
||||||
|
VAD: '',
|
||||||
|
ASR: ''
|
||||||
|
};
|
||||||
roleDescription.value = config.prompt || '';
|
roleDescription.value = config.prompt || '';
|
||||||
nickname.value = config.nickname || '小智'; // Load saved nickname
|
nickname.value = config.nickname || '小智';
|
||||||
return;
|
return; // 如果找到本地配置就直接返回
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no local config, fetch from server
|
// 如果没有本地配置,则从服务器获取
|
||||||
const response = await fetch(`${baseUrl}/api/config/devices`);
|
const response = await apiClient.get('/api/config/devices');
|
||||||
const data = await response.json();
|
if (response.data.success && response.data.data) {
|
||||||
if (data.success) {
|
const deviceConfig = response.data.data[deviceId.value];
|
||||||
const deviceConfig = data.data.find(d => d.id === props.deviceId);
|
|
||||||
if (deviceConfig) {
|
|
||||||
selectedModules.value = deviceConfig.config.selected_module || {};
|
|
||||||
roleDescription.value = deviceConfig.config.prompt || '';
|
|
||||||
nickname.value = deviceConfig.config.nickname || '小智'; // Load nickname from server
|
|
||||||
|
|
||||||
// Save to local storage
|
if (deviceConfig && deviceConfig.config) {
|
||||||
localStorage.setItem(`deviceConfig_${props.deviceId}`, JSON.stringify({
|
selectedModules.value = deviceConfig.config.selected_module || {
|
||||||
selected_module: deviceConfig.config.selected_module,
|
LLM: '',
|
||||||
prompt: deviceConfig.config.prompt,
|
TTS: '',
|
||||||
nickname: deviceConfig.config.nickname
|
VAD: '',
|
||||||
|
ASR: ''
|
||||||
|
};
|
||||||
|
roleDescription.value = deviceConfig.config.prompt || '';
|
||||||
|
nickname.value = deviceConfig.config.nickname || '小智';
|
||||||
|
|
||||||
|
// 保存到 localStorage
|
||||||
|
localStorage.setItem(`deviceConfig_${deviceId.value}`, JSON.stringify({
|
||||||
|
selected_module: selectedModules.value,
|
||||||
|
prompt: roleDescription.value,
|
||||||
|
nickname: nickname.value
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading device config:', error);
|
console.error('Error loading device config:', error);
|
||||||
|
alert(error.response?.data?.message || '加载设备配置失败');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -297,7 +286,7 @@ const resetConfig = async () => {
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.app-container {
|
.app-container {
|
||||||
height: 100%;
|
min-height: 100vh;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
background-color: #f5f7fa;
|
background-color: #f5f7fa;
|
||||||
|
|
@ -313,7 +302,9 @@ const resetConfig = async () => {
|
||||||
max-width: 1000px;
|
max-width: 1000px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 16px 24px;
|
padding: 16px 24px;
|
||||||
overflow: auto;
|
width: 100%;
|
||||||
|
overflow-y: auto;
|
||||||
|
height: calc(100vh - 120px); /* 减去头部和面包屑的高度 */
|
||||||
}
|
}
|
||||||
|
|
||||||
.page-title {
|
.page-title {
|
||||||
|
|
@ -327,6 +318,7 @@ const resetConfig = async () => {
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
||||||
|
margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-group {
|
.form-group {
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,44 @@
|
||||||
<div class="app">
|
<div class="app">
|
||||||
<NavBar current-tab="device" @tab-change="handleTabChange"/>
|
<NavBar current-tab="device" @tab-change="handleTabChange"/>
|
||||||
<main class="content">
|
<main class="content">
|
||||||
<div class="breadcrumb">
|
<div class="page-header">
|
||||||
<router-link to="/control-panel">控制台</router-link> /
|
<div class="header-left">
|
||||||
<span>设备管理</span>
|
|
||||||
|
<div class="breadcrumb">
|
||||||
|
<router-link to="/">首页</router-link> /
|
||||||
|
<span>设备管理</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button class="add-btn" @click="showBindDialog = true">
|
||||||
|
<i class="icon-plus"></i>添加设备
|
||||||
|
</button>
|
||||||
|
<!-- 绑定设备弹窗 -->
|
||||||
|
<div v-if="showBindDialog" class="dialog-overlay">
|
||||||
|
<div class="dialog">
|
||||||
|
<h3>绑定新设备</h3>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>请输入6位认证码:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
v-model="authCode"
|
||||||
|
maxlength="6"
|
||||||
|
pattern="\d*"
|
||||||
|
placeholder="请输入6位数字认证码"
|
||||||
|
@input="handleAuthCodeInput"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="dialog-buttons">
|
||||||
|
<button @click="showBindDialog = false">取消</button>
|
||||||
|
<button
|
||||||
|
class="primary"
|
||||||
|
@click="handleBindDevice"
|
||||||
|
:disabled="authCode.length !== 6 || isBinding"
|
||||||
|
>
|
||||||
|
{{ isBinding ? '绑定中...' : '确认绑定' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template v-if="devices.length > 0">
|
<template v-if="devices.length > 0">
|
||||||
|
|
@ -25,35 +60,93 @@
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
|
||||||
<div class="empty-state">
|
|
||||||
<div class="empty-message">
|
|
||||||
<i class="icon-info"></i>
|
|
||||||
<p>目前没有设备,请确认是否启用私有配置,并且和设备进行一次对话</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted } from 'vue';
|
import { ref, onMounted } from 'vue';
|
||||||
|
import { useRouter } from 'vue-router';
|
||||||
import NavBar from './NavBar.vue';
|
import NavBar from './NavBar.vue';
|
||||||
import DeviceCard from './DeviceCard.vue';
|
import DeviceCard from './DeviceCard.vue';
|
||||||
import { API_BASE_URL } from '../config/api';
|
import apiClient from '../utils/api';
|
||||||
|
|
||||||
const emit = defineEmits(['show-role', 'go-home']);
|
const router = useRouter();
|
||||||
|
|
||||||
const baseUrl = API_BASE_URL;
|
|
||||||
const devices = ref([]);
|
const devices = ref([]);
|
||||||
|
|
||||||
|
// 绑定设备相关的状态
|
||||||
|
const showBindDialog = ref(false);
|
||||||
|
const authCode = ref('');
|
||||||
|
const isBinding = ref(false);
|
||||||
|
|
||||||
|
// 处理认证码输入,只允许数字
|
||||||
|
const handleAuthCodeInput = (event) => {
|
||||||
|
authCode.value = event.target.value.replace(/\D/g, '').slice(0, 6);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 处理设备绑定
|
||||||
|
const handleBindDevice = async () => {
|
||||||
|
if (authCode.value.length !== 6) {
|
||||||
|
alert('请输入6位数字认证码');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
isBinding.value = true;
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post('/api/config/bind_device', {
|
||||||
|
auth_code: authCode.value
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.data.success) {
|
||||||
|
alert('设备绑定成功');
|
||||||
|
showBindDialog.value = false;
|
||||||
|
authCode.value = '';
|
||||||
|
// 刷新设备列表
|
||||||
|
loadDevices();
|
||||||
|
} else {
|
||||||
|
throw new Error(response.data.message);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
alert(error.response?.data?.message || error.message || '绑定失败');
|
||||||
|
} finally {
|
||||||
|
isBinding.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 将现有的加载设备方法提取出来
|
||||||
|
const loadDevices = async () => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get('/api/config/devices');
|
||||||
|
|
||||||
|
if (response.data.success) {
|
||||||
|
const deviceArray = Object.entries(response.data.data).map(([id, config]) => ({
|
||||||
|
id,
|
||||||
|
config,
|
||||||
|
type: '面包板(WiFi)',
|
||||||
|
version: '0.9.9',
|
||||||
|
lastActivity: '3 天前',
|
||||||
|
note: ''
|
||||||
|
}));
|
||||||
|
devices.value = deviceArray;
|
||||||
|
} else {
|
||||||
|
throw new Error(response.data.message || '加载设备失败');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading devices:', error);
|
||||||
|
// Show error message to user
|
||||||
|
const errorMessage = error.message || '加载设备失败,请检查网络连接';
|
||||||
|
alert(errorMessage);
|
||||||
|
|
||||||
|
// If user is not logged in, redirect will be handled by api interceptor
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const formatLastActivity = (timestamp) => {
|
const formatLastActivity = (timestamp) => {
|
||||||
console.log('Formatting timestamp:', timestamp);
|
|
||||||
if (!timestamp) return '从未对话';
|
if (!timestamp) return '从未对话';
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const lastChat = timestamp * 1000; // Convert to milliseconds
|
const lastChat = timestamp * 1000;
|
||||||
const diffMinutes = Math.floor((now - lastChat) / (1000 * 60));
|
const diffMinutes = Math.floor((now - lastChat) / (1000 * 60));
|
||||||
|
|
||||||
if (diffMinutes < 60) {
|
if (diffMinutes < 60) {
|
||||||
|
|
@ -69,10 +162,16 @@ const formatLastActivity = (timestamp) => {
|
||||||
return `${diffDays} 天前`;
|
return `${diffDays} 天前`;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Event handlers
|
|
||||||
const handleRoleConfig = (device) => {
|
const handleRoleConfig = (device) => {
|
||||||
console.log('Configure device:', device.id);
|
// 在跳转前保存完整的设备配置到 localStorage
|
||||||
emit('show-role', device.id);
|
localStorage.setItem(`deviceConfig_${device.id}`, JSON.stringify({
|
||||||
|
selected_module: device.config.selected_module || {},
|
||||||
|
prompt: device.config.prompt || '',
|
||||||
|
nickname: device.config.nickname || '小智'
|
||||||
|
}));
|
||||||
|
|
||||||
|
// 跳转到角色配置页面
|
||||||
|
router.push(`/role-setting/${device.id}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleVoiceprint = (device) => {
|
const handleVoiceprint = (device) => {
|
||||||
|
|
@ -85,20 +184,15 @@ const handleHistory = (device) => {
|
||||||
|
|
||||||
const handleDelete = async (device) => {
|
const handleDelete = async (device) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${baseUrl}/api/config/delete_device`, {
|
const response = await apiClient.post('/api/config/delete_device', {
|
||||||
method: 'POST',
|
device_id: device.id
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ device_id: device.id })
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
if (response.data.success) {
|
||||||
if (data.success) {
|
|
||||||
devices.value = devices.value.filter(d => d.id !== device.id);
|
devices.value = devices.value.filter(d => d.id !== device.id);
|
||||||
alert('设备已删除');
|
alert('设备已删除');
|
||||||
} else {
|
} else {
|
||||||
throw new Error(data.message || '删除失败');
|
throw new Error(response.data.message || '删除失败');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error deleting device:', error);
|
console.error('Error deleting device:', error);
|
||||||
|
|
@ -108,29 +202,12 @@ const handleDelete = async (device) => {
|
||||||
|
|
||||||
const handleTabChange = (tab) => {
|
const handleTabChange = (tab) => {
|
||||||
if (tab === 'home') {
|
if (tab === 'home') {
|
||||||
emit('go-home');
|
router.push('/');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Load devices on mount
|
// Load devices on mount
|
||||||
onMounted(async () => {
|
onMounted(loadDevices);
|
||||||
try {
|
|
||||||
const response = await fetch(`${baseUrl}/api/config/devices`);
|
|
||||||
const data = await response.json();
|
|
||||||
if (data.success) {
|
|
||||||
console.log('Loaded devices:', data.data);
|
|
||||||
devices.value = data.data.map(device => ({
|
|
||||||
...device,
|
|
||||||
type: '面包板(WiFi)',
|
|
||||||
version: '0.9.9',
|
|
||||||
lastActivity: '3 天前',
|
|
||||||
note: ''
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error loading devices:', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
@ -309,4 +386,115 @@ onMounted(async () => {
|
||||||
background-size: contain;
|
background-size: contain;
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-start;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-btn {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
background-color: #28a745;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
height: 36px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-btn:hover {
|
||||||
|
background-color: #218838;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-plus {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background-color: rgba(0, 0, 0, 0.5);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog {
|
||||||
|
background: white;
|
||||||
|
padding: 24px;
|
||||||
|
border-radius: 8px;
|
||||||
|
width: 90%;
|
||||||
|
max-width: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog h3 {
|
||||||
|
margin: 0 0 20px;
|
||||||
|
font-size: 18px;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog .form-group {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #4a5568;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog-buttons {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog-buttons button {
|
||||||
|
padding: 8px 16px;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog-buttons button.primary {
|
||||||
|
background-color: #28a745;
|
||||||
|
color: white;
|
||||||
|
border-color: #28a745;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dialog-buttons button.primary:disabled {
|
||||||
|
background-color: #90be9c;
|
||||||
|
border-color: #90be9c;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.breadcrumb {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
@ -1,5 +1,58 @@
|
||||||
import { createApp } from 'vue'
|
import { createApp } from 'vue'
|
||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
import './style.css'
|
import './style.css'
|
||||||
import App from './App.vue'
|
import App from './App.vue'
|
||||||
|
import Login from './components/Login.vue'
|
||||||
|
import Panel from './components/panel.vue'
|
||||||
|
import MainPage from './components/Main.vue'
|
||||||
|
import RoleSetting from './components/RoleSetting.vue'
|
||||||
|
import Registration from './components/Registration.vue'
|
||||||
|
|
||||||
createApp(App).mount('#app')
|
const router = createRouter({
|
||||||
|
history: createWebHistory(),
|
||||||
|
routes: [
|
||||||
|
{
|
||||||
|
path: '/login',
|
||||||
|
component: Login,
|
||||||
|
name: 'login'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/register',
|
||||||
|
component: Registration,
|
||||||
|
name: 'register'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/panel',
|
||||||
|
component: Panel,
|
||||||
|
name: 'panel',
|
||||||
|
meta: { requiresAuth: true }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/role-setting/:deviceId',
|
||||||
|
component: RoleSetting,
|
||||||
|
name: 'role-setting',
|
||||||
|
meta: { requiresAuth: true }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
component: MainPage,
|
||||||
|
name: 'main',
|
||||||
|
meta: { requiresAuth: true }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
router.beforeEach((to, from, next) => {
|
||||||
|
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
|
||||||
|
if (to.meta.requiresAuth && !isLoggedIn) {
|
||||||
|
next('/login')
|
||||||
|
} else if (to.path === '/login' && isLoggedIn) {
|
||||||
|
next('/panel')
|
||||||
|
} else {
|
||||||
|
next()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
app.use(router)
|
||||||
|
app.mount('#app')
|
||||||
|
|
|
||||||
61
ZhiKongTaiWeb/src/utils/api.js
Normal file
61
ZhiKongTaiWeb/src/utils/api.js
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
import axios from 'axios';
|
||||||
|
import { API_BASE_URL } from '../config/api';
|
||||||
|
|
||||||
|
// Add server status check utility
|
||||||
|
export const checkServerStatus = async () => {
|
||||||
|
try {
|
||||||
|
await axios.get(`${API_BASE_URL}/health`, { timeout: 5000 });
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const apiClient = axios.create({
|
||||||
|
baseURL: API_BASE_URL,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
timeout: 10000 // Add timeout
|
||||||
|
});
|
||||||
|
|
||||||
|
// 添加请求拦截器,自动添加 session_id
|
||||||
|
apiClient.interceptors.request.use(config => {
|
||||||
|
const sessionId = localStorage.getItem('session_id');
|
||||||
|
if (sessionId) {
|
||||||
|
config.headers.Authorization = sessionId;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 响应拦截器
|
||||||
|
apiClient.interceptors.response.use(
|
||||||
|
response => response,
|
||||||
|
error => {
|
||||||
|
// Network error or server not reachable
|
||||||
|
if (!error.response || error.code === 'ERR_NETWORK' || error.code === 'ECONNABORTED') {
|
||||||
|
localStorage.removeItem('session_id');
|
||||||
|
localStorage.removeItem('isLoggedIn');
|
||||||
|
|
||||||
|
const errorMessage = error.code === 'ECONNABORTED'
|
||||||
|
? '服务器响应超时'
|
||||||
|
: '无法连接到服务器,请检查服务器是否正常运行';
|
||||||
|
|
||||||
|
if (window.location.pathname !== '/login') {
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
return Promise.reject(new Error(errorMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unauthorized error
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
localStorage.removeItem('session_id');
|
||||||
|
localStorage.removeItem('isLoggedIn');
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export default apiClient;
|
||||||
|
|
@ -7,7 +7,7 @@ export default defineConfig({
|
||||||
server: {
|
server: {
|
||||||
open: true, // 自动启动浏览器
|
open: true, // 自动启动浏览器
|
||||||
host: "0.0.0.0", // localhost
|
host: "0.0.0.0", // localhost
|
||||||
port: 8001, // 端口号
|
port: 8002, // 端口号
|
||||||
https: false,
|
https: false,
|
||||||
hmr: {overlay: false},
|
hmr: {overlay: false},
|
||||||
proxy: {
|
proxy: {
|
||||||
|
|
@ -16,5 +16,6 @@ export default defineConfig({
|
||||||
changeOrigin: true
|
changeOrigin: true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
base: '/'
|
||||||
})
|
})
|
||||||
|
|
|
||||||
475
ZhiKongTaiWeb/yarn.lock
Normal file
475
ZhiKongTaiWeb/yarn.lock
Normal file
|
|
@ -0,0 +1,475 @@
|
||||||
|
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||||
|
# yarn lockfile v1
|
||||||
|
|
||||||
|
|
||||||
|
"@babel/helper-string-parser@^7.25.9":
|
||||||
|
version "7.25.9"
|
||||||
|
resolved "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz#1aabb72ee72ed35789b4bbcad3ca2862ce614e8c"
|
||||||
|
integrity sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==
|
||||||
|
|
||||||
|
"@babel/helper-validator-identifier@^7.25.9":
|
||||||
|
version "7.25.9"
|
||||||
|
resolved "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz#24b64e2c3ec7cd3b3c547729b8d16871f22cbdc7"
|
||||||
|
integrity sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==
|
||||||
|
|
||||||
|
"@babel/parser@^7.25.3":
|
||||||
|
version "7.26.9"
|
||||||
|
resolved "https://registry.npmmirror.com/@babel/parser/-/parser-7.26.9.tgz#d9e78bee6dc80f9efd8f2349dcfbbcdace280fd5"
|
||||||
|
integrity sha512-81NWa1njQblgZbQHxWHpxxCzNsa3ZwvFqpUg7P+NNUU6f3UU2jBEg4OlF/J6rl8+PQGh1q6/zWScd001YwcA5A==
|
||||||
|
dependencies:
|
||||||
|
"@babel/types" "^7.26.9"
|
||||||
|
|
||||||
|
"@babel/types@^7.26.9":
|
||||||
|
version "7.26.9"
|
||||||
|
resolved "https://registry.npmmirror.com/@babel/types/-/types-7.26.9.tgz#08b43dec79ee8e682c2ac631c010bdcac54a21ce"
|
||||||
|
integrity sha512-Y3IR1cRnOxOCDvMmNiym7XpXQ93iGDDPHx+Zj+NM+rg0fBaShfQLkg+hKPaZCEvg5N/LeCo4+Rj/i3FuJsIQaw==
|
||||||
|
dependencies:
|
||||||
|
"@babel/helper-string-parser" "^7.25.9"
|
||||||
|
"@babel/helper-validator-identifier" "^7.25.9"
|
||||||
|
|
||||||
|
"@esbuild/aix-ppc64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz#c7184a326533fcdf1b8ee0733e21c713b975575f"
|
||||||
|
integrity sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==
|
||||||
|
|
||||||
|
"@esbuild/android-arm64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz#09d9b4357780da9ea3a7dfb833a1f1ff439b4052"
|
||||||
|
integrity sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==
|
||||||
|
|
||||||
|
"@esbuild/android-arm@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.21.5.tgz#9b04384fb771926dfa6d7ad04324ecb2ab9b2e28"
|
||||||
|
integrity sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==
|
||||||
|
|
||||||
|
"@esbuild/android-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.21.5.tgz#29918ec2db754cedcb6c1b04de8cd6547af6461e"
|
||||||
|
integrity sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==
|
||||||
|
|
||||||
|
"@esbuild/darwin-arm64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz#e495b539660e51690f3928af50a76fb0a6ccff2a"
|
||||||
|
integrity sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==
|
||||||
|
|
||||||
|
"@esbuild/darwin-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz#c13838fa57372839abdddc91d71542ceea2e1e22"
|
||||||
|
integrity sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==
|
||||||
|
|
||||||
|
"@esbuild/freebsd-arm64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz#646b989aa20bf89fd071dd5dbfad69a3542e550e"
|
||||||
|
integrity sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==
|
||||||
|
|
||||||
|
"@esbuild/freebsd-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz#aa615cfc80af954d3458906e38ca22c18cf5c261"
|
||||||
|
integrity sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==
|
||||||
|
|
||||||
|
"@esbuild/linux-arm64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz#70ac6fa14f5cb7e1f7f887bcffb680ad09922b5b"
|
||||||
|
integrity sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==
|
||||||
|
|
||||||
|
"@esbuild/linux-arm@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz#fc6fd11a8aca56c1f6f3894f2bea0479f8f626b9"
|
||||||
|
integrity sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==
|
||||||
|
|
||||||
|
"@esbuild/linux-ia32@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz#3271f53b3f93e3d093d518d1649d6d68d346ede2"
|
||||||
|
integrity sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==
|
||||||
|
|
||||||
|
"@esbuild/linux-loong64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz#ed62e04238c57026aea831c5a130b73c0f9f26df"
|
||||||
|
integrity sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==
|
||||||
|
|
||||||
|
"@esbuild/linux-mips64el@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz#e79b8eb48bf3b106fadec1ac8240fb97b4e64cbe"
|
||||||
|
integrity sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==
|
||||||
|
|
||||||
|
"@esbuild/linux-ppc64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz#5f2203860a143b9919d383ef7573521fb154c3e4"
|
||||||
|
integrity sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==
|
||||||
|
|
||||||
|
"@esbuild/linux-riscv64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz#07bcafd99322d5af62f618cb9e6a9b7f4bb825dc"
|
||||||
|
integrity sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==
|
||||||
|
|
||||||
|
"@esbuild/linux-s390x@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz#b7ccf686751d6a3e44b8627ababc8be3ef62d8de"
|
||||||
|
integrity sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==
|
||||||
|
|
||||||
|
"@esbuild/linux-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz#6d8f0c768e070e64309af8004bb94e68ab2bb3b0"
|
||||||
|
integrity sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==
|
||||||
|
|
||||||
|
"@esbuild/netbsd-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz#bbe430f60d378ecb88decb219c602667387a6047"
|
||||||
|
integrity sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==
|
||||||
|
|
||||||
|
"@esbuild/openbsd-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz#99d1cf2937279560d2104821f5ccce220cb2af70"
|
||||||
|
integrity sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==
|
||||||
|
|
||||||
|
"@esbuild/sunos-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz#08741512c10d529566baba837b4fe052c8f3487b"
|
||||||
|
integrity sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==
|
||||||
|
|
||||||
|
"@esbuild/win32-arm64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz#675b7385398411240735016144ab2e99a60fc75d"
|
||||||
|
integrity sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==
|
||||||
|
|
||||||
|
"@esbuild/win32-ia32@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz#1bfc3ce98aa6ca9a0969e4d2af72144c59c1193b"
|
||||||
|
integrity sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==
|
||||||
|
|
||||||
|
"@esbuild/win32-x64@0.21.5":
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz#acad351d582d157bb145535db2a6ff53dd514b5c"
|
||||||
|
integrity sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==
|
||||||
|
|
||||||
|
"@jridgewell/sourcemap-codec@^1.5.0":
|
||||||
|
version "1.5.0"
|
||||||
|
resolved "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz#3188bcb273a414b0d215fd22a58540b989b9409a"
|
||||||
|
integrity sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==
|
||||||
|
|
||||||
|
"@rollup/rollup-android-arm-eabi@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.34.7.tgz#e554185b1afa5509a7a4040d15ec0c3b4435ded1"
|
||||||
|
integrity sha512-l6CtzHYo8D2TQ3J7qJNpp3Q1Iye56ssIAtqbM2H8axxCEEwvN7o8Ze9PuIapbxFL3OHrJU2JBX6FIIVnP/rYyw==
|
||||||
|
|
||||||
|
"@rollup/rollup-android-arm64@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.34.7.tgz#b1ee64bb413b2feba39803b0a1bebf2a9f3d70e1"
|
||||||
|
integrity sha512-KvyJpFUueUnSp53zhAa293QBYqwm94TgYTIfXyOTtidhm5V0LbLCJQRGkQClYiX3FXDQGSvPxOTD/6rPStMMDg==
|
||||||
|
|
||||||
|
"@rollup/rollup-darwin-arm64@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.34.7.tgz#bfdce3e07a345dd1bd628f3b796050f39629d7f0"
|
||||||
|
integrity sha512-jq87CjmgL9YIKvs8ybtIC98s/M3HdbqXhllcy9EdLV0yMg1DpxES2gr65nNy7ObNo/vZ/MrOTxt0bE5LinL6mA==
|
||||||
|
|
||||||
|
"@rollup/rollup-darwin-x64@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.34.7.tgz#781a94a537c57bdf0a500e47a25ab5985e5e8dff"
|
||||||
|
integrity sha512-rSI/m8OxBjsdnMMg0WEetu/w+LhLAcCDEiL66lmMX4R3oaml3eXz3Dxfvrxs1FbzPbJMaItQiksyMfv1hoIxnA==
|
||||||
|
|
||||||
|
"@rollup/rollup-freebsd-arm64@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.34.7.tgz#7a028357cbd12c5869c446ad18177c89f3405102"
|
||||||
|
integrity sha512-oIoJRy3ZrdsXpFuWDtzsOOa/E/RbRWXVokpVrNnkS7npz8GEG++E1gYbzhYxhxHbO2om1T26BZjVmdIoyN2WtA==
|
||||||
|
|
||||||
|
"@rollup/rollup-freebsd-x64@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.34.7.tgz#f24836a6371cccc4408db74f0fd986dacf098950"
|
||||||
|
integrity sha512-X++QSLm4NZfZ3VXGVwyHdRf58IBbCu9ammgJxuWZYLX0du6kZvdNqPwrjvDfwmi6wFdvfZ/s6K7ia0E5kI7m8Q==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-arm-gnueabihf@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.34.7.tgz#95f27e96f0eb9b9ae9887739a8b6dffc90c1237f"
|
||||||
|
integrity sha512-Z0TzhrsNqukTz3ISzrvyshQpFnFRfLunYiXxlCRvcrb3nvC5rVKI+ZXPFG/Aa4jhQa1gHgH3A0exHaRRN4VmdQ==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-arm-musleabihf@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.34.7.tgz#677b34fba9d070877736c3fe8b02aacb5e142d97"
|
||||||
|
integrity sha512-nkznpyXekFAbvFBKBy4nNppSgneB1wwG1yx/hujN3wRnhnkrYVugMTCBXED4+Ni6thoWfQuHNYbFjgGH0MBXtw==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-arm64-gnu@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.34.7.tgz#32d3d19dedde54e91574a098f22ea43a09cf63dd"
|
||||||
|
integrity sha512-KCjlUkcKs6PjOcxolqrXglBDcfCuUCTVlX5BgzgoJHw+1rWH1MCkETLkLe5iLLS9dP5gKC7mp3y6x8c1oGBUtA==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-arm64-musl@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.34.7.tgz#a58dff44a18696df65ed8c0ad68a2945cf900484"
|
||||||
|
integrity sha512-uFLJFz6+utmpbR313TTx+NpPuAXbPz4BhTQzgaP0tozlLnGnQ6rCo6tLwaSa6b7l6gRErjLicXQ1iPiXzYotjw==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-loongarch64-gnu@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.34.7.tgz#a7488ab078233111e8aeb370d1ecf107ec7e1716"
|
||||||
|
integrity sha512-ws8pc68UcJJqCpneDFepnwlsMUFoWvPbWXT/XUrJ7rWUL9vLoIN3GAasgG+nCvq8xrE3pIrd+qLX/jotcLy0Qw==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-powerpc64le-gnu@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.34.7.tgz#e9b9c0d6bd248a92b2d6ec01ebf99c62ae1f2e9a"
|
||||||
|
integrity sha512-vrDk9JDa/BFkxcS2PbWpr0C/LiiSLxFbNOBgfbW6P8TBe9PPHx9Wqbvx2xgNi1TOAyQHQJ7RZFqBiEohm79r0w==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-riscv64-gnu@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.34.7.tgz#0df84ce2bea48ee686fb55060d76ab47aff45c4c"
|
||||||
|
integrity sha512-rB+ejFyjtmSo+g/a4eovDD1lHWHVqizN8P0Hm0RElkINpS0XOdpaXloqM4FBkF9ZWEzg6bezymbpLmeMldfLTw==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-s390x-gnu@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.34.7.tgz#73df374c57d036856e33dbd2715138922e91e452"
|
||||||
|
integrity sha512-nNXNjo4As6dNqRn7OrsnHzwTgtypfRA3u3AKr0B3sOOo+HkedIbn8ZtFnB+4XyKJojIfqDKmbIzO1QydQ8c+Pw==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-x64-gnu@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.34.7.tgz#f27af0b55f0cdd84e182e6cd44a6d03da0458149"
|
||||||
|
integrity sha512-9kPVf9ahnpOMSGlCxXGv980wXD0zRR3wyk8+33/MXQIpQEOpaNe7dEHm5LMfyRZRNt9lMEQuH0jUKj15MkM7QA==
|
||||||
|
|
||||||
|
"@rollup/rollup-linux-x64-musl@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.34.7.tgz#c7981ad5cfb8c3cd5d643d33ca54e4d2802b9201"
|
||||||
|
integrity sha512-7wJPXRWTTPtTFDFezA8sle/1sdgxDjuMoRXEKtx97ViRxGGkVQYovem+Q8Pr/2HxiHp74SSRG+o6R0Yq0shPwQ==
|
||||||
|
|
||||||
|
"@rollup/rollup-win32-arm64-msvc@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.34.7.tgz#06cedc0ef3cbf1cbd8abcf587090712e40ae6941"
|
||||||
|
integrity sha512-MN7aaBC7mAjsiMEZcsJvwNsQVNZShgES/9SzWp1HC9Yjqb5OpexYnRjF7RmE4itbeesHMYYQiAtUAQaSKs2Rfw==
|
||||||
|
|
||||||
|
"@rollup/rollup-win32-ia32-msvc@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.34.7.tgz#90b39b977b14961a769be6ea61238e7fc668dd4d"
|
||||||
|
integrity sha512-aeawEKYswsFu1LhDM9RIgToobquzdtSc4jSVqHV8uApz4FVvhFl/mKh92wc8WpFc6aYCothV/03UjY6y7yLgbg==
|
||||||
|
|
||||||
|
"@rollup/rollup-win32-x64-msvc@4.34.7":
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.7.tgz#6531d61e7141091eaab0461ee8e0380c10e4ca57"
|
||||||
|
integrity sha512-4ZedScpxxIrVO7otcZ8kCX1mZArtH2Wfj3uFCxRJ9NO80gg1XV0U/b2f/MKaGwj2X3QopHfoWiDQ917FRpwY3w==
|
||||||
|
|
||||||
|
"@types/estree@1.0.6":
|
||||||
|
version "1.0.6"
|
||||||
|
resolved "https://registry.npmmirror.com/@types/estree/-/estree-1.0.6.tgz#628effeeae2064a1b4e79f78e81d87b7e5fc7b50"
|
||||||
|
integrity sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==
|
||||||
|
|
||||||
|
"@vitejs/plugin-vue@^5.1.4":
|
||||||
|
version "5.2.1"
|
||||||
|
resolved "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-5.2.1.tgz#d1491f678ee3af899f7ae57d9c21dc52a65c7133"
|
||||||
|
integrity sha512-cxh314tzaWwOLqVes2gnnCtvBDcM1UMdn+iFR+UjAn411dPT3tOmqrJjbMd7koZpMAmBM/GqeV4n9ge7JSiJJQ==
|
||||||
|
|
||||||
|
"@vue/compiler-core@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/compiler-core/-/compiler-core-3.5.13.tgz#b0ae6c4347f60c03e849a05d34e5bf747c9bda05"
|
||||||
|
integrity sha512-oOdAkwqUfW1WqpwSYJce06wvt6HljgY3fGeM9NcVA1HaYOij3mZG9Rkysn0OHuyUAGMbEbARIpsG+LPVlBJ5/Q==
|
||||||
|
dependencies:
|
||||||
|
"@babel/parser" "^7.25.3"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
entities "^4.5.0"
|
||||||
|
estree-walker "^2.0.2"
|
||||||
|
source-map-js "^1.2.0"
|
||||||
|
|
||||||
|
"@vue/compiler-dom@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/compiler-dom/-/compiler-dom-3.5.13.tgz#bb1b8758dbc542b3658dda973b98a1c9311a8a58"
|
||||||
|
integrity sha512-ZOJ46sMOKUjO3e94wPdCzQ6P1Lx/vhp2RSvfaab88Ajexs0AHeV0uasYhi99WPaogmBlRHNRuly8xV75cNTMDA==
|
||||||
|
dependencies:
|
||||||
|
"@vue/compiler-core" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
|
||||||
|
"@vue/compiler-sfc@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/compiler-sfc/-/compiler-sfc-3.5.13.tgz#461f8bd343b5c06fac4189c4fef8af32dea82b46"
|
||||||
|
integrity sha512-6VdaljMpD82w6c2749Zhf5T9u5uLBWKnVue6XWxprDobftnletJ8+oel7sexFfM3qIxNmVE7LSFGTpv6obNyaQ==
|
||||||
|
dependencies:
|
||||||
|
"@babel/parser" "^7.25.3"
|
||||||
|
"@vue/compiler-core" "3.5.13"
|
||||||
|
"@vue/compiler-dom" "3.5.13"
|
||||||
|
"@vue/compiler-ssr" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
estree-walker "^2.0.2"
|
||||||
|
magic-string "^0.30.11"
|
||||||
|
postcss "^8.4.48"
|
||||||
|
source-map-js "^1.2.0"
|
||||||
|
|
||||||
|
"@vue/compiler-ssr@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/compiler-ssr/-/compiler-ssr-3.5.13.tgz#e771adcca6d3d000f91a4277c972a996d07f43ba"
|
||||||
|
integrity sha512-wMH6vrYHxQl/IybKJagqbquvxpWCuVYpoUJfCqFZwa/JY1GdATAQ+TgVtgrwwMZ0D07QhA99rs/EAAWfvG6KpA==
|
||||||
|
dependencies:
|
||||||
|
"@vue/compiler-dom" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
|
||||||
|
"@vue/devtools-api@^6.6.4":
|
||||||
|
version "6.6.4"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-6.6.4.tgz#cbe97fe0162b365edc1dba80e173f90492535343"
|
||||||
|
integrity sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==
|
||||||
|
|
||||||
|
"@vue/reactivity@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/reactivity/-/reactivity-3.5.13.tgz#b41ff2bb865e093899a22219f5b25f97b6fe155f"
|
||||||
|
integrity sha512-NaCwtw8o48B9I6L1zl2p41OHo/2Z4wqYGGIK1Khu5T7yxrn+ATOixn/Udn2m+6kZKB/J7cuT9DbWWhRxqixACg==
|
||||||
|
dependencies:
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
|
||||||
|
"@vue/runtime-core@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/runtime-core/-/runtime-core-3.5.13.tgz#1fafa4bf0b97af0ebdd9dbfe98cd630da363a455"
|
||||||
|
integrity sha512-Fj4YRQ3Az0WTZw1sFe+QDb0aXCerigEpw418pw1HBUKFtnQHWzwojaukAs2X/c9DQz4MQ4bsXTGlcpGxU/RCIw==
|
||||||
|
dependencies:
|
||||||
|
"@vue/reactivity" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
|
||||||
|
"@vue/runtime-dom@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/runtime-dom/-/runtime-dom-3.5.13.tgz#610fc795de9246300e8ae8865930d534e1246215"
|
||||||
|
integrity sha512-dLaj94s93NYLqjLiyFzVs9X6dWhTdAlEAciC3Moq7gzAc13VJUdCnjjRurNM6uTLFATRHexHCTu/Xp3eW6yoog==
|
||||||
|
dependencies:
|
||||||
|
"@vue/reactivity" "3.5.13"
|
||||||
|
"@vue/runtime-core" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
csstype "^3.1.3"
|
||||||
|
|
||||||
|
"@vue/server-renderer@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/server-renderer/-/server-renderer-3.5.13.tgz#429ead62ee51de789646c22efe908e489aad46f7"
|
||||||
|
integrity sha512-wAi4IRJV/2SAW3htkTlB+dHeRmpTiVIK1OGLWV1yeStVSebSQQOwGwIq0D3ZIoBj2C2qpgz5+vX9iEBkTdk5YA==
|
||||||
|
dependencies:
|
||||||
|
"@vue/compiler-ssr" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
|
|
||||||
|
"@vue/shared@3.5.13":
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.13.tgz#87b309a6379c22b926e696893237826f64339b6f"
|
||||||
|
integrity sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==
|
||||||
|
|
||||||
|
csstype@^3.1.3:
|
||||||
|
version "3.1.3"
|
||||||
|
resolved "https://registry.npmmirror.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81"
|
||||||
|
integrity sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==
|
||||||
|
|
||||||
|
entities@^4.5.0:
|
||||||
|
version "4.5.0"
|
||||||
|
resolved "https://registry.npmmirror.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48"
|
||||||
|
integrity sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==
|
||||||
|
|
||||||
|
esbuild@^0.21.3:
|
||||||
|
version "0.21.5"
|
||||||
|
resolved "https://registry.npmmirror.com/esbuild/-/esbuild-0.21.5.tgz#9ca301b120922959b766360d8ac830da0d02997d"
|
||||||
|
integrity sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==
|
||||||
|
optionalDependencies:
|
||||||
|
"@esbuild/aix-ppc64" "0.21.5"
|
||||||
|
"@esbuild/android-arm" "0.21.5"
|
||||||
|
"@esbuild/android-arm64" "0.21.5"
|
||||||
|
"@esbuild/android-x64" "0.21.5"
|
||||||
|
"@esbuild/darwin-arm64" "0.21.5"
|
||||||
|
"@esbuild/darwin-x64" "0.21.5"
|
||||||
|
"@esbuild/freebsd-arm64" "0.21.5"
|
||||||
|
"@esbuild/freebsd-x64" "0.21.5"
|
||||||
|
"@esbuild/linux-arm" "0.21.5"
|
||||||
|
"@esbuild/linux-arm64" "0.21.5"
|
||||||
|
"@esbuild/linux-ia32" "0.21.5"
|
||||||
|
"@esbuild/linux-loong64" "0.21.5"
|
||||||
|
"@esbuild/linux-mips64el" "0.21.5"
|
||||||
|
"@esbuild/linux-ppc64" "0.21.5"
|
||||||
|
"@esbuild/linux-riscv64" "0.21.5"
|
||||||
|
"@esbuild/linux-s390x" "0.21.5"
|
||||||
|
"@esbuild/linux-x64" "0.21.5"
|
||||||
|
"@esbuild/netbsd-x64" "0.21.5"
|
||||||
|
"@esbuild/openbsd-x64" "0.21.5"
|
||||||
|
"@esbuild/sunos-x64" "0.21.5"
|
||||||
|
"@esbuild/win32-arm64" "0.21.5"
|
||||||
|
"@esbuild/win32-ia32" "0.21.5"
|
||||||
|
"@esbuild/win32-x64" "0.21.5"
|
||||||
|
|
||||||
|
estree-walker@^2.0.2:
|
||||||
|
version "2.0.2"
|
||||||
|
resolved "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz#52f010178c2a4c117a7757cfe942adb7d2da4cac"
|
||||||
|
integrity sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==
|
||||||
|
|
||||||
|
fsevents@~2.3.2, fsevents@~2.3.3:
|
||||||
|
version "2.3.3"
|
||||||
|
resolved "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6"
|
||||||
|
integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==
|
||||||
|
|
||||||
|
magic-string@^0.30.11:
|
||||||
|
version "0.30.17"
|
||||||
|
resolved "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.17.tgz#450a449673d2460e5bbcfba9a61916a1714c7453"
|
||||||
|
integrity sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==
|
||||||
|
dependencies:
|
||||||
|
"@jridgewell/sourcemap-codec" "^1.5.0"
|
||||||
|
|
||||||
|
nanoid@^3.3.8:
|
||||||
|
version "3.3.8"
|
||||||
|
resolved "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.8.tgz#b1be3030bee36aaff18bacb375e5cce521684baf"
|
||||||
|
integrity sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==
|
||||||
|
|
||||||
|
picocolors@^1.1.1:
|
||||||
|
version "1.1.1"
|
||||||
|
resolved "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b"
|
||||||
|
integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==
|
||||||
|
|
||||||
|
postcss@^8.4.43, postcss@^8.4.48:
|
||||||
|
version "8.5.2"
|
||||||
|
resolved "https://registry.npmmirror.com/postcss/-/postcss-8.5.2.tgz#e7b99cb9d2ec3e8dd424002e7c16517cb2b846bd"
|
||||||
|
integrity sha512-MjOadfU3Ys9KYoX0AdkBlFEF1Vx37uCCeN4ZHnmwm9FfpbsGWMZeBLMmmpY+6Ocqod7mkdZ0DT31OlbsFrLlkA==
|
||||||
|
dependencies:
|
||||||
|
nanoid "^3.3.8"
|
||||||
|
picocolors "^1.1.1"
|
||||||
|
source-map-js "^1.2.1"
|
||||||
|
|
||||||
|
rollup@^4.20.0:
|
||||||
|
version "4.34.7"
|
||||||
|
resolved "https://registry.npmmirror.com/rollup/-/rollup-4.34.7.tgz#e00d8550688a616a3481c6446bb688d4c753ba8f"
|
||||||
|
integrity sha512-8qhyN0oZ4x0H6wmBgfKxJtxM7qS98YJ0k0kNh5ECVtuchIJ7z9IVVvzpmtQyT10PXKMtBxYr1wQ5Apg8RS8kXQ==
|
||||||
|
dependencies:
|
||||||
|
"@types/estree" "1.0.6"
|
||||||
|
optionalDependencies:
|
||||||
|
"@rollup/rollup-android-arm-eabi" "4.34.7"
|
||||||
|
"@rollup/rollup-android-arm64" "4.34.7"
|
||||||
|
"@rollup/rollup-darwin-arm64" "4.34.7"
|
||||||
|
"@rollup/rollup-darwin-x64" "4.34.7"
|
||||||
|
"@rollup/rollup-freebsd-arm64" "4.34.7"
|
||||||
|
"@rollup/rollup-freebsd-x64" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-arm-gnueabihf" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-arm-musleabihf" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-arm64-gnu" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-arm64-musl" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-loongarch64-gnu" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-powerpc64le-gnu" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-riscv64-gnu" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-s390x-gnu" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-x64-gnu" "4.34.7"
|
||||||
|
"@rollup/rollup-linux-x64-musl" "4.34.7"
|
||||||
|
"@rollup/rollup-win32-arm64-msvc" "4.34.7"
|
||||||
|
"@rollup/rollup-win32-ia32-msvc" "4.34.7"
|
||||||
|
"@rollup/rollup-win32-x64-msvc" "4.34.7"
|
||||||
|
fsevents "~2.3.2"
|
||||||
|
|
||||||
|
source-map-js@^1.2.0, source-map-js@^1.2.1:
|
||||||
|
version "1.2.1"
|
||||||
|
resolved "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz#1ce5650fddd87abc099eda37dcff024c2667ae46"
|
||||||
|
integrity sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==
|
||||||
|
|
||||||
|
vite@^5.4.8:
|
||||||
|
version "5.4.14"
|
||||||
|
resolved "https://registry.npmmirror.com/vite/-/vite-5.4.14.tgz#ff8255edb02134df180dcfca1916c37a6abe8408"
|
||||||
|
integrity sha512-EK5cY7Q1D8JNhSaPKVK4pwBFvaTmZxEnoKXLG/U9gmdDcihQGNzFlgIvaxezFR4glP1LsuiedwMBqCXH3wZccA==
|
||||||
|
dependencies:
|
||||||
|
esbuild "^0.21.3"
|
||||||
|
postcss "^8.4.43"
|
||||||
|
rollup "^4.20.0"
|
||||||
|
optionalDependencies:
|
||||||
|
fsevents "~2.3.3"
|
||||||
|
|
||||||
|
vue-router@^4.0.0:
|
||||||
|
version "4.5.0"
|
||||||
|
resolved "https://registry.npmmirror.com/vue-router/-/vue-router-4.5.0.tgz#58fc5fe374e10b6018f910328f756c3dae081f14"
|
||||||
|
integrity sha512-HDuk+PuH5monfNuY+ct49mNmkCRK4xJAV9Ts4z9UFc4rzdDnxQLyCMGGc8pKhZhHTVzfanpNwB/lwqevcBwI4w==
|
||||||
|
dependencies:
|
||||||
|
"@vue/devtools-api" "^6.6.4"
|
||||||
|
|
||||||
|
vue@^3.5.10:
|
||||||
|
version "3.5.13"
|
||||||
|
resolved "https://registry.npmmirror.com/vue/-/vue-3.5.13.tgz#9f760a1a982b09c0c04a867903fc339c9f29ec0a"
|
||||||
|
integrity sha512-wmeiSMxkZCSc+PM2w2VRsOYAZC8GdipNFRTsLSfodVqI9mbejKeXEGr8SckuLnrQPGe3oJN5c3K0vpoU9q/wCQ==
|
||||||
|
dependencies:
|
||||||
|
"@vue/compiler-dom" "3.5.13"
|
||||||
|
"@vue/compiler-sfc" "3.5.13"
|
||||||
|
"@vue/runtime-dom" "3.5.13"
|
||||||
|
"@vue/server-renderer" "3.5.13"
|
||||||
|
"@vue/shared" "3.5.13"
|
||||||
49
config.yaml
49
config.yaml
|
|
@ -1,5 +1,6 @@
|
||||||
# 如果您是一名开发者,建议阅读以下内容。如果不是开发者,可以忽略这部分内容。
|
# 如果您是一名开发者,建议阅读以下内容。如果不是开发者,可以忽略这部分内容。
|
||||||
# 在开发中,建议将【config.yaml】复制一份,改成【.config.yaml】。 系统会优先读取【.config.yaml】文件的配置。
|
# 在开发中,在项目根目录创建data目录,将【config.yaml】复制一份,改成【.config.yaml】,放进data目录中
|
||||||
|
# 系统会优先读取【data/.config.yaml】文件的配置。
|
||||||
# 这样做,可以避免在提交代码的时候,错误地提交密钥信息,保护您的密钥安全。
|
# 这样做,可以避免在提交代码的时候,错误地提交密钥信息,保护您的密钥安全。
|
||||||
|
|
||||||
# 服务器基础配置(Basic server configuration)
|
# 服务器基础配置(Basic server configuration)
|
||||||
|
|
@ -45,7 +46,11 @@ prompt: |
|
||||||
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
|
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
|
||||||
delete_audio: true
|
delete_audio: true
|
||||||
|
|
||||||
|
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
|
||||||
|
close_connection_no_voice_time: 120
|
||||||
|
|
||||||
# 是否启用私有配置(Enable private configuration),启用后可以每个设备有不同的配置
|
# 是否启用私有配置(Enable private configuration),启用后可以每个设备有不同的配置
|
||||||
|
# 目前这个模块还在开发中,建议:不要修改use_private_config选项
|
||||||
use_private_config: false
|
use_private_config: false
|
||||||
|
|
||||||
CMD_exit:
|
CMD_exit:
|
||||||
|
|
@ -124,6 +129,13 @@ LLM:
|
||||||
# 若部署地无法访问接口,需要开启科学上网
|
# 若部署地无法访问接口,需要开启科学上网
|
||||||
api_key: 你的gemini api key
|
api_key: 你的gemini api key
|
||||||
model_name: "gemini-1.5-pro" # gemini-1.5-pro 是免费的
|
model_name: "gemini-1.5-pro" # gemini-1.5-pro 是免费的
|
||||||
|
CozeLLM:
|
||||||
|
# 定义LLM API类型
|
||||||
|
type: coze
|
||||||
|
bot_id: 你的bot_id
|
||||||
|
user_id: 你的user_id
|
||||||
|
base_url: "https://api.coze.cn/open_api/v2/chat" # 服务地址
|
||||||
|
personal_access_token: 你的coze个人令牌
|
||||||
TTS:
|
TTS:
|
||||||
# 当前支持的type为edge、doubao,可自行适配
|
# 当前支持的type为edge、doubao,可自行适配
|
||||||
EdgeTTS:
|
EdgeTTS:
|
||||||
|
|
@ -152,6 +164,14 @@ TTS:
|
||||||
output_file: tmp/
|
output_file: tmp/
|
||||||
access_token: 你的硅基流动API密钥
|
access_token: 你的硅基流动API密钥
|
||||||
response_format: wav
|
response_format: wav
|
||||||
|
CozeCnTTS:
|
||||||
|
type: cozecn
|
||||||
|
# COZECN TTS
|
||||||
|
# token申请地址 https://www.coze.cn/open/oauth/pats
|
||||||
|
voice: 7426720361733046281
|
||||||
|
output_file: tmp/
|
||||||
|
access_token: 你的coze api key
|
||||||
|
response_format: wav
|
||||||
FishSpeech:
|
FishSpeech:
|
||||||
# 定义TTS API类型
|
# 定义TTS API类型
|
||||||
#启动tts方法:
|
#启动tts方法:
|
||||||
|
|
@ -178,5 +198,30 @@ TTS:
|
||||||
seed: null
|
seed: null
|
||||||
channels: 1
|
channels: 1
|
||||||
rate: 44100
|
rate: 44100
|
||||||
api_key: "YOUR_API_KEY"
|
api_key: "你的api_key"
|
||||||
api_url: "http://127.0.0.1:8080/v1/tts"
|
api_url: "http://127.0.0.1:8080/v1/tts"
|
||||||
|
GPT_SOVITS_V2:
|
||||||
|
# 定义TTS API类型
|
||||||
|
#启动tts方法:
|
||||||
|
#python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/caixukun.yaml
|
||||||
|
type: gpt_sovits_v2
|
||||||
|
url: "http://127.0.0.1:9880/tts"
|
||||||
|
output_file: 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: []
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,10 @@ import sys
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
def setup_logging(log_dir='tmp'):
|
def setup_logging(log_dir='tmp', data_dir='data'):
|
||||||
"""配置全局日志"""
|
"""配置全局日志"""
|
||||||
os.makedirs(log_dir, exist_ok=True)
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
|
os.makedirs(data_dir, exist_ok=True)
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
|
|
|
||||||
|
|
@ -2,60 +2,76 @@ import os
|
||||||
import time
|
import time
|
||||||
import yaml
|
import yaml
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, Optional
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from core.utils.util import get_project_dir
|
from core.utils.util import get_project_dir
|
||||||
from core.utils import asr, vad, llm, tts, embedding
|
from core.utils import asr, vad, llm, tts, embedding
|
||||||
|
from manager.api.user_manager import UserManager
|
||||||
|
from core.utils.lock_manager import FileLockManager
|
||||||
|
|
||||||
class PrivateConfig:
|
class PrivateConfig:
|
||||||
def __init__(self, device_id: str, default_config: Dict[str, Any]):
|
def __init__(self, device_id: str, default_config: Dict[str, Any], auth_code_gen=None):
|
||||||
self.device_id = device_id
|
self.device_id = device_id
|
||||||
self.default_config = default_config
|
self.default_config = default_config
|
||||||
self.config_path = get_project_dir() + '.private_config.yaml'
|
self.config_path = get_project_dir() + 'data/.private_config.yaml'
|
||||||
self.logger = logging.getLogger(__name__)
|
self.logger = logging.getLogger(__name__)
|
||||||
self.private_config = {}
|
self.private_config = {}
|
||||||
|
self.auth_code_gen = auth_code_gen
|
||||||
|
self.user_manager = UserManager()
|
||||||
|
self.lock_manager = FileLockManager()
|
||||||
|
|
||||||
async def load_or_create(self):
|
async def load_or_create(self):
|
||||||
try:
|
try:
|
||||||
if os.path.exists(self.config_path):
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
try:
|
||||||
all_configs = yaml.safe_load(f) or {}
|
if os.path.exists(self.config_path):
|
||||||
else:
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
all_configs = {}
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
else:
|
||||||
|
all_configs = {}
|
||||||
|
|
||||||
if self.device_id not in all_configs:
|
if self.device_id not in all_configs:
|
||||||
# Get selected module names
|
# Get selected module names
|
||||||
selected_modules = self.default_config['selected_module']
|
selected_modules = self.default_config['selected_module']
|
||||||
selected_tts = selected_modules['TTS']
|
selected_tts = selected_modules['TTS']
|
||||||
selected_llm = selected_modules['LLM']
|
selected_llm = selected_modules['LLM']
|
||||||
selected_asr = selected_modules['ASR']
|
selected_asr = selected_modules['ASR']
|
||||||
selected_vad = selected_modules['VAD']
|
selected_vad = selected_modules['VAD']
|
||||||
|
|
||||||
# Initialize device config with only necessary configurations
|
# 生成认证码
|
||||||
device_config = {
|
auth_code = None
|
||||||
'selected_module': deepcopy(selected_modules),
|
if self.auth_code_gen:
|
||||||
'prompt': self.default_config['prompt'],
|
auth_code = self.auth_code_gen.generate_code()
|
||||||
'LLM': {
|
|
||||||
selected_llm: deepcopy(self.default_config['LLM'][selected_llm])
|
# Initialize device config with only necessary configurations
|
||||||
},
|
device_config = {
|
||||||
'TTS': {
|
'selected_module': deepcopy(selected_modules),
|
||||||
selected_tts: deepcopy(self.default_config['TTS'][selected_tts])
|
'prompt': self.default_config['prompt'],
|
||||||
},
|
'LLM': {
|
||||||
'ASR': {
|
selected_llm: deepcopy(self.default_config['LLM'][selected_llm])
|
||||||
selected_asr: deepcopy(self.default_config['ASR'][selected_asr])
|
},
|
||||||
},
|
'TTS': {
|
||||||
'VAD': {
|
selected_tts: deepcopy(self.default_config['TTS'][selected_tts])
|
||||||
selected_vad: deepcopy(self.default_config['VAD'][selected_vad])
|
},
|
||||||
|
'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
|
all_configs[self.device_id] = device_config
|
||||||
|
|
||||||
# Save updated configs
|
# Save updated configs
|
||||||
with open(self.config_path, 'w', encoding='utf-8') as f:
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
yaml.dump(all_configs, f, allow_unicode=True)
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
self.private_config = all_configs[self.device_id]
|
self.private_config = all_configs[self.device_id]
|
||||||
|
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Error handling private config: {e}")
|
self.logger.error(f"Error handling private config: {e}")
|
||||||
|
|
@ -70,41 +86,47 @@ class PrivateConfig:
|
||||||
bool: 更新是否成功
|
bool: 更新是否成功
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Read main config to get full module configurations
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
main_config = self.default_config
|
try:
|
||||||
|
# Read main config to get full module configurations
|
||||||
|
main_config = self.default_config
|
||||||
|
|
||||||
# Create new device config
|
# Create new device config
|
||||||
device_config = {
|
device_config = {
|
||||||
'selected_module': selected_modules,
|
'selected_module': selected_modules,
|
||||||
'prompt': prompt,
|
'prompt': prompt,
|
||||||
'nickname': nickname,
|
'nickname': nickname,
|
||||||
}
|
}
|
||||||
if self.private_config.get('last_chat_time'):
|
if self.private_config.get('last_chat_time'):
|
||||||
device_config['last_chat_time'] = self.private_config['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
|
# Copy full module configurations from main config
|
||||||
for module_type, selected_name in selected_modules.items():
|
for module_type, selected_name in selected_modules.items():
|
||||||
if selected_name and selected_name in main_config.get(module_type, {}):
|
if selected_name and selected_name in main_config.get(module_type, {}):
|
||||||
device_config[module_type] = {
|
device_config[module_type] = {
|
||||||
selected_name: main_config[module_type][selected_name]
|
selected_name: main_config[module_type][selected_name]
|
||||||
}
|
}
|
||||||
|
|
||||||
# Read all configs
|
# Read all configs
|
||||||
if os.path.exists(self.config_path):
|
if os.path.exists(self.config_path):
|
||||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
all_configs = yaml.safe_load(f) or {}
|
all_configs = yaml.safe_load(f) or {}
|
||||||
else:
|
else:
|
||||||
all_configs = {}
|
all_configs = {}
|
||||||
|
|
||||||
# Update device config
|
# Update device config
|
||||||
all_configs[self.device_id] = device_config
|
all_configs[self.device_id] = device_config
|
||||||
self.private_config = device_config
|
self.private_config = device_config
|
||||||
|
|
||||||
# Save back to file
|
# Save back to file
|
||||||
with open(self.config_path, 'w', encoding='utf-8') as f:
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
yaml.dump(all_configs, f, allow_unicode=True)
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Error updating config: {e}")
|
self.logger.error(f"Error updating config: {e}")
|
||||||
|
|
@ -116,25 +138,29 @@ class PrivateConfig:
|
||||||
bool: 删除是否成功
|
bool: 删除是否成功
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# 读取所有配置
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
if os.path.exists(self.config_path):
|
try:
|
||||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
# 读取所有配置
|
||||||
all_configs = yaml.safe_load(f) or {}
|
if os.path.exists(self.config_path):
|
||||||
else:
|
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
|
return False
|
||||||
|
finally:
|
||||||
# 删除设备配置
|
self.lock_manager.release_lock(self.config_path)
|
||||||
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
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Error deleting config: {e}")
|
self.logger.error(f"Error deleting config: {e}")
|
||||||
|
|
@ -180,7 +206,7 @@ class PrivateConfig:
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
def update_last_chat_time(self, timestamp=None):
|
async def update_last_chat_time(self, timestamp=None):
|
||||||
"""更新设备最近一次的聊天时间
|
"""更新设备最近一次的聊天时间
|
||||||
Args:
|
Args:
|
||||||
timestamp: 指定的时间戳,不传则使用当前时间
|
timestamp: 指定的时间戳,不传则使用当前时间
|
||||||
|
|
@ -190,24 +216,127 @@ class PrivateConfig:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if timestamp is None:
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
timestamp = int(time.time())
|
try:
|
||||||
|
if timestamp is None:
|
||||||
|
timestamp = int(time.time())
|
||||||
|
|
||||||
self.private_config['last_chat_time'] = timestamp
|
self.private_config['last_chat_time'] = timestamp
|
||||||
|
|
||||||
# 读取所有配置
|
# 读取所有配置
|
||||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
all_configs = yaml.safe_load(f) or {}
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
# 更新当前设备配置
|
# 更新当前设备配置
|
||||||
all_configs[self.device_id] = self.private_config
|
all_configs[self.device_id] = self.private_config
|
||||||
|
|
||||||
# 保存回文件
|
# 保存回文件
|
||||||
with open(self.config_path, 'w', encoding='utf-8') as f:
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
yaml.dump(all_configs, f, allow_unicode=True)
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Error updating last chat time: {e}")
|
self.logger.error(f"Error updating last chat time: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def get_auth_code(self) -> str:
|
||||||
|
"""获取设备的认证码
|
||||||
|
Returns:
|
||||||
|
str: 认证码,如果没有返回空字符串
|
||||||
|
"""
|
||||||
|
return self.private_config.get('auth_code', '')
|
||||||
|
|
||||||
|
async def bind_user(self, username: str) -> bool:
|
||||||
|
"""绑定用户到设备"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
|
try:
|
||||||
|
# 检查用户是否存在
|
||||||
|
if not self.user_manager.get_user(username):
|
||||||
|
self.logger.error(f"User {username} not found")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 读取所有配置
|
||||||
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
|
if self.device_id not in all_configs:
|
||||||
|
self.logger.error(f"Device {self.device_id} not found")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 删除认证码
|
||||||
|
auth_code = all_configs[self.device_id].get('auth_code')
|
||||||
|
self.logger.info(f"Binding user {username} to device {self.device_id}")
|
||||||
|
if auth_code:
|
||||||
|
del all_configs[self.device_id]['auth_code']
|
||||||
|
|
||||||
|
if self.auth_code_gen:
|
||||||
|
self.auth_code_gen.remove_code(auth_code)
|
||||||
|
|
||||||
|
# 更新设备所有者
|
||||||
|
all_configs[self.device_id]['owner'] = username
|
||||||
|
self.private_config = all_configs[self.device_id]
|
||||||
|
|
||||||
|
# 更新用户的设备列表
|
||||||
|
user_data = await self.user_manager.get_user(username)
|
||||||
|
if 'devices' not in user_data:
|
||||||
|
user_data['devices'] = []
|
||||||
|
if self.device_id not in user_data['devices']:
|
||||||
|
user_data['devices'].append(self.device_id)
|
||||||
|
await self.user_manager.update_user(username, user_data)
|
||||||
|
|
||||||
|
# 保存配置
|
||||||
|
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.error(f"Error binding user: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def unbind_user(self) -> bool:
|
||||||
|
"""解绑设备当前用户"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
|
try:
|
||||||
|
if not self.private_config.get('owner'):
|
||||||
|
return True
|
||||||
|
|
||||||
|
username = self.private_config['owner']
|
||||||
|
|
||||||
|
# 从用户数据中移除设备
|
||||||
|
user_data = self.user_manager.get_user(username)
|
||||||
|
if user_data and 'devices' in user_data:
|
||||||
|
if self.device_id in user_data['devices']:
|
||||||
|
user_data['devices'].remove(self.device_id)
|
||||||
|
self.user_manager.update_user(username, user_data)
|
||||||
|
|
||||||
|
# 从设备配置中移除所有者
|
||||||
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
|
if self.device_id in all_configs:
|
||||||
|
if 'owner' in all_configs[self.device_id]:
|
||||||
|
del all_configs[self.device_id]['owner']
|
||||||
|
self.private_config = all_configs[self.device_id]
|
||||||
|
|
||||||
|
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.error(f"Error unbinding user: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_owner(self) -> Optional[str]:
|
||||||
|
"""获取设备当前所有者"""
|
||||||
|
return self.private_config.get('owner')
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@ from core.utils.util import read_config, get_project_dir
|
||||||
def get_config_file():
|
def get_config_file():
|
||||||
default_config_file = "config.yaml"
|
default_config_file = "config.yaml"
|
||||||
# 判断是否存在私有的配置文件
|
# 判断是否存在私有的配置文件
|
||||||
if os.path.exists(get_project_dir() + "." + default_config_file):
|
if os.path.exists(get_project_dir() + "data/." + default_config_file):
|
||||||
default_config_file = "." + default_config_file
|
default_config_file = "data/." + default_config_file
|
||||||
return default_config_file
|
return default_config_file
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@ from core.handle.audioHandle import handleAudioMessage, sendAudioMessage
|
||||||
from config.private_config import PrivateConfig
|
from config.private_config import PrivateConfig
|
||||||
from core.auth import AuthMiddleware, AuthenticationError
|
from core.auth import AuthMiddleware, AuthenticationError
|
||||||
from core.utils.llm_memory import MemoryManager
|
from core.utils.llm_memory import MemoryManager
|
||||||
|
from core.utils.auth_code_gen import AuthCodeGenerator # 添加导入
|
||||||
|
|
||||||
|
|
||||||
class ConnectionHandler:
|
class ConnectionHandler:
|
||||||
|
|
@ -56,6 +56,7 @@ class ConnectionHandler:
|
||||||
self.client_audio_buffer = bytes()
|
self.client_audio_buffer = bytes()
|
||||||
self.client_have_voice = False
|
self.client_have_voice = False
|
||||||
self.client_have_voice_last_time = 0.0
|
self.client_have_voice_last_time = 0.0
|
||||||
|
self.client_no_voice_last_time = 0.0
|
||||||
self.client_voice_stop = False
|
self.client_voice_stop = False
|
||||||
|
|
||||||
# asr相关变量
|
# asr相关变量
|
||||||
|
|
@ -79,6 +80,9 @@ class ConnectionHandler:
|
||||||
self.max_cmd_length = len(cmd)
|
self.max_cmd_length = len(cmd)
|
||||||
|
|
||||||
self.private_config = None
|
self.private_config = None
|
||||||
|
self.auth_code_gen = AuthCodeGenerator.get_instance()
|
||||||
|
self.is_device_verified = False # 添加设备验证状态标志
|
||||||
|
|
||||||
|
|
||||||
self.llm_memory = MemoryManager(llm=_llm, embd=_embd)
|
self.llm_memory = MemoryManager(llm=_llm, embd=_embd)
|
||||||
|
|
||||||
|
|
@ -99,22 +103,33 @@ class ConnectionHandler:
|
||||||
bUsePrivateConfig = self.config.get("use_private_config", False)
|
bUsePrivateConfig = self.config.get("use_private_config", False)
|
||||||
logging.info(f"bUsePrivateConfig: {bUsePrivateConfig}, device_id: {device_id}")
|
logging.info(f"bUsePrivateConfig: {bUsePrivateConfig}, device_id: {device_id}")
|
||||||
if bUsePrivateConfig and device_id:
|
if bUsePrivateConfig and device_id:
|
||||||
self.private_config = PrivateConfig(device_id, self.config)
|
|
||||||
await self.private_config.load_or_create()
|
|
||||||
# Create private instances using private config
|
|
||||||
vad, asr, llm, tts, embd = self.private_config.create_private_instances()
|
|
||||||
if vad is not None and asr is not None and llm is not None and tts is not None:
|
|
||||||
self.vad = vad
|
|
||||||
self.asr = asr
|
|
||||||
self.llm = llm
|
|
||||||
self.tts = tts
|
|
||||||
self.embd = embd
|
|
||||||
|
|
||||||
self.logger.info(f"Loaded private config and instances for device {device_id}")
|
try:
|
||||||
self.private_config.update_last_chat_time()
|
self.private_config = PrivateConfig(device_id, self.config, self.auth_code_gen)
|
||||||
else:
|
await self.private_config.load_or_create()
|
||||||
self.logger.error(f"Failed to load private config for device {device_id}")
|
# 判断是否已经绑定
|
||||||
|
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()
|
||||||
|
|
||||||
|
vad, asr, llm, tts ,embd = self.private_config.create_private_instances()
|
||||||
|
if all([vad, asr, llm, tts]):
|
||||||
|
self.vad = vad
|
||||||
|
self.asr = asr
|
||||||
|
self.llm = llm
|
||||||
|
self.tts = tts
|
||||||
|
self.embd = embd
|
||||||
|
self.logger.info(f"Loaded private config and instances for device {device_id}")
|
||||||
|
else:
|
||||||
|
self.logger.error(f"Failed to create instances for device {device_id}")
|
||||||
|
self.private_config = None
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(f"Error initializing private config: {e}")
|
||||||
|
|
||||||
self.private_config = None
|
self.private_config = None
|
||||||
|
raise
|
||||||
|
|
||||||
# 认证通过,继续处理
|
# 认证通过,继续处理
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
|
|
@ -164,7 +179,40 @@ class ConnectionHandler:
|
||||||
self.prompt = self.prompt.replace("{date_time}", date_time)
|
self.prompt = self.prompt.replace("{date_time}", date_time)
|
||||||
self.dialogue.put(Message(role="system", content=self.prompt))
|
self.dialogue.put(Message(role="system", content=self.prompt))
|
||||||
|
|
||||||
def chat(self, query:str):
|
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
|
||||||
|
# 创建一个新的事件循环来运行异步函数
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
try:
|
||||||
|
loop.run_until_complete(self._check_and_broadcast_auth_code())
|
||||||
|
finally:
|
||||||
|
loop.close()
|
||||||
|
return True
|
||||||
|
|
||||||
query = self.llm_memory.handle_user_scene(self.device_id, query)
|
query = self.llm_memory.handle_user_scene(self.device_id, query)
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
self.dialogue.put(Message(role="user", content=query))
|
||||||
response_message = []
|
response_message = []
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,10 @@ async def handleAudioMessage(conn, audio):
|
||||||
|
|
||||||
# 如果本次没有声音,本段也没声音,就把声音丢弃了
|
# 如果本次没有声音,本段也没声音,就把声音丢弃了
|
||||||
if have_voice == False and conn.client_have_voice == False:
|
if have_voice == False and conn.client_have_voice == False:
|
||||||
|
await no_voice_close_connect(conn)
|
||||||
conn.asr_audio.clear()
|
conn.asr_audio.clear()
|
||||||
return
|
return
|
||||||
|
conn.client_no_voice_last_time = 0.0
|
||||||
conn.asr_audio.append(audio)
|
conn.asr_audio.append(audio)
|
||||||
# 如果本段有声音,且已经停止了
|
# 如果本段有声音,且已经停止了
|
||||||
if conn.client_voice_stop:
|
if conn.client_voice_stop:
|
||||||
|
|
@ -146,3 +148,16 @@ async def schedule_with_interrupt(delay, coro):
|
||||||
await coro
|
await coro
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def no_voice_close_connect(conn):
|
||||||
|
if conn.client_no_voice_last_time == 0.0:
|
||||||
|
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 = conn.config.get("close_connection_no_voice_time", 120)
|
||||||
|
if no_voice_time > 1000 * close_connection_no_voice_time:
|
||||||
|
conn.client_abort = False
|
||||||
|
conn.asr_server_receive = False
|
||||||
|
prompt = "时间过得真快,我都好久没说话了。请你用十个字左右话跟我告别,以“再见”或“拜拜拜”为结尾"
|
||||||
|
await startToChat(conn, prompt)
|
||||||
|
|
|
||||||
95
core/providers/llm/coze/coze.py
Normal file
95
core/providers/llm/coze/coze.py
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
import logging
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from core.providers.llm.base import LLMProviderBase
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 定义用于匹配中文标点符号的正则表达式(包括句号、感叹号、问号、分号)
|
||||||
|
punctuation_pattern = re.compile(r'([。!?;])')
|
||||||
|
|
||||||
|
class LLMProvider(LLMProviderBase):
|
||||||
|
def __init__(self, config):
|
||||||
|
self.personal_access_token = config.get("personal_access_token")
|
||||||
|
self.bot_id = config.get("bot_id")
|
||||||
|
self.user_id = config.get("user_id") # 默认用户 ID
|
||||||
|
self.base_url = config.get("base_url")
|
||||||
|
|
||||||
|
def response(self, session_id, dialogue):
|
||||||
|
try:
|
||||||
|
# 从对话中取出最新的用户消息
|
||||||
|
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
||||||
|
data = {
|
||||||
|
"conversation_id": session_id,
|
||||||
|
"bot_id": self.bot_id,
|
||||||
|
"user": self.user_id,
|
||||||
|
"query": last_msg["content"],
|
||||||
|
"stream": True
|
||||||
|
}
|
||||||
|
logger.info(f"发送到 Coze API 的请求数据: {json.dumps(data, ensure_ascii=False)}")
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Bearer {self.personal_access_token}',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': '*/*',
|
||||||
|
'Host': 'api.coze.cn',
|
||||||
|
'Connection': 'keep-alive'
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post(
|
||||||
|
self.base_url,
|
||||||
|
headers=headers,
|
||||||
|
json=data,
|
||||||
|
stream=True
|
||||||
|
)
|
||||||
|
logger.info(f"请求状态: {response.status_code}")
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
# 对每一行流数据进行处理,不做跨块累积
|
||||||
|
for line_bytes in response.iter_lines(decode_unicode=False):
|
||||||
|
if not line_bytes:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
# 使用 utf-8 解码,错误部分用替换符
|
||||||
|
line = line_bytes.decode('utf-8', errors='replace')
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"解码失败: {e}")
|
||||||
|
continue
|
||||||
|
if line.startswith("data:"):
|
||||||
|
data_str = line[len("data:"):].strip()
|
||||||
|
if data_str == "[DONE]":
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
data_chunk = json.loads(data_str)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
logger.error(f"JSON解析失败: {e} 数据: {line}")
|
||||||
|
continue
|
||||||
|
msg = data_chunk.get("message", {})
|
||||||
|
if msg.get("role") == "assistant" and msg.get("type") == "answer":
|
||||||
|
content = msg.get("content", "")
|
||||||
|
# 如果返回内容中包含标点符号,则按标点拆分,立即返回每个片段
|
||||||
|
if punctuation_pattern.search(content):
|
||||||
|
# 利用 finditer 找到每个标点,并返回以标点结尾的片段
|
||||||
|
start = 0
|
||||||
|
for match in punctuation_pattern.finditer(content):
|
||||||
|
end = match.end()
|
||||||
|
sentence = content[start:end].strip()
|
||||||
|
if sentence:
|
||||||
|
yield sentence
|
||||||
|
start = end
|
||||||
|
# 如果拆分后剩余内容也返回(不含标点),直接返回
|
||||||
|
if start < len(content):
|
||||||
|
remainder = content[start:].strip()
|
||||||
|
if remainder:
|
||||||
|
yield remainder
|
||||||
|
else:
|
||||||
|
# 如果没有标点,则直接返回这块内容
|
||||||
|
if content.strip():
|
||||||
|
yield content.strip()
|
||||||
|
else:
|
||||||
|
logger.error(f"请求失败,状态码: {response.status_code}")
|
||||||
|
yield f"【Coze服务响应异常:请求失败,状态码 {response.status_code}】"
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error in Coze response generation: {e}")
|
||||||
|
yield "【Coze服务响应异常】"
|
||||||
38
core/providers/tts/cozecn.py
Normal file
38
core/providers/tts/cozecn.py
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import json
|
||||||
|
import base64
|
||||||
|
import requests
|
||||||
|
from datetime import datetime
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
self.model = config.get("model")
|
||||||
|
self.access_token = config.get("access_token")
|
||||||
|
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}")
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
request_json = {
|
||||||
|
"model": self.model,
|
||||||
|
"input": text,
|
||||||
|
"voice_id": self.voice,
|
||||||
|
"response_format": self.response_format,
|
||||||
|
}
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {self.access_token}",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
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)
|
||||||
65
core/providers/tts/gpt_sovits_v2.py
Normal file
65
core/providers/tts/gpt_sovits_v2.py
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import json
|
||||||
|
import base64
|
||||||
|
import requests
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
self.url = config.get("url")
|
||||||
|
self.text_lang = config.get("text_lang", "zh")
|
||||||
|
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 = 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 = 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}")
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
request_json = {
|
||||||
|
"text": text,
|
||||||
|
"text_lang": self.text_lang,
|
||||||
|
"ref_audio_path": self.ref_audio_path,
|
||||||
|
"aux_ref_audio_paths": self.aux_ref_audio_paths,
|
||||||
|
"prompt_text": self.prompt_text,
|
||||||
|
"prompt_lang": self.prompt_lang,
|
||||||
|
"top_k": self.top_k,
|
||||||
|
"top_p": self.top_p,
|
||||||
|
"temperature": self.temperature,
|
||||||
|
"text_split_method": self.text_split_method,
|
||||||
|
"batch_size": self.batch_size,
|
||||||
|
"batch_threshold": self.batch_threshold,
|
||||||
|
"split_bucket": self.split_bucket,
|
||||||
|
"return_fragment": self.return_fragment,
|
||||||
|
"speed_factor": self.speed_factor,
|
||||||
|
"streaming_mode": self.streaming_mode,
|
||||||
|
"seed": self.seed,
|
||||||
|
"parallel_infer": self.parallel_infer,
|
||||||
|
"repetition_penalty": self.repetition_penalty
|
||||||
|
}
|
||||||
|
|
||||||
|
resp = requests.post(self.url, json=request_json)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
with open(output_file, "wb") as file:
|
||||||
|
file.write(resp.content)
|
||||||
|
else:
|
||||||
|
logger.error(f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}")
|
||||||
97
core/utils/auth_code_gen.py
Normal file
97
core/utils/auth_code_gen.py
Normal file
|
|
@ -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]
|
||||||
38
core/utils/lock_manager.py
Normal file
38
core/utils/lock_manager.py
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import asyncio
|
||||||
|
from typing import Dict
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
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.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.debug(f"Released lock for {file_path}")
|
||||||
|
except RuntimeError as e:
|
||||||
|
logger.warning(f"Failed to release lock for {file_path}: {e}")
|
||||||
|
|
@ -105,7 +105,7 @@ def check_password(password):
|
||||||
:return: 如果密码满足条件,则返回True;否则返回False。
|
:return: 如果密码满足条件,则返回True;否则返回False。
|
||||||
"""
|
"""
|
||||||
# 检查密码长度
|
# 检查密码长度
|
||||||
if len(password) < 10:
|
if len(password) < 8:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 检查是否包含英文字符和数字
|
# 检查是否包含英文字符和数字
|
||||||
|
|
@ -116,7 +116,7 @@ def check_password(password):
|
||||||
if "xiaozhi" in password:
|
if "xiaozhi" in password:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if "123456" in password:
|
if "1234" in password:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 如果满足所有条件,则返回True
|
# 如果满足所有条件,则返回True
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,9 @@ class WebSocketServer:
|
||||||
host = server_config["ip"]
|
host = server_config["ip"]
|
||||||
port = server_config["port"]
|
port = server_config["port"]
|
||||||
|
|
||||||
|
self.logger.info("=======下面的地址是websocket协议地址,请勿用浏览器访问=======")
|
||||||
self.logger.info("Server is running at ws://%s:%s", get_local_ip(), port)
|
self.logger.info("Server is running at ws://%s:%s", get_local_ip(), port)
|
||||||
|
self.logger.info("=======上面的地址是websocket协议地址,请勿用浏览器访问=======")
|
||||||
async with websockets.serve(
|
async with websockets.serve(
|
||||||
self._handle_connection,
|
self._handle_connection,
|
||||||
host,
|
host,
|
||||||
|
|
|
||||||
12
docker-compose-example.yml
Executable file
12
docker-compose-example.yml
Executable file
|
|
@ -0,0 +1,12 @@
|
||||||
|
services:
|
||||||
|
xiaozhi-esp32-server:
|
||||||
|
image: ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||||
|
container_name: xiaozhi-esp32-server
|
||||||
|
restart: always
|
||||||
|
#security_opt:
|
||||||
|
# - seccomp:unconfined
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
- "8002:8002"
|
||||||
|
volumes:
|
||||||
|
- ./.config.yaml:/opt/xiaozhi-esp32-server/config.yaml
|
||||||
217
docs/Deployment-silm.md
Normal file
217
docs/Deployment-silm.md
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
# 部署指南
|
||||||
|
|
||||||
|
本项目支持 **x86** 和 **arm64** 架构,可运行于国产操作系统。
|
||||||
|
|
||||||
|
## 方式一:快速部署(推荐)
|
||||||
|
|
||||||
|
### 1. 安装 Docker
|
||||||
|
|
||||||
|
如果未安装 Docker,可参考 [Docker 安装教程](https://www.runoob.com/docker/ubuntu-docker-install.html)。
|
||||||
|
|
||||||
|
### 2. 创建项目目录
|
||||||
|
|
||||||
|
选择一个空目录作为 **项目目录**。
|
||||||
|
|
||||||
|
### 3. 下载配置文件
|
||||||
|
|
||||||
|
访问 [config.yaml](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/config.yaml),点击 `RAW` 旁的下载按钮,保存到 **项目目录**。
|
||||||
|
|
||||||
|
### 4. 运行 Docker
|
||||||
|
|
||||||
|
打开终端,`cd` 进入 **项目目录**,执行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run -d --name xiaozhi-esp32-server --restart always --security-opt seccomp:unconfined \
|
||||||
|
-p 8000:8000 \
|
||||||
|
-v $(pwd)/config.yaml:/opt/xiaozhi-esp32-server/config.yaml \
|
||||||
|
ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 确认运行状态
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker ps # 查看容器状态
|
||||||
|
docker logs -f xiaozhi-esp32-server # 查看日志
|
||||||
|
```
|
||||||
|
|
||||||
|
## 方式二:使用 Docker Compose 部署
|
||||||
|
|
||||||
|
### 1. 创建 `docker-compose.yml`
|
||||||
|
在 `项目目录` 下创建 `docker-compose.yml` 文件,内容如下:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
xiaozhi-esp32-server:
|
||||||
|
image: ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||||
|
container_name: xiaozhi-esp32-server
|
||||||
|
restart: always
|
||||||
|
security_opt:
|
||||||
|
- seccomp:unconfined
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
volumes:
|
||||||
|
- ./config.yaml:/opt/xiaozhi-esp32-server/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 启动服务
|
||||||
|
```sh
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 确认运行状态
|
||||||
|
```sh
|
||||||
|
docker-compose ps
|
||||||
|
docker-compose logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 停止和删除容器
|
||||||
|
```sh
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 版本升级
|
||||||
|
|
||||||
|
#### 备份配置文件
|
||||||
|
```sh
|
||||||
|
cp config.yaml config_backup.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 更新 Docker 镜像
|
||||||
|
```sh
|
||||||
|
docker-compose pull
|
||||||
|
docker-compose down
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## 方式三:源码部署(免环境部署/可修改代码)
|
||||||
|
|
||||||
|
### 1. 下载源码
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone https://github.com/xinnan-tech/xiaozhi-esp32-server.git
|
||||||
|
cd xiaozhi-esp32-server
|
||||||
|
```
|
||||||
|
|
||||||
|
或手动下载 [ZIP 包](https://github.com/xinnan-tech/xiaozhi-esp32-server/archive/refs/heads/main.zip),解压后重命名为 `xiaozhi-esp32-server`。
|
||||||
|
|
||||||
|
## 2.运行docker
|
||||||
|
|
||||||
|
修改完配置后,打开命令行工具,`cd`进入到你的项目目录下,执行以下命令
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconfined \
|
||||||
|
-p 8000:8000 \
|
||||||
|
-p 8002:8002 \
|
||||||
|
-v ./:/app \
|
||||||
|
ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest
|
||||||
|
```
|
||||||
|
|
||||||
|
然后就和正常开发一样了
|
||||||
|
|
||||||
|
## 3.安装依赖
|
||||||
|
|
||||||
|
在刚刚的打开的终端运行
|
||||||
|
|
||||||
|
```sh
|
||||||
|
poetry install --no-root
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends libopus0 ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
速度慢可以尝试使用清华镜像
|
||||||
|
|
||||||
|
```sh
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends libopus0 ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4.运行项目
|
||||||
|
|
||||||
|
```sh
|
||||||
|
poetry run python app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 方式三:本地运行(适用于开发)
|
||||||
|
|
||||||
|
### 1. 安装环境
|
||||||
|
|
||||||
|
```sh
|
||||||
|
conda create -n xiaozhi-esp32-server python=3.10 -y
|
||||||
|
conda activate xiaozhi-esp32-server
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Mac/Windows:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
conda install conda-forge::libopus conda-forge::ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Ubuntu:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
apt-get install libopus0 ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 下载源码 & 安装依赖
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone https://github.com/xinnan-tech/xiaozhi-esp32-server.git
|
||||||
|
cd xiaozhi-esp32-server
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 运行项目
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 版本升级
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker stop xiaozhi-esp32-server
|
||||||
|
docker rm xiaozhi-esp32-server
|
||||||
|
docker rmi ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
然后重新按照 **方式一** 或 **方式二** 运行 Docker。
|
||||||
|
|
||||||
|
## 重要配置
|
||||||
|
|
||||||
|
修改 `config.yaml` 以适配不同 LLM 和 TTS 组件。
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
selected_module:
|
||||||
|
ASR: FunASR
|
||||||
|
VAD: SileroVAD
|
||||||
|
LLM: ChatGLMLLM
|
||||||
|
TTS: EdgeTTS
|
||||||
|
```
|
||||||
|
|
||||||
|
如需使用 `Dify` 或 `DeepSeekLLM`,修改 `LLM` 部分并填写密钥。
|
||||||
|
|
||||||
|
## 模型文件下载
|
||||||
|
|
||||||
|
语音转文字默认使用 `SenseVoiceSmall`,需下载 `model.pt` 并存放至 `model/SenseVoiceSmall` 目录。
|
||||||
|
|
||||||
|
- [阿里魔塔下载](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
||||||
|
- [百度网盘下载](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:`qvna`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
如遇问题,可参考 `docker logs -f xiaozhi-esp32-server` 进行排查。
|
||||||
|
|
||||||
|
**至此,部署完成!** 🚀
|
||||||
|
|
||||||
|
|
||||||
250
docs/Deployment.md
Normal file
250
docs/Deployment.md
Normal file
|
|
@ -0,0 +1,250 @@
|
||||||
|
# 方式一:docker快速部署
|
||||||
|
|
||||||
|
docker镜像已支持x86架构、arm64架构的CPU,支持在国产操作系统上运行。
|
||||||
|
|
||||||
|
## 1. 安装docker
|
||||||
|
|
||||||
|
如果您的电脑还没安装docker,可以按照这里的教程安装:[docker安装](https://www.runoob.com/docker/ubuntu-docker-install.html)
|
||||||
|
|
||||||
|
## 2. 创建目录
|
||||||
|
|
||||||
|
安装完后,你需要为这个项目找一个安放配置文件的目录,我们暂且称它为`项目目录`,这个目录最好是一个新建的空的目录。
|
||||||
|
|
||||||
|
## 3. 下载配置文件
|
||||||
|
|
||||||
|
用浏览器打开[这个链接](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/config.yaml)。
|
||||||
|
|
||||||
|
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config.yaml`文件。 把文件下载到你的
|
||||||
|
`项目目录`。
|
||||||
|
|
||||||
|
## 4.[跳转到配置项目文件](#配置项目)
|
||||||
|
|
||||||
|
## 5. 执行docker命令
|
||||||
|
|
||||||
|
打开命令行工具,`cd` 进入到你的`项目目录`,执行以下命令
|
||||||
|
|
||||||
|
```
|
||||||
|
#如果你是linux,执行
|
||||||
|
ls
|
||||||
|
#如果你是windows,执行
|
||||||
|
dir
|
||||||
|
```
|
||||||
|
|
||||||
|
如果你能看到`config.yaml`文件,确确实实进入到了`项目目录`,接着执行以下命令:
|
||||||
|
|
||||||
|
```
|
||||||
|
docker run -d --name xiaozhi-esp32-server --restart always --security-opt seccomp:unconfined -p 8000:8000 -v $(pwd)/config.yaml:/opt/xiaozhi-esp32-server/config.yaml ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6.[跳转到运行状态确认](#运行状态确认)
|
||||||
|
|
||||||
|
## [跳转到版本升级操作](#版本升级操作)
|
||||||
|
|
||||||
|
3.按本教程重新来一遍
|
||||||
|
|
||||||
|
# 方式二:借助docker环境运行部署(仅限开发人员/小白勿用)
|
||||||
|
|
||||||
|
## 1.克隆项目
|
||||||
|
|
||||||
|
## 2.[跳转到下载语音识别模型文件](#模型文件)
|
||||||
|
|
||||||
|
## 3.[跳转到配置项目文件](#配置项目)
|
||||||
|
|
||||||
|
## 4.运行docker
|
||||||
|
|
||||||
|
修改完配置后,打开命令行工具,`cd`进入到你的项目目录下,执行以下命令
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconfined \
|
||||||
|
-p 8000:8000 \
|
||||||
|
-p 8002:8002 \
|
||||||
|
-v ./:/app \
|
||||||
|
ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest
|
||||||
|
```
|
||||||
|
|
||||||
|
然后就和正常开发一样了
|
||||||
|
|
||||||
|
## 5.安装依赖
|
||||||
|
|
||||||
|
在刚刚的打开的终端运行
|
||||||
|
|
||||||
|
```sh
|
||||||
|
poetry install --no-root
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends libopus0 ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
速度慢可以尝试使用清华镜像
|
||||||
|
|
||||||
|
```sh
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
||||||
|
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends libopus0 ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6.运行项目
|
||||||
|
|
||||||
|
```sh
|
||||||
|
poetry run python app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
# 方式三:本地源码运行
|
||||||
|
|
||||||
|
## 1.安装基础环境
|
||||||
|
|
||||||
|
本项目使用`conda`管理依赖环境,安装好后,开始执行以下命令。
|
||||||
|
|
||||||
|
```
|
||||||
|
conda remove -n xiaozhi-esp32-server --all -y
|
||||||
|
conda create -n xiaozhi-esp32-server python=3.10 -y
|
||||||
|
conda activate xiaozhi-esp32-server
|
||||||
|
```
|
||||||
|
|
||||||
|
执行以上命令后, 如果你的电脑是Windows或Mac,执行下面的语句:
|
||||||
|
|
||||||
|
```
|
||||||
|
conda activate xiaozhi-esp32-server
|
||||||
|
conda install conda-forge::libopus
|
||||||
|
conda install conda-forge::ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
如果你的电脑是ubuntu,执行下面的语句:
|
||||||
|
|
||||||
|
```
|
||||||
|
apt-get install libopus0 ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2.安装本项目依赖
|
||||||
|
|
||||||
|
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
|
||||||
|
|
||||||
|
你可以用浏览器打开这个地址`https://github.com/xinnan-tech/xiaozhi-esp32-server.git`
|
||||||
|
|
||||||
|
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
|
||||||
|
|
||||||
|
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`xiaozhi-esp32-server-main`
|
||||||
|
你需要把它重命名成`xiaozhi-esp32-server`,好了请记住这个目录,我们暂且称它为`项目目录`。
|
||||||
|
|
||||||
|
```
|
||||||
|
# 使用dos或者终端,进入到你的项目目录,执行以下命令
|
||||||
|
conda activate xiaozhi-esp32-server
|
||||||
|
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3.[跳转到下载语音识别模型文件](#模型文件)
|
||||||
|
|
||||||
|
## 4.[跳转到配置项目文件](#配置项目)
|
||||||
|
|
||||||
|
## 5.运行项目
|
||||||
|
|
||||||
|
```
|
||||||
|
# 确保在本项目的根目录下执行
|
||||||
|
conda activate xiaozhi-esp32-server
|
||||||
|
python app.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6.[跳转到运行状态确认](#运行状态确认)
|
||||||
|
|
||||||
|
# 汇总
|
||||||
|
|
||||||
|
## 配置项目
|
||||||
|
|
||||||
|
修改`config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM`
|
||||||
|
,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。
|
||||||
|
默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。
|
||||||
|
|
||||||
|
```
|
||||||
|
# 如果您是一名开发者,建议阅读以下内容。如果不是开发者,可以忽略这部分内容。
|
||||||
|
# 在开发中,在项目根目录创建data目录,将【config.yaml】复制一份,改成【.config.yaml】,放进data目录中
|
||||||
|
# 系统会优先读取【data/.config.yaml】文件的配置。
|
||||||
|
# 这样做,可以避免在提交代码的时候,错误地提交密钥信息,保护您的密钥安全。
|
||||||
|
```
|
||||||
|
|
||||||
|
配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。
|
||||||
|
|
||||||
|
本项目的默认配置仅是成本最低配置(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。
|
||||||
|
|
||||||
|
```
|
||||||
|
selected_module:
|
||||||
|
ASR: FunASR
|
||||||
|
VAD: SileroVAD
|
||||||
|
LLM: ChatGLMLLM
|
||||||
|
TTS: EdgeTTS
|
||||||
|
```
|
||||||
|
|
||||||
|
比如修改`LLM`使用的组件,就看本项目支持哪些`LLM` API接口,当前支持的是`openai`、`dify`。欢迎验证和支持更多LLM平台的接口。
|
||||||
|
使用时,在`selected_module`修改成对应的如下LLM配置的名称:
|
||||||
|
|
||||||
|
```
|
||||||
|
LLM:
|
||||||
|
DeepSeekLLM:
|
||||||
|
type: openai
|
||||||
|
...
|
||||||
|
ChatGLMLLM:
|
||||||
|
type: openai
|
||||||
|
...
|
||||||
|
DifyLLM:
|
||||||
|
type: dify
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
有些服务,比如如果你使用`Dify`、`豆包的TTS`,是需要密钥的,记得在配置文件加上哦!
|
||||||
|
|
||||||
|
## 模型文件
|
||||||
|
|
||||||
|
下载源码后,需要下载模型文件。 默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
|
||||||
|
文件放在`model/SenseVoiceSmall`
|
||||||
|
目录下。下面两个下载路线任选一个。
|
||||||
|
|
||||||
|
- 线路一:阿里魔塔下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
||||||
|
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
|
||||||
|
`qvna`
|
||||||
|
|
||||||
|
|
||||||
|
## 运行状态确认
|
||||||
|
|
||||||
|
如果首次执行,可能需要几分钟时间,你要耐心等待他完成拉取。正常拉取完成后,你可以在命令行执行以下命令查看服务是否启动成功
|
||||||
|
|
||||||
|
```
|
||||||
|
docker ps
|
||||||
|
```
|
||||||
|
|
||||||
|
如果你能看到`xiaozhi-server`,说明服务启动成功。那你还可以进一步执行以下命令,查看服务的日志
|
||||||
|
|
||||||
|
```
|
||||||
|
docker logs -f xiaozhi-esp32-server
|
||||||
|
```
|
||||||
|
|
||||||
|
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
|
||||||
|
|
||||||
|
```
|
||||||
|
2025-xx-xx xx:51:59,492 - core.server - INFO - Server is running at ws://xx.xx.xx.xxx:8000
|
||||||
|
2025-xx-xx xx:51:59,516 - websockets.server - INFO - server listening on 0.0.0.0:8000
|
||||||
|
```
|
||||||
|
|
||||||
|
接下来,你就可以开始 `编译esp32固件`了,请往下翻,翻到编译`esp32固件`相关章节。那么由于你是用docker部署,你要自己查看自己本机电脑的ip是多少。
|
||||||
|
正常来说,假设你的ip是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。这个信息很有用的,后面`编译esp32固件`
|
||||||
|
需要用到。
|
||||||
|
|
||||||
|
请注意,你的接口地址是`websocket`协议的地址,你可以使用`apifox`等工具调试。但是不能直接用浏览器打开访问,如果用浏览器打开,日志会显示错误,会让你怀疑是否部署成功了。
|
||||||
|
|
||||||
|
## 版本升级操作
|
||||||
|
|
||||||
|
如果想升级版本,可以这么操作
|
||||||
|
|
||||||
|
1、备份好`config.yaml`文件,一些关键的配置到时复制到新的`config.yaml`文件里。
|
||||||
|
|
||||||
|
2、执行以下命令
|
||||||
|
|
||||||
|
```
|
||||||
|
docker stop xiaozhi-esp32-server
|
||||||
|
docker rm xiaozhi-esp32-server
|
||||||
|
docker rmi ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||||
|
```
|
||||||
|
|
@ -13,7 +13,7 @@ docker build -t xiaozhi-esp32-server:local -f ./Dockerfile .
|
||||||
docker stop xiaozhi-esp32-server
|
docker stop xiaozhi-esp32-server
|
||||||
docker rm xiaozhi-esp32-server
|
docker rm xiaozhi-esp32-server
|
||||||
|
|
||||||
docker run -d --name xiaozhi-esp32-server --restart always -p 8000:8000 -v $(pwd)/.config.yaml:/opt/xiaozhi-esp32-server/config.yaml xiaozhi-esp32-server:local
|
docker run -d --name xiaozhi-esp32-server --restart always -p 8000:8000 -v $(pwd)/data/.config.yaml:/opt/xiaozhi-esp32-server/config.yaml xiaozhi-esp32-server:local
|
||||||
|
|
||||||
docker logs -f xiaozhi-esp32-server
|
docker logs -f xiaozhi-esp32-server
|
||||||
|
|
||||||
|
|
|
||||||
89
docs/firmware-build.md
Normal file
89
docs/firmware-build.md
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
# 编译esp32固件
|
||||||
|
|
||||||
|
1. 下载`xiaozhi-esp32`
|
||||||
|
项目,按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf)
|
||||||
|
|
||||||
|
2. 打开`xiaozhi-esp32/main/Kconfig.projbuild`文件,找到`WEBSOCKET_URL`的`default`的内容,把`wss://api.tenclass.net`
|
||||||
|
改成你自己的地址,例如,我的接口地址是`ws://192.168.1.25:8000`,就把内容改成这个。
|
||||||
|
|
||||||
|
修改前:
|
||||||
|
|
||||||
|
```
|
||||||
|
config WEBSOCKET_URL
|
||||||
|
depends on CONNECTION_TYPE_WEBSOCKET
|
||||||
|
string "Websocket URL"
|
||||||
|
default "wss://api.tenclass.net/xiaozhi/v1/"
|
||||||
|
help
|
||||||
|
Communication with the server through websocket after wake up.
|
||||||
|
```
|
||||||
|
|
||||||
|
修改后(示例):
|
||||||
|
|
||||||
|
```
|
||||||
|
config WEBSOCKET_URL
|
||||||
|
depends on CONNECTION_TYPE_WEBSOCKET
|
||||||
|
string "Websocket URL"
|
||||||
|
default "ws://192.168.1.25:8000/xiaozhi/v1/"
|
||||||
|
help
|
||||||
|
Communication with the server through websocket after wake up.
|
||||||
|
```
|
||||||
|
|
||||||
|
注意:你的地址是`ws://`开头,不是`wss://`开头,一定不要写错了。
|
||||||
|
|
||||||
|
注意:你的地址是`ws://`开头,不是`wss://`开头,一定不要写错了。
|
||||||
|
|
||||||
|
注意:你的地址是`ws://`开头,不是`wss://`开头,一定不要写错了。
|
||||||
|
|
||||||
|
3. 设置编译参数
|
||||||
|
|
||||||
|
```
|
||||||
|
# 终端命令行进入xiaozhi-esp32的根目录
|
||||||
|
cd xiaozhi-esp32
|
||||||
|
# 例如我使用的板子是esp32s3,所以设置编译目标为esp32s3,如果你的板子是其他型号,请替换成对应的型号
|
||||||
|
idf.py set-target esp32s3
|
||||||
|
# 进入菜单配置
|
||||||
|
idf.py menuconfig
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
进入菜单配置后,再进入`Xiaozhi Assistant`,将`CONNECTION_TYPE`设置为`Websocket`
|
||||||
|
回退到主菜单,再进入`Xiaozhi Assistant`,将`BOARD_TYPE`设置你板子的具体型号
|
||||||
|
保存退出,回到终端命令行。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
4. 编译固件
|
||||||
|
|
||||||
|
```
|
||||||
|
idf.py build
|
||||||
|
```
|
||||||
|
|
||||||
|
如果是vscode安装的idf可以使用`F1`或者`ctrl+shift+p`,输入idf然后直接选择进行编译
|
||||||
|
|
||||||
|
还可以直接进行烧录不用接下来的操作
|
||||||
|
|
||||||
|
<img src="./images/vscode_idf.png" width="500px"/>
|
||||||
|
|
||||||
|
5. 打包bin固件
|
||||||
|
|
||||||
|
```
|
||||||
|
cd scripts
|
||||||
|
python release.py
|
||||||
|
```
|
||||||
|
|
||||||
|
编译成功后,会在项目根目录下的`build`目录下生成固件文件`merged-binary.bin`。
|
||||||
|
这个`merged-binary.bin`就是要烧录到硬件上的固件文件。
|
||||||
|
|
||||||
|
注意:如果执行到第二命令后,报了“zip”相关的错误,请忽略这个错误,只要`build`目录下生成固件文件`merged-binary.bin`
|
||||||
|
,对你没有太大影响,请继续。
|
||||||
|
|
||||||
|
6. 烧录固件
|
||||||
|
将esp32设备连接电脑,使用chrome浏览器,打开以下网址
|
||||||
|
|
||||||
|
```
|
||||||
|
https://espressif.github.io/esp-launchpad/
|
||||||
|
```
|
||||||
|
|
||||||
|
打开这个教程,[Flash工具/Web端烧录固件(无IDF开发环境)](https://ccnphfhqs21z.feishu.cn/wiki/Zpz4wXBtdimBrLk25WdcXzxcnNS)。
|
||||||
|
翻到:`方式二:ESP-Launchpad 浏览器WEB端烧录`,从`3. 烧录固件/下载到开发板`开始,按照教程操作。
|
||||||
BIN
docs/images/vscode_idf.png
Normal file
BIN
docs/images/vscode_idf.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 149 KiB |
|
|
@ -2,21 +2,24 @@ import os
|
||||||
import yaml
|
import yaml
|
||||||
import logging
|
import logging
|
||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from typing import Dict, Any
|
|
||||||
from core.utils.util import get_project_dir
|
from core.utils.util import get_project_dir
|
||||||
from config.private_config import PrivateConfig
|
from config.private_config import PrivateConfig
|
||||||
|
from manager.api.user_manager import UserManager # 添加导入
|
||||||
|
from core.utils.auth_code_gen import AuthCodeGenerator # 添加导入
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class ConfigHandler:
|
class ConfigHandler:
|
||||||
def __init__(self):
|
def __init__(self, session_manager):
|
||||||
self.private_config_path = get_project_dir() + '.private_config.yaml'
|
self.session_manager = session_manager
|
||||||
|
self.user_manager = UserManager() # 添加 user_manager 实例
|
||||||
|
self.private_config_path = get_project_dir() + 'data/.private_config.yaml'
|
||||||
self.config_path = get_project_dir() + 'config.yaml'
|
self.config_path = get_project_dir() + 'config.yaml'
|
||||||
# 如果存在.config.yaml文件,则使用该文件
|
# 如果存在.config.yaml文件,则使用该文件
|
||||||
if os.path.exists(get_project_dir() + ".config.yaml"):
|
if os.path.exists(get_project_dir() + "data/.config.yaml"):
|
||||||
self.config_path = get_project_dir() + ".config.yaml"
|
self.config_path = get_project_dir() + "data/.config.yaml"
|
||||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
self.config = yaml.safe_load(f)
|
self.config = yaml.safe_load(f)
|
||||||
|
|
||||||
async def get_module_options(self, request):
|
async def get_module_options(self, request):
|
||||||
"""Get all available module options from config.yaml"""
|
"""Get all available module options from config.yaml"""
|
||||||
|
|
@ -46,46 +49,41 @@ class ConfigHandler:
|
||||||
})
|
})
|
||||||
|
|
||||||
async def get_private_configs(self, request):
|
async def get_private_configs(self, request):
|
||||||
"""获取所有私有配置设备列表及其配置"""
|
"""只返回用户绑定的设备配置"""
|
||||||
try:
|
try:
|
||||||
|
username = request['username']
|
||||||
|
logger.info(f"Getting devices for user: {username}")
|
||||||
|
|
||||||
|
# 从用户管理器获取用户的设备列表
|
||||||
|
user_devices = await self.user_manager.get_user_devices(username)
|
||||||
|
logger.info(f"User {username} has devices: {user_devices}")
|
||||||
|
|
||||||
|
# 读取所有配置
|
||||||
|
all_configs = {}
|
||||||
if os.path.exists(self.private_config_path):
|
if os.path.exists(self.private_config_path):
|
||||||
with open(self.private_config_path, 'r', encoding='utf-8') as f:
|
with open(self.private_config_path, 'r', encoding='utf-8') as f:
|
||||||
all_configs = yaml.safe_load(f) or {}
|
all_configs = yaml.safe_load(f) or {}
|
||||||
else:
|
|
||||||
all_configs = {}
|
|
||||||
|
|
||||||
# 转换配置为前端友好的格式
|
# 只返回用户有权限的设备配置
|
||||||
devices = []
|
user_configs = {
|
||||||
for device_id, config in all_configs.items():
|
device_id: config
|
||||||
device_info = {
|
for device_id, config in all_configs.items()
|
||||||
'id': device_id,
|
if device_id in user_devices
|
||||||
'config': {
|
}
|
||||||
'selected_module': config.get('selected_module', {}),
|
|
||||||
'prompt': config.get('prompt', ''),
|
|
||||||
'last_chat_time': config.get('last_chat_time', ''),
|
|
||||||
'nickname': config.get('nickname', '小智'),
|
|
||||||
'modules': {
|
|
||||||
'LLM': config.get('LLM', {}),
|
|
||||||
'TTS': config.get('TTS', {}),
|
|
||||||
'ASR': config.get('ASR', {}),
|
|
||||||
'VAD': config.get('VAD', {})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
devices.append(device_info)
|
|
||||||
|
|
||||||
|
logger.info(f"Returning {len(user_configs)} device configs for user {username}")
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'success': True,
|
'success': True,
|
||||||
'data': devices,
|
'data': user_configs,
|
||||||
'message': '获取成功'
|
'message': '获取成功'
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error getting private configs: {str(e)}", exc_info=True)
|
logger.error(f"Error getting devices for user {request.get('username')}: {str(e)}", exc_info=True)
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'success': False,
|
'success': False,
|
||||||
'message': '获取配置失败'
|
'message': f'获取设备列表失败: {str(e)}'
|
||||||
})
|
}, status=400)
|
||||||
|
|
||||||
async def save_device_config(self, request):
|
async def save_device_config(self, request):
|
||||||
"""保存单个设备的配置"""
|
"""保存单个设备的配置"""
|
||||||
|
|
@ -93,6 +91,16 @@ class ConfigHandler:
|
||||||
data = await request.json()
|
data = await request.json()
|
||||||
device_id = data.get('id')
|
device_id = data.get('id')
|
||||||
config = data.get('config')
|
config = data.get('config')
|
||||||
|
username = request['username'] # 从请求中获取用户名
|
||||||
|
|
||||||
|
# 检查设备所有权
|
||||||
|
user_devices = await self.user_manager.get_user_devices(username)
|
||||||
|
if device_id not in user_devices:
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'message': '无权操作此设备'
|
||||||
|
}, status=403)
|
||||||
|
|
||||||
logger.info(f"Device config updated: {device_id} :\n{config}")
|
logger.info(f"Device config updated: {device_id} :\n{config}")
|
||||||
if not device_id or not config:
|
if not device_id or not config:
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
|
|
@ -131,10 +139,20 @@ class ConfigHandler:
|
||||||
try:
|
try:
|
||||||
data = await request.json()
|
data = await request.json()
|
||||||
device_id = data.get('device_id')
|
device_id = data.get('device_id')
|
||||||
|
username = request['username']
|
||||||
|
|
||||||
|
# 检查设备所有权
|
||||||
|
user_devices = await self.user_manager.get_user_devices(username)
|
||||||
|
if device_id not in user_devices:
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'message': '无权删除此设备'
|
||||||
|
}, status=403)
|
||||||
|
|
||||||
# 使用PrivateConfig处理配置删除
|
# 使用PrivateConfig处理配置删除
|
||||||
private_config = PrivateConfig(device_id, self.config)
|
private_config = PrivateConfig(device_id, self.config)
|
||||||
success = await private_config.delete_config()
|
success = await private_config.delete_config()
|
||||||
|
await self.user_manager.remove_device(username, device_id)
|
||||||
|
|
||||||
if not success:
|
if not success:
|
||||||
raise Exception("Failed to delete device config")
|
raise Exception("Failed to delete device config")
|
||||||
|
|
@ -150,3 +168,59 @@ class ConfigHandler:
|
||||||
'success': False,
|
'success': False,
|
||||||
'message': f'删除配置失败: {str(e)}'
|
'message': f'删除配置失败: {str(e)}'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
async def bind_device(self, request):
|
||||||
|
"""绑定设备到用户"""
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
auth_code = data.get('auth_code')
|
||||||
|
username = request['username']
|
||||||
|
|
||||||
|
if not auth_code or len(auth_code) != 6:
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'message': '请输入6位认证码'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
# 读取所有设备配置
|
||||||
|
with open(self.private_config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
|
# 查找匹配认证码的设备
|
||||||
|
device_found = None
|
||||||
|
for device_id, config in all_configs.items():
|
||||||
|
if config.get('auth_code') == auth_code and not config.get('owner'):
|
||||||
|
device_found = device_id
|
||||||
|
break
|
||||||
|
|
||||||
|
if not device_found:
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'message': '认证码无效或设备已被绑定'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
# 使用 PrivateConfig 进行绑定
|
||||||
|
private_config = PrivateConfig(device_found, self.config, AuthCodeGenerator())
|
||||||
|
await private_config.load_or_create()
|
||||||
|
|
||||||
|
# 绑定设备到用户 - 修改为异步调用
|
||||||
|
success = await private_config.bind_user(username)
|
||||||
|
if success:
|
||||||
|
# 同时更新用户的设备列表 - 修改为异步调用
|
||||||
|
await self.user_manager.add_device(username, device_found)
|
||||||
|
return web.json_response({
|
||||||
|
'success': True,
|
||||||
|
'message': '设备绑定成功'
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'message': '设备绑定失败'
|
||||||
|
}, status=500)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error binding device: {str(e)}", exc_info=True)
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'message': f'绑定设备失败: {str(e)}'
|
||||||
|
}, status=500)
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,9 @@ import datetime
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class LoginHandler:
|
class LoginHandler:
|
||||||
def __init__(self, config):
|
def __init__(self, user_manager, session_manager):
|
||||||
self.config = config
|
self.user_manager = user_manager
|
||||||
|
self.session_manager = session_manager
|
||||||
|
|
||||||
async def handle_login(self, request):
|
async def handle_login(self, request):
|
||||||
"""处理登录请求"""
|
"""处理登录请求"""
|
||||||
|
|
@ -22,8 +23,8 @@ class LoginHandler:
|
||||||
'message': '用户名和密码不能为空'
|
'message': '用户名和密码不能为空'
|
||||||
})
|
})
|
||||||
|
|
||||||
stored_user = self.config['get_user'](username)
|
stored_user = await self.user_manager.get_user(username)
|
||||||
if not stored_user or stored_user['password'] != self.config['hash_password'](password):
|
if not stored_user or stored_user['password'] != self.user_manager.hash_password(password):
|
||||||
logger.warning(f"Failed login attempt for user {username} from {request.remote}")
|
logger.warning(f"Failed login attempt for user {username} from {request.remote}")
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'success': False,
|
'success': False,
|
||||||
|
|
@ -31,14 +32,16 @@ class LoginHandler:
|
||||||
})
|
})
|
||||||
|
|
||||||
# 更新最后登录时间
|
# 更新最后登录时间
|
||||||
self.config['update_user'](username, {
|
await self.user_manager.update_user(username, {
|
||||||
'last_login': datetime.datetime.now().isoformat()
|
'last_login': datetime.datetime.now().isoformat()
|
||||||
})
|
})
|
||||||
|
|
||||||
logger.info(f"Successful login for user {username} from {request.remote}")
|
# 创建会话并返回session_id
|
||||||
|
session_id = self.session_manager.create_session(username)
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'success': True,
|
'success': True,
|
||||||
'message': '登录成功'
|
'message': '登录成功',
|
||||||
|
'session_id': session_id
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,10 @@ import datetime
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class RegisterHandler:
|
class RegisterHandler:
|
||||||
def __init__(self, config):
|
def __init__(self, user_manager):
|
||||||
self.config = config
|
self.user_manager = user_manager
|
||||||
|
|
||||||
async def handle_register(self, request):
|
async def handle_register(self, request):
|
||||||
"""处理注册请求"""
|
"""处理注册请求"""
|
||||||
|
|
@ -22,20 +23,23 @@ class RegisterHandler:
|
||||||
'message': '用户名和密码不能为空'
|
'message': '用户名和密码不能为空'
|
||||||
})
|
})
|
||||||
|
|
||||||
users = self.config.get('users', {})
|
# 检查用户是否已存在
|
||||||
if username in users:
|
if await self.user_manager.get_user(username):
|
||||||
logger.warning(f"Registration attempt with existing username {username} from {request.remote}")
|
logger.warning(f"Registration attempt with existing username {username} from {request.remote}")
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'success': False,
|
'success': False,
|
||||||
'message': '用户名已存在'
|
'message': '用户名已存在'
|
||||||
})
|
})
|
||||||
|
|
||||||
# 存储新用户
|
# 创建用户
|
||||||
self.config['users'][username] = {
|
user_data = {
|
||||||
'password': self.config['hash_password'](password),
|
'username': username,
|
||||||
'created_at': datetime.datetime.now().isoformat()
|
'password': self.user_manager.hash_password(password),
|
||||||
|
'devices': [],
|
||||||
|
'created_at': datetime.datetime.now().isoformat(),
|
||||||
|
'last_login': ''
|
||||||
}
|
}
|
||||||
self.config['save_user_data']()
|
await self.user_manager.add_user(username, user_data)
|
||||||
|
|
||||||
logger.info(f"Successfully registered new user {username} from {request.remote}")
|
logger.info(f"Successfully registered new user {username} from {request.remote}")
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
|
|
@ -44,7 +48,7 @@ class RegisterHandler:
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Registration error: {str(e)}", exc_info=True)
|
logger.error(f"Register error: {str(e)}", exc_info=True)
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'success': False,
|
'success': False,
|
||||||
'message': '注册失败,请稍后重试'
|
'message': '注册失败,请稍后重试'
|
||||||
|
|
|
||||||
|
|
@ -2,15 +2,16 @@ import os
|
||||||
import yaml
|
import yaml
|
||||||
import hashlib
|
import hashlib
|
||||||
import logging
|
import logging
|
||||||
|
from core.utils.util import get_project_dir
|
||||||
|
from core.utils.lock_manager import FileLockManager
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class UserManager:
|
class UserManager:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.secrets_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.secrets.yaml')
|
self.secrets_path = get_project_dir() + 'data/.secrets.yaml'
|
||||||
self.users = {}
|
self.lock_manager = FileLockManager()
|
||||||
self.ensure_secrets_file()
|
self.ensure_secrets_file()
|
||||||
self.load_user_data()
|
|
||||||
|
|
||||||
def ensure_secrets_file(self):
|
def ensure_secrets_file(self):
|
||||||
"""确保 .secrets.yaml 文件存在"""
|
"""确保 .secrets.yaml 文件存在"""
|
||||||
|
|
@ -27,23 +28,50 @@ class UserManager:
|
||||||
logger.error(f"Failed to create .secrets.yaml: {e}")
|
logger.error(f"Failed to create .secrets.yaml: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def load_user_data(self):
|
async def _load_user_data_internal(self):
|
||||||
"""加载用户数据"""
|
"""内部加载用户数据方法 - 不获取锁"""
|
||||||
try:
|
try:
|
||||||
with open(self.secrets_path, 'r', encoding='utf-8') as f:
|
with open(self.secrets_path, 'r', encoding='utf-8') as f:
|
||||||
data = yaml.safe_load(f) or {'users': {}}
|
data = yaml.safe_load(f) or {'users': {}}
|
||||||
self.users = data['users']
|
users = data['users']
|
||||||
logger.info("Successfully loaded user data")
|
logger.debug("Successfully loaded user data")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to load user data: {e}")
|
logger.error(f"Failed to load user data: {e}")
|
||||||
self.users = {}
|
users = {}
|
||||||
|
return users
|
||||||
|
|
||||||
def save_user_data(self):
|
async def load_user_data(self):
|
||||||
"""保存用户数据"""
|
"""加载用户数据"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.secrets_path)
|
||||||
|
try:
|
||||||
|
users = await self._load_user_data_internal()
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.secrets_path)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to load user data: {e}")
|
||||||
|
users = {}
|
||||||
|
return users
|
||||||
|
|
||||||
|
async def _save_user_data_internal(self, users):
|
||||||
|
"""内部保存用户数据方法 - 不获取锁"""
|
||||||
try:
|
try:
|
||||||
with open(self.secrets_path, 'w', encoding='utf-8') as f:
|
with open(self.secrets_path, 'w', encoding='utf-8') as f:
|
||||||
yaml.dump({'users': self.users}, f)
|
yaml.dump({'users': users}, f)
|
||||||
logger.info("Successfully saved user data")
|
logger.debug("Successfully saved user data")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to save user data: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def save_user_data(self, users):
|
||||||
|
"""外部保存用户数据方法 - 获取锁"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.secrets_path)
|
||||||
|
try:
|
||||||
|
await self._save_user_data_internal(users)
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.secrets_path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to save user data: {e}")
|
logger.error(f"Failed to save user data: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
@ -52,16 +80,95 @@ class UserManager:
|
||||||
"""密码哈希"""
|
"""密码哈希"""
|
||||||
return hashlib.sha256(password.encode()).hexdigest()
|
return hashlib.sha256(password.encode()).hexdigest()
|
||||||
|
|
||||||
def get_users(self):
|
async def get_users(self):
|
||||||
"""获取所有用户"""
|
"""异步获取所有用户"""
|
||||||
return self.users
|
users = await self.load_user_data() # 确保获取最新数据
|
||||||
|
return users
|
||||||
|
|
||||||
def get_user(self, username):
|
async def get_user(self, username):
|
||||||
"""获取指定用户"""
|
"""异步获取指定用户"""
|
||||||
return self.users.get(username)
|
users = await self.load_user_data() # 确保获取最新数据
|
||||||
|
return users.get(username)
|
||||||
|
|
||||||
def update_user(self, username, data):
|
async def add_user(self, username: str, user_data: dict):
|
||||||
|
"""异步添加新用户"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.secrets_path)
|
||||||
|
try:
|
||||||
|
users = await self._load_user_data_internal() # 确保获取最新数据
|
||||||
|
if username in users:
|
||||||
|
raise ValueError("User already exists")
|
||||||
|
users[username] = user_data
|
||||||
|
await self._save_user_data_internal(users)
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.secrets_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error adding user: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def update_user(self, username, data):
|
||||||
"""更新用户数据"""
|
"""更新用户数据"""
|
||||||
if username in self.users:
|
try:
|
||||||
self.users[username].update(data)
|
await self.lock_manager.acquire_lock(self.secrets_path)
|
||||||
self.save_user_data()
|
try:
|
||||||
|
users = await self._load_user_data_internal() # 确保获取最新数据
|
||||||
|
if username in users:
|
||||||
|
users[username].update(data)
|
||||||
|
await self._save_user_data_internal(users)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.secrets_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error updating user: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get_user_devices(self, username: str) -> list:
|
||||||
|
"""获取用户的设备列表"""
|
||||||
|
user = await self.get_user(username)
|
||||||
|
print(user)
|
||||||
|
if user and user.get('devices'):
|
||||||
|
return user['devices']
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def add_device(self, username: str, device_id: str) -> bool:
|
||||||
|
"""添加设备到用户的设备列表"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.secrets_path)
|
||||||
|
try:
|
||||||
|
users = await self._load_user_data_internal() # 确保获取最新数据
|
||||||
|
user = users.get(username) # 直接从内存获取,因为已经有锁
|
||||||
|
if not user:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if 'devices' not in user:
|
||||||
|
user['devices'] = []
|
||||||
|
|
||||||
|
if device_id not in user['devices']:
|
||||||
|
user['devices'].append(device_id)
|
||||||
|
await self._save_user_data_internal(users)
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.secrets_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error adding device: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def remove_device(self, username: str, device_id: str) -> bool:
|
||||||
|
"""从用户的设备列表中移除设备"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.secrets_path)
|
||||||
|
try:
|
||||||
|
users = await self._load_user_data_internal() # 确保获取最新数据
|
||||||
|
user = users.get(username) # 直接从内存获取,因为已经有锁
|
||||||
|
if user and 'devices' in user:
|
||||||
|
if device_id in user['devices']:
|
||||||
|
user['devices'].remove(device_id)
|
||||||
|
await self._save_user_data_internal(users)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.secrets_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error removing device: {e}")
|
||||||
|
return False
|
||||||
|
|
|
||||||
|
|
@ -13,26 +13,33 @@ from manager.api.login import LoginHandler
|
||||||
from manager.api.register import RegisterHandler
|
from manager.api.register import RegisterHandler
|
||||||
from manager.api.user_manager import UserManager
|
from manager.api.user_manager import UserManager
|
||||||
from manager.api.config import ConfigHandler
|
from manager.api.config import ConfigHandler
|
||||||
|
from manager.session import SessionManager
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def auth_required(handler):
|
||||||
|
"""鉴权装饰器"""
|
||||||
|
@wraps(handler)
|
||||||
|
async def wrapper(self, request):
|
||||||
|
session_id = request.cookies.get('session_id')
|
||||||
|
username = self.session_manager.validate_session(session_id)
|
||||||
|
if not username:
|
||||||
|
return web.json_response({'error': 'Unauthorized'}, status=401)
|
||||||
|
# 将用户名添加到请求对象
|
||||||
|
request['username'] = username
|
||||||
|
return await handler(self, request)
|
||||||
|
return wrapper
|
||||||
|
|
||||||
class WebUI:
|
class WebUI:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.app = web.Application()
|
self.app = web.Application()
|
||||||
self.user_manager = UserManager()
|
self.user_manager = UserManager()
|
||||||
|
self.session_manager = SessionManager()
|
||||||
|
|
||||||
# 添加静态文件路径
|
# 添加静态文件路径
|
||||||
self.static_path = os.path.join(root_dir, 'manager', 'static', 'webui')
|
self.static_path = os.path.join(root_dir, 'manager', 'static', 'webui')
|
||||||
|
|
||||||
# 创建配置字典
|
|
||||||
self.config = {
|
|
||||||
'users': self.user_manager.get_users(),
|
|
||||||
'hash_password': self.user_manager.hash_password,
|
|
||||||
'save_user_data': self.user_manager.save_user_data,
|
|
||||||
'get_user': self.user_manager.get_user,
|
|
||||||
'update_user': self.user_manager.update_user
|
|
||||||
}
|
|
||||||
|
|
||||||
self.setup_routes()
|
self.setup_routes()
|
||||||
self.setup_cors()
|
self.setup_cors()
|
||||||
|
|
||||||
|
|
@ -52,18 +59,21 @@ class WebUI:
|
||||||
|
|
||||||
def setup_routes(self):
|
def setup_routes(self):
|
||||||
"""设置路由"""
|
"""设置路由"""
|
||||||
login_handler = LoginHandler(self.config)
|
login_handler = LoginHandler(self.user_manager, self.session_manager)
|
||||||
register_handler = RegisterHandler(self.config)
|
register_handler = RegisterHandler(self.user_manager)
|
||||||
config_handler = ConfigHandler()
|
config_handler = ConfigHandler(self.session_manager)
|
||||||
|
|
||||||
# API 路由
|
# Public APIs
|
||||||
self.app.router.add_post('/api/login', login_handler.handle_login)
|
self.app.router.add_post('/api/login', login_handler.handle_login)
|
||||||
self.app.router.add_post('/api/register', register_handler.handle_register)
|
self.app.router.add_post('/api/register', register_handler.handle_register)
|
||||||
self.app.router.add_get('/api/config/devices', config_handler.get_private_configs)
|
|
||||||
self.app.router.add_post('/api/config/device', config_handler.save_device_config)
|
# Protected APIs
|
||||||
self.app.router.add_get('/api/config/module-options', config_handler.get_module_options)
|
self.app.router.add_get('/api/config/devices', self.auth_wrapper(config_handler.get_private_configs))
|
||||||
self.app.router.add_post('/api/config/save_device_config', config_handler.save_device_config)
|
|
||||||
self.app.router.add_post('/api/config/delete_device', config_handler.delete_device_config)
|
self.app.router.add_get('/api/config/module-options', self.auth_wrapper(config_handler.get_module_options))
|
||||||
|
self.app.router.add_post('/api/config/save_device_config', self.auth_wrapper(config_handler.save_device_config))
|
||||||
|
self.app.router.add_post('/api/config/delete_device', self.auth_wrapper(config_handler.delete_device_config))
|
||||||
|
self.app.router.add_post('/api/config/bind_device', self.auth_wrapper(config_handler.bind_device))
|
||||||
|
|
||||||
# 添加静态文件服务
|
# 添加静态文件服务
|
||||||
self.app.router.add_static('/assets/', path=os.path.join(self.static_path, 'assets'))
|
self.app.router.add_static('/assets/', path=os.path.join(self.static_path, 'assets'))
|
||||||
|
|
@ -77,6 +87,26 @@ class WebUI:
|
||||||
return web.FileResponse(index_file)
|
return web.FileResponse(index_file)
|
||||||
return web.Response(status=404, text='Not found')
|
return web.Response(status=404, text='Not found')
|
||||||
|
|
||||||
|
def auth_wrapper(self, handler):
|
||||||
|
"""包装处理器添加鉴权"""
|
||||||
|
@wraps(handler)
|
||||||
|
async def wrapper(request):
|
||||||
|
# 从请求头获取session_id
|
||||||
|
session_id = request.headers.get('Authorization')
|
||||||
|
if not session_id:
|
||||||
|
logger.warning("No session_id in Authorization header")
|
||||||
|
return web.json_response({'error': 'Unauthorized'}, status=401)
|
||||||
|
|
||||||
|
username = self.session_manager.validate_session(session_id)
|
||||||
|
if not username:
|
||||||
|
logger.warning(f"Invalid session_id: {session_id}")
|
||||||
|
return web.json_response({'error': 'Unauthorized'}, status=401)
|
||||||
|
|
||||||
|
request['username'] = username
|
||||||
|
logger.debug(f"Auth success for user: {username}")
|
||||||
|
return await handler(request)
|
||||||
|
return wrapper
|
||||||
|
|
||||||
def run(self, host='0.0.0.0', port=8002):
|
def run(self, host='0.0.0.0', port=8002):
|
||||||
"""运行服务器"""
|
"""运行服务器"""
|
||||||
local_ip = get_local_ip()
|
local_ip = get_local_ip()
|
||||||
|
|
|
||||||
33
manager/session.py
Normal file
33
manager/session.py
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
import time
|
||||||
|
from typing import Dict, Optional
|
||||||
|
|
||||||
|
class SessionManager:
|
||||||
|
def __init__(self):
|
||||||
|
self.sessions: Dict[str, Dict] = {}
|
||||||
|
self.session_timeout = 24 * 60 * 60 # 24小时过期
|
||||||
|
|
||||||
|
def create_session(self, username: str) -> str:
|
||||||
|
"""创建新会话"""
|
||||||
|
session_id = str(hash(f"{username}:{time.time()}"))
|
||||||
|
self.sessions[session_id] = {
|
||||||
|
'username': username,
|
||||||
|
'created_at': time.time()
|
||||||
|
}
|
||||||
|
return session_id
|
||||||
|
|
||||||
|
def validate_session(self, session_id: str) -> Optional[str]:
|
||||||
|
"""验证会话是否有效,返回用户名"""
|
||||||
|
if session_id not in self.sessions:
|
||||||
|
return None
|
||||||
|
|
||||||
|
session = self.sessions[session_id]
|
||||||
|
if time.time() - session['created_at'] > self.session_timeout:
|
||||||
|
del self.sessions[session_id]
|
||||||
|
return None
|
||||||
|
|
||||||
|
return session['username']
|
||||||
|
|
||||||
|
def remove_session(self, session_id: str):
|
||||||
|
"""删除会话"""
|
||||||
|
if session_id in self.sessions:
|
||||||
|
del self.sessions[session_id]
|
||||||
4349
poetry.lock
generated
Normal file
4349
poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
37
pyproject.toml
Normal file
37
pyproject.toml
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
[tool.poetry]
|
||||||
|
name = "xiaozhi-esp32-server"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = ""
|
||||||
|
authors = ["kalicyh <34980061+kaliCYH@users.noreply.github.com>"]
|
||||||
|
readme = "README.md"
|
||||||
|
|
||||||
|
[tool.poetry.dependencies]
|
||||||
|
python = "^3.10.16"
|
||||||
|
pyyml = "0.0.2"
|
||||||
|
torch = "2.2.2"
|
||||||
|
silero-vad = "5.1.2"
|
||||||
|
websockets = "14.2"
|
||||||
|
opuslib = "3.0.1"
|
||||||
|
numpy = "1.26.4"
|
||||||
|
pydub = "0.25.1"
|
||||||
|
funasr = "1.2.3"
|
||||||
|
torchaudio = "2.2.2"
|
||||||
|
openai = "1.61.0"
|
||||||
|
google-generativeai = "0.8.4"
|
||||||
|
edge-tts = "7.0.0"
|
||||||
|
httpx = "0.27.2"
|
||||||
|
aiohttp = "3.9.3"
|
||||||
|
aiohttp-cors = "0.7.0"
|
||||||
|
ormsgpack = "1.7.0"
|
||||||
|
ruamel-yaml = "0.18.10"
|
||||||
|
setuptools = "^75.8.0"
|
||||||
|
|
||||||
|
|
||||||
|
[[tool.poetry.source]]
|
||||||
|
name = "mirrors"
|
||||||
|
url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
|
||||||
|
priority = "primary"
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["poetry-core"]
|
||||||
|
build-backend = "poetry.core.masonry.api"
|
||||||
Loading…
Reference in a new issue