update:pip转成poetry启动

This commit is contained in:
hrz 2025-03-03 21:40:30 +08:00
parent a05bc90ce8
commit d181b837f4
7 changed files with 61 additions and 171 deletions

28
app.py
View file

@ -1,10 +1,7 @@
import asyncio import asyncio
from config.logger import setup_logging
from config.settings import load_config, check_config_file from config.settings import load_config, check_config_file
from core.websocket_server import WebSocketServer from core.websocket_server import WebSocketServer
from manager.http_server import WebUI from core.utils.util import check_ffmpeg_installed
from aiohttp import web
from core.utils.util import get_local_ip, check_ffmpeg_installed
TAG = __name__ TAG = __name__
@ -12,38 +9,17 @@ TAG = __name__
async def main(): async def main():
check_config_file() check_config_file()
check_ffmpeg_installed() check_ffmpeg_installed()
logger = setup_logging()
config = load_config() config = load_config()
# 启动 WebSocket 服务器 # 启动 WebSocket 服务器
ws_server = WebSocketServer(config) ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start()) ws_task = asyncio.create_task(ws_server.start())
# 启动 WebUI 服务器
webui_runner = None
if config['manager'].get('enabled', False):
server_config = config["manager"]
host = server_config["ip"]
port = server_config["port"]
try:
webui = WebUI()
runner = web.AppRunner(webui.app)
await runner.setup()
site = web.TCPSite(runner, host, port)
await site.start()
webui_runner = runner
local_ip = get_local_ip()
logger.bind(tag=TAG).info(f"WebUI server is running at http://{local_ip}:{port}")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to start WebUI server: {e}")
try: try:
# 等待 WebSocket 服务器运行 # 等待 WebSocket 服务器运行
await ws_task await ws_task
finally: finally:
# 清理 WebUI 服务器 ws_task.cancel()
if webui_runner:
await webui_runner.cleanup()
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -5,8 +5,7 @@ from config.logger import setup_logging
from typing import Dict, Any, Optional 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 from core.utils import llm, tts
from manager.api.user_manager import UserManager
from core.utils.lock_manager import FileLockManager from core.utils.lock_manager import FileLockManager
TAG = __name__ TAG = __name__
@ -19,7 +18,6 @@ class PrivateConfig:
self.logger = setup_logging() self.logger = setup_logging()
self.private_config = {} self.private_config = {}
self.auth_code_gen = auth_code_gen self.auth_code_gen = auth_code_gen
self.user_manager = UserManager()
self.lock_manager = FileLockManager() self.lock_manager = FileLockManager()
async def load_or_create(self): async def load_or_create(self):
@ -238,94 +236,6 @@ class PrivateConfig:
""" """
return self.private_config.get('auth_code', '') 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.bind(tag=TAG).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.bind(tag=TAG).error(f"Device {self.device_id} not found")
return False
# 删除认证码
auth_code = all_configs[self.device_id].get('auth_code')
self.logger.bind(tag=TAG).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.bind(tag=TAG).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.bind(tag=TAG).error(f"Error unbinding user: {e}")
return False
def get_owner(self) -> Optional[str]: def get_owner(self) -> Optional[str]:
"""获取设备当前所有者""" """获取设备当前所有者"""
return self.private_config.get('owner') return self.private_config.get('owner')

View file

@ -199,7 +199,8 @@ conda install ffmpeg -y
# 继续使用conda环境,进入到你的项目目录,执行以下命令 # 继续使用conda环境,进入到你的项目目录,执行以下命令
conda activate xiaozhi-esp32-server conda activate xiaozhi-esp32-server
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip install -r requirements.txt pip install poetry
poetry install --no-root
``` ```
## 3.下载语音识别模型文件 ## 3.下载语音识别模型文件
@ -216,14 +217,22 @@ pip install -r requirements.txt
## 5.运行项目 ## 5.运行项目
如果您想启动8000端口,接收esp32的语音服务
``` ```
# 确保在本项目的根目录下执行 # 确保在本项目的根目录下执行
conda activate xiaozhi-esp32-server conda activate xiaozhi-esp32-server
python app.py poetry run python app.py
``` ```
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认) 这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
如果您想启动8002端口服务,启动管理后台
```
# 确保在本项目的根目录下执行
conda activate xiaozhi-esp32-server
poetry run uvicorn web.app:app --host 0.0.0.0 --port 8888 --reload
```
# 汇总 # 汇总
## 配置项目 ## 配置项目

