mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
Merge branch 'develop' into Increase-tts
This commit is contained in:
commit
64677d6adf
34 changed files with 2201 additions and 796 deletions
46
.github/workflows/docker-image.yml
vendored
Normal file
46
.github/workflows/docker-image.yml
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*' # 只在以 v 开头的标签推送时触发,例如 v1.0.0
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release Docker image
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
contents: write
|
||||
id-token: write
|
||||
issues: write
|
||||
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.TOKEN }}
|
||||
|
||||
- name: Extract version from tag
|
||||
id: get_version
|
||||
run: |
|
||||
echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: build_push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
ghcr.io/${{ github.repository }}:${{ env.VERSION }}
|
||||
ghcr.io/${{ github.repository }}:latest
|
||||
platforms: linux/amd64,linux/arm64
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -143,4 +143,6 @@ tmp
|
|||
.config.yaml
|
||||
.secrets.yaml
|
||||
.private_config.yaml
|
||||
.env.development
|
||||
docker-compose.yml
|
||||
models/jina-embeddings-v2-base-zh/onnx/model.onnx
|
||||
|
|
|
|||
56
Dockerfile
56
Dockerfile
|
|
@ -1,46 +1,50 @@
|
|||
# 第一阶段:前端构建
|
||||
FROM node:18 AS frontend-builder
|
||||
|
||||
FROM kalicyh/node:v18-alpine AS frontend-builder
|
||||
|
||||
WORKDIR /app/ZhiKongTaiWeb
|
||||
|
||||
RUN corepack enable && yarn config set registry https://registry.npmmirror.com
|
||||
# RUN corepack enable && yarn config set registry https://registry.npmmirror.com
|
||||
|
||||
COPY ZhiKongTaiWeb/package.json ZhiKongTaiWeb/yarn.lock ./
|
||||
|
||||
RUN mkdir node_modules && yarn install --frozen-lockfile
|
||||
RUN yarn install --frozen-lockfile
|
||||
|
||||
COPY ZhiKongTaiWeb .
|
||||
RUN yarn build
|
||||
|
||||
# 第二阶段:构建 Python 依赖
|
||||
FROM ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest AS builder
|
||||
|
||||
FROM kalicyh/poetry:v3.10_xiaozhi AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY pyproject.toml poetry.lock /app/
|
||||
|
||||
# 同时拷贝本地环境.venv
|
||||
COPY . .
|
||||
# 检查是否有缺失
|
||||
RUN poetry install --no-root
|
||||
|
||||
# 第三阶段:生产镜像
|
||||
FROM python:3.10-slim
|
||||
|
||||
WORKDIR /opt/xiaozhi-esp32-server
|
||||
|
||||
# 使用清华源加速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 update && \
|
||||
apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
||||
apt-get clean
|
||||
# 使用清华源加速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 update && \
|
||||
# apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
||||
# apt-get clean
|
||||
|
||||
# 从构建阶段复制虚拟环境和前端构建产物
|
||||
COPY --from=builder /app/.venv /opt/venv
|
||||
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /opt/xiaozhi-esp32-server/manager/static/webui
|
||||
# 设置虚拟环境路径
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /app/manager/static/webui
|
||||
|
||||
# 复制应用代码
|
||||
COPY . .
|
||||
# 下载模型文件(断点续传 + 自动重试)
|
||||
RUN mkdir -p /app/model/SenseVoiceSmall && \
|
||||
wget -O /app/model/SenseVoiceSmall/model.pt -c --tries=5 --waitretry=5 \
|
||||
https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt
|
||||
|
||||
# 设置虚拟环境路径
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
# 启动应用
|
||||
CMD ["python", "app.py"]
|
||||
ENTRYPOINT ["poetry", "run", "python"]
|
||||
CMD ["app.py"]
|
||||
57
Dockerfile-pip
Executable file
57
Dockerfile-pip
Executable file
|
|
@ -0,0 +1,57 @@
|
|||
# 第一阶段:前端构建
|
||||
FROM node:18 AS frontend-builder
|
||||
|
||||
WORKDIR /app/ZhiKongTaiWeb
|
||||
|
||||
# 配置npm使用淘宝源
|
||||
RUN npm config set registry https://registry.npmmirror.com
|
||||
|
||||
COPY ZhiKongTaiWeb/package*.json ./
|
||||
|
||||
# 安装axios依赖
|
||||
RUN npm install axios
|
||||
RUN npm install
|
||||
|
||||
COPY ZhiKongTaiWeb .
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# 第二阶段:构建Python依赖
|
||||
FROM python:3.10-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
|
||||
# 优化apt安装
|
||||
RUN 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 && \
|
||||
apt-get update && \
|
||||
apt-get install -y --no-install-recommends gcc libopus-dev ffmpeg && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
# 直接使用系统Python
|
||||
pip install --no-cache-dir -r requirements.txt \
|
||||
-i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
|
||||
# 第三阶段:生产镜像
|
||||
FROM python:3.10-slim
|
||||
|
||||
WORKDIR /opt/xiaozhi-esp32-server
|
||||
|
||||
# 优化apt安装
|
||||
RUN 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 && \
|
||||
apt-get update && \
|
||||
apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 从构建阶段复制Python包和前端构建产物
|
||||
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
|
||||
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /opt/xiaozhi-esp32-server/manager/static/webui
|
||||
|
||||
# 复制应用代码
|
||||
COPY . .
|
||||
|
||||
# 启动应用
|
||||
CMD ["python", "app.py"]
|
||||
|
|
@ -4,7 +4,9 @@
|
|||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev": "concurrently -n 'Frontend,Backend' -c 'blue,green' 'yarn run dev:ui' 'npm run dev:api'",
|
||||
"dev:ui": "vite",
|
||||
"dev:api": "cd .. && poetry run python manager/http_server.py",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
|
|
@ -15,6 +17,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.1.4",
|
||||
"concurrently": "^9.1.2",
|
||||
"vite": "^5.4.8"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -337,6 +337,18 @@
|
|||
resolved "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.13.tgz#87b309a6379c22b926e696893237826f64339b6f"
|
||||
integrity sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==
|
||||
|
||||
ansi-regex@^5.0.1:
|
||||
version "5.0.1"
|
||||
resolved "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
|
||||
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
|
||||
|
||||
ansi-styles@^4.0.0, ansi-styles@^4.1.0:
|
||||
version "4.3.0"
|
||||
resolved "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937"
|
||||
integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==
|
||||
dependencies:
|
||||
color-convert "^2.0.1"
|
||||
|
||||
asynckit@^0.4.0:
|
||||
version "0.4.0"
|
||||
resolved "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
|
||||
|
|
@ -359,6 +371,35 @@ call-bind-apply-helpers@^1.0.1:
|
|||
es-errors "^1.3.0"
|
||||
function-bind "^1.1.2"
|
||||
|
||||
chalk@^4.1.2:
|
||||
version "4.1.2"
|
||||
resolved "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01"
|
||||
integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==
|
||||
dependencies:
|
||||
ansi-styles "^4.1.0"
|
||||
supports-color "^7.1.0"
|
||||
|
||||
cliui@^8.0.1:
|
||||
version "8.0.1"
|
||||
resolved "https://registry.npmmirror.com/cliui/-/cliui-8.0.1.tgz#0c04b075db02cbfe60dc8e6cf2f5486b1a3608aa"
|
||||
integrity sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==
|
||||
dependencies:
|
||||
string-width "^4.2.0"
|
||||
strip-ansi "^6.0.1"
|
||||
wrap-ansi "^7.0.0"
|
||||
|
||||
color-convert@^2.0.1:
|
||||
version "2.0.1"
|
||||
resolved "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3"
|
||||
integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==
|
||||
dependencies:
|
||||
color-name "~1.1.4"
|
||||
|
||||
color-name@~1.1.4:
|
||||
version "1.1.4"
|
||||
resolved "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
|
||||
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
|
||||
|
||||
combined-stream@^1.0.8:
|
||||
version "1.0.8"
|
||||
resolved "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
|
||||
|
|
@ -366,6 +407,19 @@ combined-stream@^1.0.8:
|
|||
dependencies:
|
||||
delayed-stream "~1.0.0"
|
||||
|
||||
concurrently@^9.1.2:
|
||||
version "9.1.2"
|
||||
resolved "https://registry.npmmirror.com/concurrently/-/concurrently-9.1.2.tgz#22d9109296961eaee773e12bfb1ce9a66bc9836c"
|
||||
integrity sha512-H9MWcoPsYddwbOGM6difjVwVZHl63nwMEwDJG/L7VGtuaJhb12h2caPG2tVPWs7emuYix252iGfqOyrz1GczTQ==
|
||||
dependencies:
|
||||
chalk "^4.1.2"
|
||||
lodash "^4.17.21"
|
||||
rxjs "^7.8.1"
|
||||
shell-quote "^1.8.1"
|
||||
supports-color "^8.1.1"
|
||||
tree-kill "^1.2.2"
|
||||
yargs "^17.7.2"
|
||||
|
||||
csstype@^3.1.3:
|
||||
version "3.1.3"
|
||||
resolved "https://registry.npmmirror.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81"
|
||||
|
|
@ -385,6 +439,11 @@ dunder-proto@^1.0.1:
|
|||
es-errors "^1.3.0"
|
||||
gopd "^1.2.0"
|
||||
|
||||
emoji-regex@^8.0.0:
|
||||
version "8.0.0"
|
||||
resolved "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
|
||||
integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
|
||||
|
||||
entities@^4.5.0:
|
||||
version "4.5.0"
|
||||
resolved "https://registry.npmmirror.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48"
|
||||
|
|
@ -446,6 +505,11 @@ esbuild@^0.21.3:
|
|||
"@esbuild/win32-ia32" "0.21.5"
|
||||
"@esbuild/win32-x64" "0.21.5"
|
||||
|
||||
escalade@^3.1.1:
|
||||
version "3.2.0"
|
||||
resolved "https://registry.npmmirror.com/escalade/-/escalade-3.2.0.tgz#011a3f69856ba189dffa7dc8fcce99d2a87903e5"
|
||||
integrity sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==
|
||||
|
||||
estree-walker@^2.0.2:
|
||||
version "2.0.2"
|
||||
resolved "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz#52f010178c2a4c117a7757cfe942adb7d2da4cac"
|
||||
|
|
@ -476,6 +540,11 @@ function-bind@^1.1.2:
|
|||
resolved "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c"
|
||||
integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==
|
||||
|
||||
get-caller-file@^2.0.5:
|
||||
version "2.0.5"
|
||||
resolved "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e"
|
||||
integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==
|
||||
|
||||
get-intrinsic@^1.2.6:
|
||||
version "1.2.7"
|
||||
resolved "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.7.tgz#dcfcb33d3272e15f445d15124bc0a216189b9044"
|
||||
|
|
@ -505,6 +574,11 @@ gopd@^1.2.0:
|
|||
resolved "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1"
|
||||
integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==
|
||||
|
||||
has-flag@^4.0.0:
|
||||
version "4.0.0"
|
||||
resolved "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b"
|
||||
integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==
|
||||
|
||||
has-symbols@^1.0.3, has-symbols@^1.1.0:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338"
|
||||
|
|
@ -524,6 +598,16 @@ hasown@^2.0.2:
|
|||
dependencies:
|
||||
function-bind "^1.1.2"
|
||||
|
||||
is-fullwidth-code-point@^3.0.0:
|
||||
version "3.0.0"
|
||||
resolved "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
|
||||
integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
|
||||
|
||||
lodash@^4.17.21:
|
||||
version "4.17.21"
|
||||
resolved "https://registry.npmmirror.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
|
||||
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
|
||||
|
||||
magic-string@^0.30.11:
|
||||
version "0.30.17"
|
||||
resolved "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.17.tgz#450a449673d2460e5bbcfba9a61916a1714c7453"
|
||||
|
|
@ -572,6 +656,11 @@ proxy-from-env@^1.1.0:
|
|||
resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
|
||||
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
|
||||
|
||||
require-directory@^2.1.1:
|
||||
version "2.1.1"
|
||||
resolved "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"
|
||||
integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==
|
||||
|
||||
rollup@^4.20.0:
|
||||
version "4.34.7"
|
||||
resolved "https://registry.npmmirror.com/rollup/-/rollup-4.34.7.tgz#e00d8550688a616a3481c6446bb688d4c753ba8f"
|
||||
|
|
@ -600,11 +689,63 @@ rollup@^4.20.0:
|
|||
"@rollup/rollup-win32-x64-msvc" "4.34.7"
|
||||
fsevents "~2.3.2"
|
||||
|
||||
rxjs@^7.8.1:
|
||||
version "7.8.1"
|
||||
resolved "https://registry.npmmirror.com/rxjs/-/rxjs-7.8.1.tgz#6f6f3d99ea8044291efd92e7c7fcf562c4057543"
|
||||
integrity sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==
|
||||
dependencies:
|
||||
tslib "^2.1.0"
|
||||
|
||||
shell-quote@^1.8.1:
|
||||
version "1.8.2"
|
||||
resolved "https://registry.npmmirror.com/shell-quote/-/shell-quote-1.8.2.tgz#d2d83e057959d53ec261311e9e9b8f51dcb2934a"
|
||||
integrity sha512-AzqKpGKjrj7EM6rKVQEPpB288oCfnrEIuyoT9cyF4nmGa7V8Zk6f7RRqYisX8X9m+Q7bd632aZW4ky7EhbQztA==
|
||||
|
||||
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==
|
||||
|
||||
string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
|
||||
version "4.2.3"
|
||||
resolved "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||
dependencies:
|
||||
emoji-regex "^8.0.0"
|
||||
is-fullwidth-code-point "^3.0.0"
|
||||
strip-ansi "^6.0.1"
|
||||
|
||||
strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
||||
version "6.0.1"
|
||||
resolved "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||
dependencies:
|
||||
ansi-regex "^5.0.1"
|
||||
|
||||
supports-color@^7.1.0:
|
||||
version "7.2.0"
|
||||
resolved "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da"
|
||||
integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==
|
||||
dependencies:
|
||||
has-flag "^4.0.0"
|
||||
|
||||
supports-color@^8.1.1:
|
||||
version "8.1.1"
|
||||
resolved "https://registry.npmmirror.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c"
|
||||
integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==
|
||||
dependencies:
|
||||
has-flag "^4.0.0"
|
||||
|
||||
tree-kill@^1.2.2:
|
||||
version "1.2.2"
|
||||
resolved "https://registry.npmmirror.com/tree-kill/-/tree-kill-1.2.2.tgz#4ca09a9092c88b73a7cdc5e8a01b507b0790a0cc"
|
||||
integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==
|
||||
|
||||
tslib@^2.1.0:
|
||||
version "2.8.1"
|
||||
resolved "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f"
|
||||
integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==
|
||||
|
||||
vite@^5.4.8:
|
||||
version "5.4.14"
|
||||
resolved "https://registry.npmmirror.com/vite/-/vite-5.4.14.tgz#ff8255edb02134df180dcfca1916c37a6abe8408"
|
||||
|
|
@ -633,3 +774,35 @@ vue@^3.5.10:
|
|||
"@vue/runtime-dom" "3.5.13"
|
||||
"@vue/server-renderer" "3.5.13"
|
||||
"@vue/shared" "3.5.13"
|
||||
|
||||
wrap-ansi@^7.0.0:
|
||||
version "7.0.0"
|
||||
resolved "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||
dependencies:
|
||||
ansi-styles "^4.0.0"
|
||||
string-width "^4.1.0"
|
||||
strip-ansi "^6.0.0"
|
||||
|
||||
y18n@^5.0.5:
|
||||
version "5.0.8"
|
||||
resolved "https://registry.npmmirror.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"
|
||||
integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==
|
||||
|
||||
yargs-parser@^21.1.1:
|
||||
version "21.1.1"
|
||||
resolved "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35"
|
||||
integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==
|
||||
|
||||
yargs@^17.7.2:
|
||||
version "17.7.2"
|
||||
resolved "https://registry.npmmirror.com/yargs/-/yargs-17.7.2.tgz#991df39aca675a192b816e1e0363f9d75d2aa269"
|
||||
integrity sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==
|
||||
dependencies:
|
||||
cliui "^8.0.1"
|
||||
escalade "^3.1.1"
|
||||
get-caller-file "^2.0.5"
|
||||
require-directory "^2.1.1"
|
||||
string-width "^4.2.3"
|
||||
y18n "^5.0.5"
|
||||
yargs-parser "^21.1.1"
|
||||
|
|
|
|||
78
config.yaml
78
config.yaml
|
|
@ -38,6 +38,20 @@ xiaozhi:
|
|||
sample_rate: 16000
|
||||
channels: 1
|
||||
frame_duration: 60
|
||||
|
||||
# 长期记忆参数
|
||||
memory:
|
||||
# 记忆摘要提示
|
||||
summary_prompt: "你还保留着一些长期的记忆,这有助于让你的对话更加丰富和连贯:"
|
||||
# 记忆最大长度
|
||||
max_memory_length: 10000
|
||||
# 摘要最大长度
|
||||
max_summary_length: 2000
|
||||
# 单次摘要长度
|
||||
summary_length: 1000
|
||||
# 记忆文件夹
|
||||
memory_dir: "memory_data"
|
||||
|
||||
prompt: |
|
||||
你是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
|
||||
请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。
|
||||
|
|
@ -65,6 +79,7 @@ selected_module:
|
|||
LLM: ChatGLMLLM
|
||||
# TTS将根据配置名称对应的type调用实际的TTS适配器
|
||||
TTS: EdgeTTS
|
||||
EMBD: SentenceTransformer
|
||||
|
||||
ASR:
|
||||
FunASR:
|
||||
|
|
@ -77,6 +92,13 @@ VAD:
|
|||
model_dir: models/snakers4_silero-vad
|
||||
min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些
|
||||
|
||||
EMBD:
|
||||
SentenceTransformer:
|
||||
# 下载 https://huggingface.co/jinaai/jina-embeddings-v2-base-zh/blob/main/onnx/model.onnx 到 models/jina-embeddings-v2-base-zh/onnx/model.onnx
|
||||
model_dir: models/jina-embeddings-v2-base-zh
|
||||
# cpu cuda:0 推荐cpu节省显存
|
||||
device: "cpu"
|
||||
|
||||
LLM:
|
||||
# 当前支持的type为openai、dify、ollama,可自行适配
|
||||
AliLLM:
|
||||
|
|
@ -217,6 +239,62 @@ TTS:
|
|||
parallel_infer: true
|
||||
repetition_penalty: 1.35
|
||||
aux_ref_audio_paths: []
|
||||
|
||||
MinimaxTTS:
|
||||
# Minimax语音合成服务,需要先在minimax平台创建账户充值,并获取登录信息
|
||||
# 平台地址:https://platform.minimaxi.com/
|
||||
# 充值地址:https://platform.minimaxi.com/user-center/payment/balance
|
||||
# group_id地址:https://platform.minimaxi.com/user-center/basic-information
|
||||
# api_key地址:https://platform.minimaxi.com/user-center/basic-information/interface-key
|
||||
# 定义TTS API类型
|
||||
type: minimax
|
||||
output_file: tmp/
|
||||
group_id: 你的minimax平台groupID
|
||||
api_key: 你的minimax平台接口密钥
|
||||
model: "speech-01-turbo"
|
||||
# 此处设置将优先于voice_setting中voice_id的设置;如都不设置,默认为 female-shaonv
|
||||
voice_id: "female-shaonv"
|
||||
# 以下可不用设置,使用默认设置
|
||||
# voice_setting:
|
||||
# voice_id: "male-qn-qingse"
|
||||
# speed: 1
|
||||
# vol: 1
|
||||
# pitch: 0
|
||||
# emotion: "happy"
|
||||
# pronunciation_dict:
|
||||
# tone:
|
||||
# - "处理/(chu3)(li3)"
|
||||
# - "危险/dangerous"
|
||||
# audio_setting:
|
||||
# sample_rate: 32000
|
||||
# bitrate: 128000
|
||||
# format: "mp3"
|
||||
# channel: 1
|
||||
# timber_weights:
|
||||
# -
|
||||
# voice_id: male-qn-qingse
|
||||
# weight: 1
|
||||
# -
|
||||
# voice_id: female-shaonv
|
||||
# weight: 1
|
||||
# language_boost: auto
|
||||
AliyunTTS:
|
||||
# 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
|
||||
# 平台地址:https://nls-portal.console.aliyun.com/
|
||||
# appkey地址:https://nls-portal.console.aliyun.com/applist
|
||||
# token地址:https://nls-portal.console.aliyun.com/overview
|
||||
# 定义TTS API类型
|
||||
type: aliyun
|
||||
output_file: tmp/
|
||||
appkey: 你的阿里云智能语音交互服务项目Appkey
|
||||
token: 你的阿里云智能语音交互服务AccessToken
|
||||
voice: xiaoyun
|
||||
# 以下可不用设置,使用默认设置
|
||||
# format: wav
|
||||
# sample_rate: 16000
|
||||
# volume: 50
|
||||
# speech_rate: 0
|
||||
# pitch_rate: 0
|
||||
fish_audio_tts:
|
||||
#最自然的AI语音
|
||||
#api申请地址https://fish.audio/zh-CN/go-api/billing/
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ def setup_logging(log_dir='tmp', data_dir='data'):
|
|||
|
||||
# 设置日志格式,时间、日志级别、标签、消息
|
||||
log_format = (
|
||||
"<green>{time:YYYY-MM-DD HH:mm:ss}</green>"
|
||||
# "<green>{time:YYYY-MM-DD HH:mm:ss}</green>"
|
||||
"[<light-blue>{extra[tag]}</light-blue>]"
|
||||
" - <level>{level}</level> - "
|
||||
"<light-green>{message}</light-green>"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from config.logger import setup_logging
|
|||
from typing import Dict, Any, Optional
|
||||
from copy import deepcopy
|
||||
from core.utils.util import get_project_dir
|
||||
from core.utils import asr, vad, llm, tts
|
||||
from core.utils import asr, vad, llm, tts, embedding
|
||||
from manager.api.user_manager import UserManager
|
||||
from core.utils.lock_manager import FileLockManager
|
||||
|
||||
|
|
@ -172,21 +172,12 @@ class PrivateConfig:
|
|||
# 判断存在私有配置,并且self.device_id在私有配置中
|
||||
if not self.private_config:
|
||||
self.logger.bind(tag=TAG).error("Private config not found for device_id: {}", self.device_id)
|
||||
return None, None, None, None
|
||||
return None, None
|
||||
|
||||
"""创建私有处理模块实例"""
|
||||
config = self.private_config
|
||||
selected_modules = config['selected_module']
|
||||
return (
|
||||
vad.create_instance(
|
||||
selected_modules["VAD"],
|
||||
config["VAD"][selected_modules["VAD"]]
|
||||
),
|
||||
asr.create_instance(
|
||||
selected_modules["ASR"],
|
||||
config["ASR"][selected_modules["ASR"]],
|
||||
self.default_config.get("delete_audio", True) # Using default_config for global settings
|
||||
),
|
||||
llm.create_instance(
|
||||
selected_modules["LLM"]
|
||||
if not 'type' in config["LLM"][selected_modules["LLM"]]
|
||||
|
|
@ -201,6 +192,10 @@ class PrivateConfig:
|
|||
config["TTS"][selected_modules["TTS"]]["type"],
|
||||
config["TTS"][selected_modules["TTS"]],
|
||||
self.default_config.get("delete_audio", True) # Using default_config for global settings
|
||||
),
|
||||
embedding.create_instance(
|
||||
selected_modules["EMBD"],
|
||||
config["EMBD"][selected_modules["EMBD"]]
|
||||
)
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -17,12 +17,13 @@ from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
|||
from core.handle.audioHandle import handleAudioMessage, sendAudioMessage
|
||||
from config.private_config import PrivateConfig
|
||||
from core.auth import AuthMiddleware, AuthenticationError
|
||||
from core.utils.llm_memory import MemoryManager
|
||||
from core.utils.auth_code_gen import AuthCodeGenerator # 添加导入
|
||||
|
||||
TAG = __name__
|
||||
|
||||
class ConnectionHandler:
|
||||
def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts):
|
||||
def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _embd):
|
||||
self.config = config
|
||||
self.logger = setup_logging()
|
||||
self.auth = AuthMiddleware(config)
|
||||
|
|
@ -49,6 +50,7 @@ class ConnectionHandler:
|
|||
self.asr = _asr
|
||||
self.llm = _llm
|
||||
self.tts = _tts
|
||||
self.embd = _embd
|
||||
self.dialogue = None
|
||||
|
||||
# vad相关变量
|
||||
|
|
@ -83,6 +85,17 @@ class ConnectionHandler:
|
|||
self.is_device_verified = False # 添加设备验证状态标志
|
||||
|
||||
|
||||
self.llm_memory = MemoryManager(
|
||||
llm=_llm,
|
||||
embd=_embd,
|
||||
summary_prompt=config.get("memory", {}).get("summary_prompt", "你还保留着一些长期的记忆,这有助于让你的对话更加丰富和连贯:"),
|
||||
max_memory_length=config.get("memory", {}).get("max_memory_length", 10000),
|
||||
max_summary_length=config.get("memory", {}).get("max_summary_length", 2000),
|
||||
summary_length=config.get("memory", {}).get("summary_length", 1000),
|
||||
memory_dir=config.get("memory", {}).get("memory_dir", "memory_data"),
|
||||
)
|
||||
|
||||
|
||||
async def handle_connection(self, ws):
|
||||
try:
|
||||
# 获取并验证headers
|
||||
|
|
@ -93,11 +106,13 @@ class ConnectionHandler:
|
|||
await self.auth.authenticate(self.headers)
|
||||
|
||||
device_id = self.headers.get("device-id", None)
|
||||
self.device_id = device_id
|
||||
|
||||
# Load private configuration if device_id is provided
|
||||
bUsePrivateConfig = self.config.get("use_private_config", False)
|
||||
self.logger.bind(tag=TAG).info(f"bUsePrivateConfig: {bUsePrivateConfig}, device_id: {device_id}")
|
||||
if bUsePrivateConfig and device_id:
|
||||
|
||||
try:
|
||||
self.private_config = PrivateConfig(device_id, self.config, self.auth_code_gen)
|
||||
await self.private_config.load_or_create()
|
||||
|
|
@ -108,13 +123,13 @@ class ConnectionHandler:
|
|||
if self.is_device_verified:
|
||||
await self.private_config.update_last_chat_time()
|
||||
|
||||
vad, asr, llm, tts = self.private_config.create_private_instances()
|
||||
if all([vad, asr, llm, tts]):
|
||||
self.vad = vad
|
||||
self.asr = asr
|
||||
llm, tts = self.private_config.create_private_instances()
|
||||
if all([llm, tts]):
|
||||
self.llm = llm
|
||||
self.tts = tts
|
||||
self.embd = embd
|
||||
self.logger.bind(tag=TAG).info(f"Loaded private config and instances for device {device_id}")
|
||||
|
||||
else:
|
||||
self.logger.bind(tag=TAG).error(f"Failed to create instances for device {device_id}")
|
||||
self.private_config = None
|
||||
|
|
@ -141,6 +156,7 @@ class ConnectionHandler:
|
|||
await self._route_message(message)
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
self.logger.bind(tag=TAG).info("客户端断开连接")
|
||||
await self.llm_memory.add_chat_paragraph(device_id,self.dialogue.get_llm_dialogue()[1:])
|
||||
await self.close()
|
||||
|
||||
except AuthenticationError as e:
|
||||
|
|
@ -149,6 +165,8 @@ class ConnectionHandler:
|
|||
return
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}")
|
||||
await self.llm_memory.add_chat_paragraph(device_id,self.dialogue.get_llm_dialogue()[1:])
|
||||
|
||||
await ws.close()
|
||||
return
|
||||
|
||||
|
|
@ -182,6 +200,7 @@ class ConnectionHandler:
|
|||
return False
|
||||
return True
|
||||
|
||||
|
||||
def isNeedAuth(self):
|
||||
bUsePrivateConfig = self.config.get("use_private_config", False)
|
||||
if not bUsePrivateConfig:
|
||||
|
|
@ -202,13 +221,18 @@ class ConnectionHandler:
|
|||
loop.close()
|
||||
return True
|
||||
|
||||
query = self.llm_memory.handle_user_scene(self.device_id, query)
|
||||
self.dialogue.put(Message(role="user", content=query))
|
||||
response_message = []
|
||||
start = 0
|
||||
# 提交 LLM 任务
|
||||
try:
|
||||
start_time = time.time() # 记录开始时间
|
||||
llm_responses = self.llm.response(self.session_id, self.dialogue.get_llm_dialogue())
|
||||
memory_summary = self.llm_memory.get_memory_summary(self.device_id)
|
||||
llm_responses = self.llm.response(
|
||||
self.session_id,
|
||||
self.dialogue.get_llm_dialogue_with_memory(memory_summary)
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
|
||||
return None
|
||||
|
|
|
|||
57
core/providers/tts/aliyun.py
Normal file
57
core/providers/tts/aliyun.py
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import os
|
||||
import uuid
|
||||
import json
|
||||
import requests
|
||||
from datetime import datetime
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
|
||||
import http.client
|
||||
import urllib.parse
|
||||
|
||||
|
||||
class TTSProvider(TTSProviderBase):
|
||||
def __init__(self, config, delete_audio_file):
|
||||
super().__init__(config, delete_audio_file)
|
||||
self.appkey = config.get("appkey")
|
||||
self.token = config.get("token")
|
||||
self.format = config.get("format", "wav")
|
||||
self.sample_rate = config.get("sample_rate", 16000)
|
||||
self.voice = config.get("voice", "xiaoyun")
|
||||
self.volume = config.get("volume", 50)
|
||||
self.speech_rate = config.get("speech_rate", 0)
|
||||
self.pitch_rate = config.get("pitch_rate", 0)
|
||||
|
||||
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
||||
self.api_url = f"https://{self.host}/stream/v1/tts"
|
||||
self.header = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def generate_filename(self, extension=".wav"):
|
||||
return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||
|
||||
async def text_to_speak(self, text, output_file):
|
||||
request_json = {
|
||||
"appkey": self.appkey,
|
||||
"token": self.token,
|
||||
"text": text,
|
||||
"format": self.format,
|
||||
"sample_rate": self.sample_rate,
|
||||
"voice": self.voice,
|
||||
"volume": self.volume,
|
||||
"speech_rate": self.speech_rate,
|
||||
"pitch_rate": self.pitch_rate
|
||||
}
|
||||
|
||||
print(self.api_url, json.dumps(request_json, ensure_ascii=False))
|
||||
try:
|
||||
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
||||
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
|
||||
if resp.headers['Content-Type'].startswith('audio/'):
|
||||
with open(output_file, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
return output_file
|
||||
else:
|
||||
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||
except Exception as e:
|
||||
raise Exception(f"{__name__} error: {e}")
|
||||
|
|
@ -2,7 +2,7 @@ import asyncio
|
|||
from config.logger import setup_logging
|
||||
import os
|
||||
import numpy as np
|
||||
import opuslib
|
||||
import opuslib_next
|
||||
from pydub import AudioSegment
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
|
@ -58,7 +58,7 @@ class TTSProviderBase(ABC):
|
|||
raw_data = audio.raw_data
|
||||
|
||||
# 初始化Opus编码器
|
||||
encoder = opuslib.Encoder(16000, 1, opuslib.APPLICATION_AUDIO)
|
||||
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
|
||||
|
||||
# 编码参数
|
||||
frame_duration = 60 # 60ms per frame
|
||||
|
|
|
|||
77
core/providers/tts/minimax.py
Normal file
77
core/providers/tts/minimax.py
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import os
|
||||
import uuid
|
||||
import json
|
||||
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.group_id = config.get("group_id")
|
||||
self.api_key = config.get("api_key")
|
||||
self.model = config.get("model")
|
||||
self.voice_id = config.get("voice_id")
|
||||
|
||||
default_voice_setting = {
|
||||
"voice_id": "female-shaonv",
|
||||
"speed": 1,
|
||||
"vol": 1,
|
||||
"pitch": 0,
|
||||
"emotion": "happy"
|
||||
}
|
||||
default_pronunciation_dict = {
|
||||
"tone": [
|
||||
"处理/(chu3)(li3)", "危险/dangerous"
|
||||
]
|
||||
}
|
||||
defult_audio_setting = {
|
||||
"sample_rate": 32000,
|
||||
"bitrate": 128000,
|
||||
"format": "mp3",
|
||||
"channel": 1
|
||||
}
|
||||
self.voice_setting = {**default_voice_setting, **config.get("voice_setting", {})}
|
||||
self.pronunciation_dict = {**default_pronunciation_dict, **config.get("pronunciation_dict", {})}
|
||||
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
|
||||
self.timber_weights = config.get("timber_weights", [])
|
||||
|
||||
if self.voice_id:
|
||||
self.voice_setting["voice_id"] = self.voice_id
|
||||
|
||||
self.host = "api.minimax.chat"
|
||||
self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}"
|
||||
self.header = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}"
|
||||
}
|
||||
|
||||
def generate_filename(self, extension=".mp3"):
|
||||
return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||
|
||||
async def text_to_speak(self, text, output_file):
|
||||
request_json = {
|
||||
"model": self.model,
|
||||
"text": text,
|
||||
"stream": False,
|
||||
"voice_setting": self.voice_setting,
|
||||
"pronunciation_dict": self.pronunciation_dict,
|
||||
"audio_setting": self.audio_setting,
|
||||
}
|
||||
|
||||
if type(self.timber_weights) is list and len(self.timber_weights) > 0:
|
||||
request_json["timber_weights"] = self.timber_weights
|
||||
request_json["voice_setting"]["voice_id"] = ""
|
||||
|
||||
try:
|
||||
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
||||
# 检查返回请求数据的status_code是否为0
|
||||
if resp.json()["base_resp"]["status_code"] == 0:
|
||||
data = resp.json()['data']['audio']
|
||||
file_to_save = open(output_file, "wb")
|
||||
file_to_save.write(bytes.fromhex(data))
|
||||
else:
|
||||
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||
except Exception as e:
|
||||
raise Exception(f"{__name__} error: {e}")
|
||||
|
|
@ -1,18 +1,36 @@
|
|||
import time
|
||||
import wave
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
from abc import ABC, abstractmethod
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
import uuid
|
||||
|
||||
import opuslib
|
||||
import opuslib_next
|
||||
from funasr import AutoModel
|
||||
from funasr.utils.postprocess_utils import rich_transcription_postprocess
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
# 捕获标准输出
|
||||
class CaptureOutput:
|
||||
def __enter__(self):
|
||||
self._output = io.StringIO()
|
||||
self._original_stdout = sys.stdout
|
||||
sys.stdout = self._output
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
sys.stdout = self._original_stdout
|
||||
self.output = self._output.getvalue()
|
||||
self._output.close()
|
||||
|
||||
# 将捕获到的内容通过 logger 输出
|
||||
if self.output:
|
||||
logger.bind(tag=TAG).info(self.output.strip())
|
||||
|
||||
class ASR(ABC):
|
||||
@abstractmethod
|
||||
def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
|
||||
|
|
@ -33,7 +51,7 @@ class FunASR(ASR):
|
|||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
with CaptureOutput():
|
||||
self.model = AutoModel(
|
||||
model=self.model_dir,
|
||||
vad_kwargs={"max_single_segment_time": 30000},
|
||||
|
|
@ -47,14 +65,14 @@ class FunASR(ASR):
|
|||
file_name = f"asr_{session_id}_{uuid.uuid4()}.wav"
|
||||
file_path = os.path.join(self.output_dir, file_name)
|
||||
|
||||
decoder = opuslib.Decoder(16000, 1) # 16kHz, 单声道
|
||||
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
|
||||
pcm_data = []
|
||||
|
||||
for opus_packet in opus_data:
|
||||
try:
|
||||
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
||||
pcm_data.append(pcm_frame)
|
||||
except opuslib.OpusError as e:
|
||||
except opuslib_next.OpusError as e:
|
||||
logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
|
||||
|
||||
with wave.open(file_path, "wb") as wf:
|
||||
|
|
|
|||
|
|
@ -19,6 +19,18 @@ class Dialogue:
|
|||
def put(self, message: Message):
|
||||
self.dialogue.append(message)
|
||||
|
||||
def get_llm_dialogue_with_memory(self, memory_data:str) -> List[Dict[str, str]]:
|
||||
dialogue = []
|
||||
|
||||
for m in self.dialogue:
|
||||
if m.role == "system" and len(memory_data.strip()) > 0:
|
||||
content = f"{m.content}\n\n你还保留着一些长期的记忆,这有助于让你的对话更加丰富和连贯:\n<start>{memory_data}</end>"
|
||||
else:
|
||||
content = m.content
|
||||
dialogue.append({"role": m.role, "content": content})
|
||||
|
||||
return dialogue
|
||||
|
||||
def get_llm_dialogue(self) -> List[Dict[str, str]]:
|
||||
dialogue = []
|
||||
for m in self.dialogue:
|
||||
|
|
|
|||
49
core/utils/embedding.py
Normal file
49
core/utils/embedding.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
from abc import ABC, abstractmethod
|
||||
import os
|
||||
from config.logger import setup_logging
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class EMBD(ABC):
|
||||
@abstractmethod
|
||||
def encode(self, conn, data):
|
||||
pass
|
||||
|
||||
class SentenceEMBD(EMBD):
|
||||
def __init__(self, config: dict,):
|
||||
from sentence_transformers import SentenceTransformer,export_optimized_onnx_model
|
||||
self.model_dir = config.get("model_dir")
|
||||
self.device = config.get("device","cpu")
|
||||
# model_dir = "jinaai/jina-embeddings-v2-base-zh"
|
||||
if not os.path.exists(os.path.join(self.model_dir,"onnx","model_O3.onnx")):
|
||||
self.model = SentenceTransformer(
|
||||
self.model_dir,
|
||||
backend="onnx",
|
||||
device=self.device,
|
||||
model_kwargs={"file_name": "model.onnx"}
|
||||
)
|
||||
export_optimized_onnx_model(self.model, "O3", self.model_dir)
|
||||
logger.bind(tag=TAG).info(f"优化模型成功: {self.model_dir}")
|
||||
|
||||
self.model = SentenceTransformer(
|
||||
self.model_dir,
|
||||
backend="onnx",
|
||||
model_kwargs={"file_name": "onnx/model_O3.onnx"},
|
||||
device=self.device,
|
||||
)
|
||||
logger.bind(tag=TAG).info(f"加载模型成功: {self.model_dir}")
|
||||
|
||||
def encode(self, data):
|
||||
return self.model.encode(data)
|
||||
|
||||
def create_instance(class_name: str, *args, **kwargs) -> EMBD:
|
||||
"""工厂方法创建embedding实例"""
|
||||
|
||||
model_map = {
|
||||
"SentenceTransformer": SentenceEMBD,
|
||||
}
|
||||
|
||||
if cls := model_map.get(class_name):
|
||||
return cls(*args, **kwargs)
|
||||
raise ValueError(f"不支持的embedding类型: {class_name}")
|
||||
492
core/utils/llm_memory.py
Normal file
492
core/utils/llm_memory.py
Normal file
|
|
@ -0,0 +1,492 @@
|
|||
import hashlib
|
||||
import threading
|
||||
import json
|
||||
import os
|
||||
from collections import deque
|
||||
import uuid
|
||||
|
||||
from numpy.linalg import norm
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import numpy as np
|
||||
from datetime import datetime
|
||||
from config.logger import setup_logging
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
# Cosine similarity function
|
||||
cos_sim = lambda a, b: (a @ b.T) / (norm(a) * norm(b))
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
class IntentRecognizer:
|
||||
intent_embeddings_cache = {}
|
||||
cache_lock = threading.Lock()
|
||||
def __init__(self, embedding_model):
|
||||
self.embedding_model = embedding_model
|
||||
# 存储注册的意图和相似度阈值以及对应的回调函数
|
||||
self.intent_callbacks = []
|
||||
|
||||
def register_intent(self, intent_phrases, callback_function, similarity_threshold=0.7):
|
||||
"""
|
||||
注册一个意图
|
||||
:param intent_phrases: 意图相关的短语列表
|
||||
:param callback_function: 对应的回调函数
|
||||
:param similarity_threshold: 意图与查询的相似度阈值,默认为0.7
|
||||
"""
|
||||
with self.cache_lock:
|
||||
for phrase in intent_phrases:
|
||||
# 如果该短语的嵌入已经缓存,则直接使用缓存
|
||||
if phrase not in IntentRecognizer.intent_embeddings_cache:
|
||||
# 计算嵌入并缓存
|
||||
intent_embedding = self.embedding_model.encode([phrase])[0]
|
||||
IntentRecognizer.intent_embeddings_cache[phrase] = intent_embedding
|
||||
else:
|
||||
# 使用缓存的嵌入
|
||||
intent_embedding = IntentRecognizer.intent_embeddings_cache[phrase]
|
||||
|
||||
# 存储每个意图短语及其对应的回调函数和相似度阈值
|
||||
self.intent_callbacks.append({
|
||||
"phrase": phrase,
|
||||
"embedding": intent_embedding,
|
||||
"callback": callback_function,
|
||||
"threshold": similarity_threshold
|
||||
})
|
||||
|
||||
def handle_query(self, query: str, *args, **kwargs):
|
||||
"""
|
||||
处理用户查询并进行意图识别,调用匹配的回调函数
|
||||
:param query: 用户查询
|
||||
:param args: 任意位置参数传递给回调函数
|
||||
:param kwargs: 任意关键字参数传递给回调函数
|
||||
:return: 回调函数的返回值
|
||||
"""
|
||||
query = query.strip()
|
||||
# 计算用户查询的嵌入表示
|
||||
query_embedding = self.embedding_model.encode([query])[0]
|
||||
|
||||
best_match = None
|
||||
highest_similarity = -1
|
||||
matched_callback = None
|
||||
|
||||
# 比较查询与注册的意图短语的相似度
|
||||
for intent in self.intent_callbacks:
|
||||
similarity = np.dot(query_embedding, intent["embedding"]) / (np.linalg.norm(query_embedding) * np.linalg.norm(intent["embedding"]))
|
||||
if similarity > highest_similarity and similarity >= intent["threshold"]:
|
||||
highest_similarity = similarity
|
||||
best_match = intent["phrase"]
|
||||
matched_callback = intent["callback"]
|
||||
|
||||
if best_match and matched_callback:
|
||||
# 调用与匹配意图对应的回调函数,传递位置参数和关键字参数
|
||||
logger.info(f"{query}\t意图识别结果:{best_match}\tfunc:{matched_callback}\t (相似度: {highest_similarity:.2f})")
|
||||
return matched_callback(query,*args, **kwargs)
|
||||
logger.info(f"{query}\t未识别到意图")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class MemoryManager:
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super(MemoryManager, cls).__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
llm,
|
||||
embd,
|
||||
summary_prompt: str = "请总结下面的聊天内容,必须在{content_len}字数以内,必须包含聊天的完整细节:\n\n{content}",
|
||||
max_memory_length: int = 1000,
|
||||
summary_length: int = 1000,
|
||||
max_summary_length: int = 2000,
|
||||
|
||||
memory_dir='memory_data'
|
||||
):
|
||||
"""
|
||||
初始化记忆管理类
|
||||
:param embedding_model: 用于生成文本嵌入的模型
|
||||
:param max_memory_length: 最大记忆总字符长度
|
||||
:param summary_length: 每次生成的总结的长度
|
||||
:param memory_file: 保存记忆数据的文件路径
|
||||
"""
|
||||
logger.info(f"初始化记忆管理器 max_memory_length:{max_memory_length} summary_length:{summary_length} max_summary_length:{max_summary_length}")
|
||||
self.max_memory_length = max_memory_length
|
||||
self.summary_length = summary_length
|
||||
self.max_summary_length = max_summary_length
|
||||
|
||||
self.memory_data = {} # 用字典管理每个用户的记忆
|
||||
self.lock = threading.Lock() # 锁对象,用于线程同步
|
||||
self.summary_prompt = summary_prompt
|
||||
self.llm = llm
|
||||
self.embedding_model = embd # 用于生成文本的嵌入
|
||||
|
||||
self.memory_dir = memory_dir
|
||||
if not os.path.exists(self.memory_dir):
|
||||
os.makedirs(self.memory_dir,exist_ok=True) # 创建目录
|
||||
|
||||
# 确保目录具有读写权限
|
||||
if not os.access(self.memory_dir, os.W_OK):
|
||||
try:
|
||||
os.chmod(self.memory_dir, 0o700) # 设置读写权限
|
||||
logger.info(f"已为目录 {self.memory_dir} 设置读写权限")
|
||||
except Exception as e:
|
||||
logger.warning(f"无法修改 {self.memory_dir} 的权限: {e}")
|
||||
raise PermissionError(f"没有足够权限访问目录: {self.memory_dir}")
|
||||
# 加载已有记忆或初始化新的记忆
|
||||
self.load_memory()
|
||||
|
||||
# ThreadPoolExecutor for async tasks
|
||||
self.executor = ThreadPoolExecutor()
|
||||
|
||||
|
||||
self.intent_recognizer = IntentRecognizer(self.embedding_model)
|
||||
self.intent_recognizer.register_intent(
|
||||
["回忆对话", "回忆上次讲的", "请回忆","有什么记忆","刚才讲了什么","上次讲了什么"],
|
||||
self._recall_last_conversation,
|
||||
similarity_threshold=0.7
|
||||
)
|
||||
self.intent_recognizer.register_intent(
|
||||
["删除我的记忆","删除所有记忆"],
|
||||
self._del_all,
|
||||
similarity_threshold=0.9
|
||||
)
|
||||
|
||||
def _recall_last_conversation(self,query: str, token_name: str)->str:
|
||||
"""
|
||||
回忆上次的对话
|
||||
:param token_name: 用户唯一标识符
|
||||
:param query: 用户查询
|
||||
:return: 上次的对话内容
|
||||
"""
|
||||
user_memory = self.search_memory(token_name, query, top_k=5)
|
||||
|
||||
|
||||
if len(user_memory) == 0:
|
||||
|
||||
user_memory = self.memory_data.get(token_name, {'memory':[]})
|
||||
|
||||
user_memory = list(user_memory['memory'])
|
||||
user_memory = user_memory[-10:]
|
||||
|
||||
|
||||
|
||||
output = "\n".join([msg['content'] for msg in user_memory])
|
||||
|
||||
|
||||
return f"{query}\n\n我们上次聊到了:\n\n{output}"
|
||||
|
||||
def _generate_summary(self, chat_paragraph: list):
|
||||
"""
|
||||
生成聊天内容的总结(可以根据具体要求定制总结逻辑)
|
||||
:param chat_content: 聊天内容
|
||||
:return: 总结的字符串
|
||||
"""
|
||||
if self.llm is None:
|
||||
return "".join([msg['content'] for msg in chat_paragraph])[:self.summary_length]
|
||||
|
||||
response_message = []
|
||||
try:
|
||||
llm_responses = self.llm.response(
|
||||
str(uuid.uuid4()),
|
||||
[
|
||||
{
|
||||
"role": "user",
|
||||
"content": self.summary_prompt.format(content=json.dumps(chat_paragraph),content_len=self.summary_length)
|
||||
}
|
||||
]
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"LLM 处理出错 {query}: {e}")
|
||||
return None
|
||||
|
||||
for content in llm_responses:
|
||||
response_message.append(content)
|
||||
return "".join(response_message)
|
||||
|
||||
def _forget_old_memory(self, token_name: str):
|
||||
"""
|
||||
超过最大记忆总长度时,删除不重要的记忆
|
||||
:param token_name: 用户唯一标识符
|
||||
"""
|
||||
user_memory = self.memory_data.get(token_name, {'memory': deque(), 'total_length': 0})
|
||||
|
||||
while user_memory['total_length'] > self.max_memory_length and user_memory['memory']:
|
||||
# 删除最旧的聊天内容和对应的嵌入
|
||||
oldest_message = user_memory['memory'].popleft()
|
||||
oldest_embedding = user_memory['embeddings'].popleft() # Remove corresponding embedding
|
||||
user_memory['total_length'] -= len(oldest_message['content'])
|
||||
|
||||
|
||||
|
||||
def _update_summary(self, token_name: str, chat_paragraph: list[dict]):
|
||||
"""
|
||||
更新记忆总结,合并每个聊天段落的内容并生成摘要
|
||||
:param token_name: 用户唯一标识符
|
||||
"""
|
||||
|
||||
if len(chat_paragraph) == 0:
|
||||
return
|
||||
|
||||
summary = self._generate_summary(chat_paragraph)
|
||||
|
||||
if summary is None or len(summary.strip()) == 0:
|
||||
return
|
||||
|
||||
self.memory_data[token_name].setdefault('memory_summary', []).append(summary)
|
||||
|
||||
# 生成并保存摘要的嵌入
|
||||
summary_embedding = self.embedding_model.encode([summary])[0]
|
||||
self.memory_data[token_name].setdefault('summary_embeddings', []).append(summary_embedding)
|
||||
|
||||
def _combine_summary(self, token_name: str):
|
||||
"""
|
||||
将所有的记忆总结合并为一个
|
||||
:param token_name: 用户唯一标识符
|
||||
"""
|
||||
|
||||
user_memory = self.memory_data.get(token_name, {'memory_summary': []})
|
||||
|
||||
# 如果没有超过最大总结长度,直接返回
|
||||
old_summary = "".join(user_memory['memory_summary'])
|
||||
if len(user_memory) == 0 or len(old_summary) < self.max_memory_length:
|
||||
logger.debug("不需要合并,总结长度:", len(old_summary))
|
||||
return
|
||||
logger.debug("合并前的总结长度:", len(old_summary))
|
||||
summary = self._generate_summary(user_memory['memory_summary'])
|
||||
logger.debug("合并后的总结长度:", len(summary))
|
||||
self.memory_data[token_name]['memory_summary'] = [summary]
|
||||
|
||||
# 生成并保存摘要的嵌入
|
||||
summary_embedding = self.embedding_model.encode([summary])[0]
|
||||
self.memory_data[token_name]['summary_embeddings'] = [summary_embedding]
|
||||
|
||||
def _del_all(self, query:str, token_name: str)->str:
|
||||
"""
|
||||
删除所有记忆
|
||||
:param token_name: 用户唯一标识符
|
||||
"""
|
||||
self.memory_data[token_name] = {'memory': deque(), 'total_length': 0, 'memory_summary': [], 'summary_embeddings': [], 'embeddings': deque()}
|
||||
self.save_memory()
|
||||
return f"你必须{query}\n\n你必须回答同意删除所有记忆"
|
||||
|
||||
async def add_chat_paragraph(self, token_name: str, chat_paragraph: list[dict]):
|
||||
"""
|
||||
添加一段聊天内容到记忆中
|
||||
:param token_name: 用户唯一标识符
|
||||
:param chat_paragraph: 聊天段落,包含多条聊天记录
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(self.executor, self._add_chat_paragraph, token_name, chat_paragraph)
|
||||
|
||||
def _add_chat_paragraph(self, token_name: str, chat_paragraph: list[dict]):
|
||||
with self.lock: # 使用锁保证线程安全
|
||||
if token_name not in self.memory_data:
|
||||
self.memory_data[token_name] = {'memory': deque(), 'total_length': 0, 'memory_summary': [], 'summary_embeddings': [], 'embeddings': deque()}
|
||||
|
||||
user_memory = self.memory_data[token_name]
|
||||
new_embeddings = []
|
||||
|
||||
for message in chat_paragraph:
|
||||
role = message['role']
|
||||
content = message['content']
|
||||
|
||||
chat_hash = hashlib.md5(content.encode()).hexdigest()
|
||||
|
||||
user_memory['memory'].append({"role": role, "content": content, "hash": chat_hash, "datatime": "{:%Y-%m-%d %H:%M:%S}".format(datetime.now())})
|
||||
user_memory['total_length'] += len(content)
|
||||
|
||||
# 生成嵌入
|
||||
embedding = self.embedding_model.encode([content])[0] # 使用嵌入模型生成嵌入
|
||||
user_memory['embeddings'].append(embedding)
|
||||
|
||||
# 更新记忆总结
|
||||
self._update_summary(token_name, chat_paragraph)
|
||||
|
||||
# 如果记忆超出了限制,删除不重要的内容
|
||||
self._forget_old_memory(token_name)
|
||||
|
||||
# 合并压缩记忆总结
|
||||
self._combine_summary(token_name)
|
||||
|
||||
# 保存记忆到文件
|
||||
self.save_memory()
|
||||
|
||||
def handle_user_scene(self,token_name:str, query: str) -> str:
|
||||
"""
|
||||
解析用户查询
|
||||
:param query: 用户查询
|
||||
:return: 解析后的查询
|
||||
"""
|
||||
query = query.strip()
|
||||
if len(query) == 0:
|
||||
return query
|
||||
|
||||
result = self.intent_recognizer.handle_query(query, token_name)
|
||||
if result is None:
|
||||
return query
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_memory_summary(self, token_name: str) -> str:
|
||||
"""
|
||||
获取当前用户的记忆总结
|
||||
:param token_name: 用户唯一标识符
|
||||
:return: 当前的总结
|
||||
"""
|
||||
user_memory = self.memory_data.get(token_name, {'memory_summary': []})
|
||||
return "\n\n".join(user_memory['memory_summary'])
|
||||
|
||||
def get_full_memory(self, token_name: str) -> list[str]:
|
||||
"""
|
||||
获取当前用户的完整记忆内容
|
||||
:param token_name: 用户唯一标识符
|
||||
:return: 当前的所有记忆内容
|
||||
"""
|
||||
user_memory = self.memory_data.get(token_name, {'memory': []})
|
||||
return [msg['content'] for msg in user_memory['memory']]
|
||||
|
||||
def search_memory(self, token_name: str, query: str, top_k: int = 5, threshold: float = 0.5):
|
||||
"""
|
||||
使用嵌入进行记忆查询
|
||||
:param token_name: 用户唯一标识符
|
||||
:param query: 查询内容
|
||||
:param top_k: 返回最相似的记忆条数
|
||||
:param threshold: 相似度阈值,低于此阈值的结果将被忽略
|
||||
:return: 最相似的记忆条目
|
||||
"""
|
||||
user_memory = self.memory_data.get(token_name, {'embeddings': []})
|
||||
if not user_memory['embeddings']:
|
||||
return []
|
||||
|
||||
# 生成查询的嵌入
|
||||
query_embedding = self.embedding_model.encode([query])[0]
|
||||
|
||||
# 计算查询与记忆中每条消息的相似度
|
||||
similarities = [cos_sim(query_embedding, embedding) for embedding in user_memory['embeddings']]
|
||||
|
||||
# 获取最相似的记忆条目,过滤相似度低于阈值的结果
|
||||
filtered_indices = [i for i, sim in enumerate(similarities) if sim >= threshold]
|
||||
top_indices = sorted(filtered_indices, key=lambda i: similarities[i], reverse=True)[:top_k]
|
||||
similar_memory = [user_memory['memory'][i] for i in top_indices]
|
||||
|
||||
return similar_memory
|
||||
|
||||
def search_memory_summary(self, token_name: str, query: str, top_k: int = 5, threshold: float = 0.5):
|
||||
"""
|
||||
使用嵌入进行记忆总结查询
|
||||
:param token_name: 用户唯一标识符
|
||||
:param query: 查询内容
|
||||
:param top_k: 返回最相似的记忆条数
|
||||
:param threshold: 相似度阈值,低于此阈值的结果将被忽略
|
||||
:return: 最相似的记忆总结条目
|
||||
"""
|
||||
user_memory = self.memory_data.get(token_name, {'memory_summary': [], 'summary_embeddings': []})
|
||||
if not user_memory['summary_embeddings']:
|
||||
return []
|
||||
|
||||
# 生成查询的嵌入
|
||||
query_embedding = self.embedding_model.encode([query])[0]
|
||||
|
||||
# 计算查询与记忆总结的相似度
|
||||
similarities = [cos_sim(query_embedding, embedding) for embedding in user_memory['summary_embeddings']]
|
||||
|
||||
# 获取最相似的记忆总结条目,过滤相似度低于阈值的结果
|
||||
filtered_indices = [i for i, sim in enumerate(similarities) if sim >= threshold]
|
||||
top_indices = sorted(filtered_indices, key=lambda i: similarities[i], reverse=True)[:top_k]
|
||||
similar_summary = [user_memory['memory_summary'][i] for i in top_indices]
|
||||
|
||||
return similar_summary
|
||||
def save_memory(self):
|
||||
"""
|
||||
将记忆保存到本地文件,每个文件以token_name作为文件名
|
||||
"""
|
||||
try:
|
||||
for token_name, user_data in self.memory_data.items():
|
||||
memory_data_serializable = {
|
||||
'memory': list(user_data['memory']),
|
||||
'total_length': user_data['total_length'],
|
||||
'memory_summary': user_data['memory_summary'],
|
||||
'summary_embeddings': [embedding.tolist() for embedding in user_data['summary_embeddings']],
|
||||
'embeddings': [embedding.tolist() for embedding in user_data['embeddings']]
|
||||
}
|
||||
|
||||
file_path = os.path.join(self.memory_dir, f"{token_name}.json")
|
||||
with open(file_path, 'w', encoding='utf-8') as file:
|
||||
json.dump(memory_data_serializable, file, ensure_ascii=False, indent=4)
|
||||
logger.info(f"记忆已保存至 {file_path}")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"保存记忆时出错: {e}")
|
||||
|
||||
def load_memory(self):
|
||||
"""
|
||||
从本地文件加载记忆数据
|
||||
"""
|
||||
try:
|
||||
self.memory_data = {}
|
||||
|
||||
for file_name in os.listdir(self.memory_dir):
|
||||
if file_name.endswith('.json'):
|
||||
token_name = file_name[:-5] # 去掉 .json 后缀
|
||||
file_path = os.path.join(self.memory_dir, file_name)
|
||||
|
||||
with open(file_path, 'r', encoding='utf-8') as file:
|
||||
try:
|
||||
memory_data = json.load(file)
|
||||
except Exception as e:
|
||||
logger.warning(f"加载记忆{file_path}时出错: {e}")
|
||||
continue
|
||||
|
||||
self.memory_data[token_name] = {
|
||||
'memory': deque(memory_data['memory']),
|
||||
'total_length': memory_data['total_length'],
|
||||
'memory_summary': memory_data['memory_summary'],
|
||||
'summary_embeddings': [np.array(embedding) for embedding in memory_data['summary_embeddings']],
|
||||
'embeddings': deque([np.array(embedding) for embedding in memory_data['embeddings']])
|
||||
}
|
||||
logger.info(f"记忆已从 {file_path} 加载")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"加载记忆时出错: {e}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from sentence_transformers import SentenceTransformer
|
||||
# 示例使用
|
||||
embedding_model = SentenceTransformer('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True, device="cpu")
|
||||
memory_manager = MemoryManager(llm=None, embd=embedding_model, max_memory_length=100)
|
||||
|
||||
# 模拟两段对话
|
||||
chat_paragraph1 = [
|
||||
{"role": "user", "content": "吹到了你的发。😔"},
|
||||
{"role": "assistant", "content": "发丝轻拂,独怜此际,梦断谁家?😔"}
|
||||
]
|
||||
|
||||
chat_paragraph2 = [
|
||||
{"role": "user", "content": "今天天气。😔"},
|
||||
{"role": "assistant", "content": "晴天?😔"}
|
||||
]
|
||||
|
||||
# 添加第一段聊天
|
||||
asyncio.run(memory_manager.add_chat_paragraph("user1", chat_paragraph1))
|
||||
|
||||
# 添加第二段聊天
|
||||
asyncio.run(memory_manager.add_chat_paragraph("user1", chat_paragraph2))
|
||||
|
||||
# 使用嵌入进行记忆查询
|
||||
query = "今天天气?"
|
||||
similar_memory = memory_manager.search_memory("user1", query, threshold=0.5)
|
||||
print("最相似的记忆内容:", [msg['content'] for msg in similar_memory])
|
||||
|
||||
# 使用嵌入进行记忆总结查询
|
||||
similar_summary = memory_manager.search_memory_summary("user1", query, threshold=0.5)
|
||||
print("最相似的记忆总结:", similar_summary)
|
||||
|
|
@ -35,7 +35,9 @@ def write_json_file(file_path, data):
|
|||
|
||||
|
||||
def is_segment(tokens):
|
||||
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":"):
|
||||
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":") and len(tokens) > 5:
|
||||
return True
|
||||
elif tokens[-1] in ( ".", "?", "。", "?", "!", "!", ";", ";", ):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from config.logger import setup_logging
|
||||
import opuslib
|
||||
import opuslib_next
|
||||
import time
|
||||
import numpy as np
|
||||
import torch
|
||||
|
|
@ -24,7 +24,7 @@ class SileroVAD(VAD):
|
|||
force_reload=False)
|
||||
(get_speech_timestamps, _, _, _, _) = self.utils
|
||||
|
||||
self.decoder = opuslib.Decoder(16000, 1)
|
||||
self.decoder = opuslib_next.Decoder(16000, 1)
|
||||
self.vad_threshold = config.get("threshold")
|
||||
self.silence_threshold_ms = config.get("min_silence_duration_ms")
|
||||
|
||||
|
|
@ -59,7 +59,7 @@ class SileroVAD(VAD):
|
|||
conn.client_have_voice_last_time = time.time() * 1000
|
||||
|
||||
return client_have_voice
|
||||
except opuslib.OpusError as e:
|
||||
except opuslib_next.OpusError as e:
|
||||
logger.bind(tag=TAG).info(f"解码错误: {e}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import websockets
|
|||
from config.logger import setup_logging
|
||||
from core.connection import ConnectionHandler
|
||||
from core.utils.util import get_local_ip
|
||||
from core.utils import asr, vad, llm, tts
|
||||
from core.utils import asr, vad, llm, tts, embedding
|
||||
|
||||
TAG = __name__
|
||||
|
||||
|
|
@ -11,7 +11,7 @@ class WebSocketServer:
|
|||
def __init__(self, config: dict):
|
||||
self.config = config
|
||||
self.logger = setup_logging()
|
||||
self._vad, self._asr, self._llm, self._tts = self._create_processing_instances()
|
||||
self._vad, self._asr, self._llm, self._tts, self._embd = self._create_processing_instances()
|
||||
|
||||
def _create_processing_instances(self):
|
||||
"""创建处理模块实例"""
|
||||
|
|
@ -39,6 +39,10 @@ class WebSocketServer:
|
|||
self.config["TTS"][self.config["selected_module"]["TTS"]]["type"],
|
||||
self.config["TTS"][self.config["selected_module"]["TTS"]],
|
||||
self.config["delete_audio"]
|
||||
),
|
||||
embedding.create_instance(
|
||||
self.config["selected_module"]["EMBD"],
|
||||
self.config["EMBD"][self.config["selected_module"]["EMBD"]]
|
||||
)
|
||||
)
|
||||
|
||||
|
|
@ -58,5 +62,5 @@ class WebSocketServer:
|
|||
|
||||
async def _handle_connection(self, websocket):
|
||||
"""处理新连接,每次创建独立的ConnectionHandler"""
|
||||
handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts)
|
||||
handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._embd)
|
||||
await handler.handle_connection(websocket)
|
||||
|
|
|
|||
|
|
@ -6,7 +6,12 @@ services:
|
|||
#security_opt:
|
||||
# - seccomp:unconfined
|
||||
ports:
|
||||
- "8000:8000"
|
||||
- "8002:8002"
|
||||
- "8000:8000" # ws服务端
|
||||
- "8002:8002" # 管理后台
|
||||
volumes:
|
||||
- ./.config.yaml:/opt/xiaozhi-esp32-server/config.yaml
|
||||
# 配置文件 记得创建文件夹
|
||||
- ./data:/opt/xiaozhi-esp32-server/data
|
||||
# 模型文件 //可以挂载本地下载好的模型
|
||||
#- ./models:/opt/xiaozhi-esp32-server/models
|
||||
# 临时文件 //可以看log和音频文件 记得创建文件夹
|
||||
#- ./tmp:/opt/xiaozhi-esp32-server/tmp
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
services:
|
||||
xiaozhi-esp32-server:
|
||||
image: ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
||||
image: ghcr.io/kalicyh/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
|
||||
- ./data:/app/data
|
||||
|
|
@ -105,11 +105,17 @@ docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconf
|
|||
-p 8000:8000 \
|
||||
-p 8002:8002 \
|
||||
-v ./:/app \
|
||||
ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest
|
||||
kalicyh/poetry:v3.10_xiaozhi
|
||||
```
|
||||
|
||||
然后就和正常开发一样了
|
||||
|
||||
进入`bash`
|
||||
|
||||
```sh
|
||||
docker exec -it xiaozhi-env /bin/bash
|
||||
```
|
||||
|
||||
## 3.安装依赖
|
||||
|
||||
在刚刚的打开的终端运行
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
|
||||
# 本地源码运行
|
||||
|
||||
## 1.安装基础环境
|
||||
|
|
|
|||
13
docs/Embe.md
Normal file
13
docs/Embe.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# mac
|
||||
|
||||
docker需要开8g才能运行成功
|
||||
|
||||
后续设备对话又爆内存
|
||||
|
||||
```sh
|
||||
brew install git-lfs
|
||||
cd models
|
||||
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/jinaai/jina-embeddings-v2-base-zh
|
||||
cd jina-embeddings-v2-base-zh
|
||||
git lfs pull
|
||||
```
|
||||
File diff suppressed because one or more lines are too long
47
manager/static/webui/assets/index-DF7ROAy9.js
Normal file
47
manager/static/webui/assets/index-DF7ROAy9.js
Normal file
File diff suppressed because one or more lines are too long
1
manager/static/webui/assets/index-D_oCZVZF.css
Normal file
1
manager/static/webui/assets/index-D_oCZVZF.css
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
BIN
manager/static/webui/favicon.ico
Normal file
BIN
manager/static/webui/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
|
|
@ -2,7 +2,7 @@
|
|||
<html lang="en" style="height: 100%;">
|
||||
<head>
|
||||
<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"/>
|
||||
<title>智控台</title>
|
||||
<style>
|
||||
|
|
@ -13,13 +13,14 @@
|
|||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#app {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
<script type="module" crossorigin src="/assets/index-CvO82KVk.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-_IjUUKjO.css">
|
||||
<script type="module" crossorigin src="/assets/index-DF7ROAy9.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-D_oCZVZF.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
|
|
|||
1580
poetry.lock
generated
1580
poetry.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -11,7 +11,6 @@ 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"
|
||||
|
|
@ -26,12 +25,10 @@ ormsgpack = "1.7.0"
|
|||
ruamel-yaml = "0.18.10"
|
||||
setuptools = "^75.8.0"
|
||||
loguru = "^0.7.3"
|
||||
opuslib-next = "^1.1.2"
|
||||
sentence-transformers = {version = "3.4.1", extras = ["onnx"]}
|
||||
|
||||
|
||||
[[tool.poetry.source]]
|
||||
name = "mirrors"
|
||||
url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
|
||||
priority = "primary"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ pyyml==0.0.2
|
|||
torch==2.2.2
|
||||
silero_vad==5.1.2
|
||||
websockets==14.2
|
||||
opuslib==3.0.1
|
||||
opuslib_next==1.1.2
|
||||
numpy==1.26.4
|
||||
pydub==0.25.1
|
||||
funasr==1.2.3
|
||||
|
|
@ -15,4 +15,5 @@ aiohttp==3.9.3
|
|||
aiohttp_cors==0.7.0
|
||||
ormsgpack==1.7.0
|
||||
ruamel.yaml==0.18.10
|
||||
sentence-transformers[onnx]==3.4.1
|
||||
loguru==0.7.3
|
||||
Loading…
Reference in a new issue