50
poetry.lock generated
View file

@ -2587,33 +2587,37 @@ PyYAML = ">=5.1.0"
[[package]] [[package]]
name = "onnxruntime" name = "onnxruntime"
version = "1.20.1" version = "1.19.2"
description = "ONNX Runtime is a runtime accelerator for Machine Learning models" description = "ONNX Runtime is a runtime accelerator for Machine Learning models"
optional = false optional = false
python-versions = "*" python-versions = "*"
groups = ["main"] groups = ["main"]
files = [ files = [
{file = "onnxruntime-1.20.1-cp310-cp310-macosx_13_0_universal2.whl", hash = "sha256:e50ba5ff7fed4f7d9253a6baf801ca2883cc08491f9d32d78a80da57256a5439"}, {file = "onnxruntime-1.19.2-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:84fa57369c06cadd3c2a538ae2a26d76d583e7c34bdecd5769d71ca5c0fc750e"},
{file = "onnxruntime-1.20.1-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7b2908b50101a19e99c4d4e97ebb9905561daf61829403061c1adc1b588bc0de"}, {file = "onnxruntime-1.19.2-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bdc471a66df0c1cdef774accef69e9f2ca168c851ab5e4f2f3341512c7ef4666"},
{file = "onnxruntime-1.20.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d82daaec24045a2e87598b8ac2b417b1cce623244e80e663882e9fe1aae86410"}, {file = "onnxruntime-1.19.2-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e3a4ce906105d99ebbe817f536d50a91ed8a4d1592553f49b3c23c4be2560ae6"},
{file = "onnxruntime-1.20.1-cp310-cp310-win32.whl", hash = "sha256:4c4b251a725a3b8cf2aab284f7d940c26094ecd9d442f07dd81ab5470e99b83f"}, {file = "onnxruntime-1.19.2-cp310-cp310-win32.whl", hash = "sha256:4b3d723cc154c8ddeb9f6d0a8c0d6243774c6b5930847cc83170bfe4678fafb3"},
{file = "onnxruntime-1.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:d3b616bb53a77a9463707bb313637223380fc327f5064c9a782e8ec69c22e6a2"}, {file = "onnxruntime-1.19.2-cp310-cp310-win_amd64.whl", hash = "sha256:17ed7382d2c58d4b7354fb2b301ff30b9bf308a1c7eac9546449cd122d21cae5"},
{file = "onnxruntime-1.20.1-cp311-cp311-macosx_13_0_universal2.whl", hash = "sha256:06bfbf02ca9ab5f28946e0f912a562a5f005301d0c419283dc57b3ed7969bb7b"}, {file = "onnxruntime-1.19.2-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:d863e8acdc7232d705d49e41087e10b274c42f09e259016a46f32c34e06dc4fd"},
{file = "onnxruntime-1.20.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f6243e34d74423bdd1edf0ae9596dd61023b260f546ee17d701723915f06a9f7"}, {file = "onnxruntime-1.19.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c1dfe4f660a71b31caa81fc298a25f9612815215a47b286236e61d540350d7b6"},
{file = "onnxruntime-1.20.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5eec64c0269dcdb8d9a9a53dc4d64f87b9e0c19801d9321246a53b7eb5a7d1bc"}, {file = "onnxruntime-1.19.2-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a36511dc07c5c964b916697e42e366fa43c48cdb3d3503578d78cef30417cb84"},
{file = "onnxruntime-1.20.1-cp311-cp311-win32.whl", hash = "sha256:a19bc6e8c70e2485a1725b3d517a2319603acc14c1f1a017dda0afe6d4665b41"}, {file = "onnxruntime-1.19.2-cp311-cp311-win32.whl", hash = "sha256:50cbb8dc69d6befad4746a69760e5b00cc3ff0a59c6c3fb27f8afa20e2cab7e7"},
{file = "onnxruntime-1.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:8508887eb1c5f9537a4071768723ec7c30c28eb2518a00d0adcd32c89dea3221"}, {file = "onnxruntime-1.19.2-cp311-cp311-win_amd64.whl", hash = "sha256:1c3e5d415b78337fa0b1b75291e9ea9fb2a4c1f148eb5811e7212fed02cfffa8"},
{file = "onnxruntime-1.20.1-cp312-cp312-macosx_13_0_universal2.whl", hash = "sha256:22b0655e2bf4f2161d52706e31f517a0e54939dc393e92577df51808a7edc8c9"}, {file = "onnxruntime-1.19.2-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:68e7051bef9cfefcbb858d2d2646536829894d72a4130c24019219442b1dd2ed"},
{file = "onnxruntime-1.20.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f1f56e898815963d6dc4ee1c35fc6c36506466eff6d16f3cb9848cea4e8c8172"}, {file = "onnxruntime-1.19.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d2d366fbcc205ce68a8a3bde2185fd15c604d9645888703785b61ef174265168"},
{file = "onnxruntime-1.20.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bb71a814f66517a65628c9e4a2bb530a6edd2cd5d87ffa0af0f6f773a027d99e"}, {file = "onnxruntime-1.19.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:477b93df4db467e9cbf34051662a4b27c18e131fa1836e05974eae0d6e4cf29b"},
{file = "onnxruntime-1.20.1-cp312-cp312-win32.whl", hash = "sha256:bd386cc9ee5f686ee8a75ba74037750aca55183085bf1941da8efcfe12d5b120"}, {file = "onnxruntime-1.19.2-cp312-cp312-win32.whl", hash = "sha256:9a174073dc5608fad05f7cf7f320b52e8035e73d80b0a23c80f840e5a97c0147"},
{file = "onnxruntime-1.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:19c2d843eb074f385e8bbb753a40df780511061a63f9def1b216bf53860223fb"}, {file = "onnxruntime-1.19.2-cp312-cp312-win_amd64.whl", hash = "sha256:190103273ea4507638ffc31d66a980594b237874b65379e273125150eb044857"},
{file = "onnxruntime-1.20.1-cp313-cp313-macosx_13_0_universal2.whl", hash = "sha256:cc01437a32d0042b606f462245c8bbae269e5442797f6213e36ce61d5abdd8cc"}, {file = "onnxruntime-1.19.2-cp38-cp38-macosx_11_0_universal2.whl", hash = "sha256:636bc1d4cc051d40bc52e1f9da87fbb9c57d9d47164695dfb1c41646ea51ea66"},
{file = "onnxruntime-1.20.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fb44b08e017a648924dbe91b82d89b0c105b1adcfe31e90d1dc06b8677ad37be"}, {file = "onnxruntime-1.19.2-cp38-cp38-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5bd8b875757ea941cbcfe01582970cc299893d1b65bd56731e326a8333f638a3"},
{file = "onnxruntime-1.20.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bda6aebdf7917c1d811f21d41633df00c58aff2bef2f598f69289c1f1dabc4b3"}, {file = "onnxruntime-1.19.2-cp38-cp38-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b2046fc9560f97947bbc1acbe4c6d48585ef0f12742744307d3364b131ac5778"},
{file = "onnxruntime-1.20.1-cp313-cp313-win_amd64.whl", hash = "sha256:d30367df7e70f1d9fc5a6a68106f5961686d39b54d3221f760085524e8d38e16"}, {file = "onnxruntime-1.19.2-cp38-cp38-win32.whl", hash = "sha256:31c12840b1cde4ac1f7d27d540c44e13e34f2345cf3642762d2a3333621abb6a"},
{file = "onnxruntime-1.20.1-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c9158465745423b2b5d97ed25aa7740c7d38d2993ee2e5c3bfacb0c4145c49d8"}, {file = "onnxruntime-1.19.2-cp38-cp38-win_amd64.whl", hash = "sha256:016229660adea180e9a32ce218b95f8f84860a200f0f13b50070d7d90e92956c"},
{file = "onnxruntime-1.20.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0df6f2df83d61f46e842dbcde610ede27218947c33e994545a22333491e72a3b"}, {file = "onnxruntime-1.19.2-cp39-cp39-macosx_11_0_universal2.whl", hash = "sha256:006c8d326835c017a9e9f74c9c77ebb570a71174a1e89fe078b29a557d9c3848"},
{file = "onnxruntime-1.19.2-cp39-cp39-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:df2a94179a42d530b936f154615b54748239c2908ee44f0d722cb4df10670f68"},
{file = "onnxruntime-1.19.2-cp39-cp39-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fae4b4de45894b9ce7ae418c5484cbf0341db6813effec01bb2216091c52f7fb"},
{file = "onnxruntime-1.19.2-cp39-cp39-win32.whl", hash = "sha256:dc5430f473e8706fff837ae01323be9dcfddd3ea471c900a91fa7c9b807ec5d3"},
{file = "onnxruntime-1.19.2-cp39-cp39-win_amd64.whl", hash = "sha256:38475e29a95c5f6c62c2c603d69fc7d4c6ccbf4df602bd567b86ae1138881c49"},
] ]
[package.dependencies] [package.dependencies]
@ -4847,4 +4851,4 @@ propcache = ">=0.2.0"
[metadata] [metadata]
lock-version = "2.1" lock-version = "2.1"
python-versions = "^3.10" python-versions = "^3.10"
content-hash = "8d84fc9b99e77a1113aa10add776e845261d45305208e8498a452cf0f83c1957" content-hash = "5b41b8cbaed395b415b249f77ea1cff3337e55cac83feaf39b2c4d6a1aebce54"

View file

@ -34,6 +34,7 @@ bcrypt = "^4.2.1"
sqlalchemy = "^2.0.38" sqlalchemy = "^2.0.38"
pymysql = "^1.1.1" pymysql = "^1.1.1"
asyncpg = "^0.30.0" asyncpg = "^0.30.0"
onnxruntime = "1.19.2"
[build-system] [build-system]

View file

@ -1,19 +0,0 @@
pyyml==0.0.2
torch==2.2.2
silero_vad==5.1.2
websockets==14.2
opuslib_next==1.1.2
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
loguru==0.7.3
requests==2.32.3

View file

@ -1,12 +1,28 @@
# web/main.py import os
import sys
from contextlib import asynccontextmanager # 新增导入
current_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(current_dir)
sys.path.append(root_dir)
from fastapi import FastAPI, Depends from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from web.api.admin import admin from web.api.admin import admin
from web.api.auth import auth as auth_router from web.api.auth import auth as auth_router
from web.api.auth.dependencies import get_current_active_user from web.api.auth.dependencies import get_current_active_user
# 新增 lifespan 处理器
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时逻辑
from web.api.db import models, database
models.Base.metadata.create_all(bind=database.engine)
print("数据库表检查完成,如果不存在则已创建!")
yield # 这里之后是关闭时逻辑(如果需要可以添加)
app = FastAPI( app = FastAPI(
lifespan=lifespan, # 添加 lifespan 参数
title="App", title="App",
description="", description="",
summary="你好小智", summary="你好小智",
@ -42,10 +58,3 @@ async def read_users_me(current_user = Depends(get_current_active_user)):
# 挂载 React 静态文件 # 挂载 React 静态文件
# app.mount("/", StaticFiles(directory="dist", html=True), name="dist") # app.mount("/", StaticFiles(directory="dist", html=True), name="dist")
# 应用启动时检查并创建数据库表
@app.on_event("startup")
def on_startup():
from web.api.db import models
from web.api.db import database
models.Base.metadata.create_all(bind=database.engine)
print("数据库表检查完成,如果不存在则已创建!")