refactor: 将 opus 库加载逻辑提取到 config 目录下

This commit is contained in:
Yang-ZhiHang 2026-04-18 14:04:14 +08:00
parent 803da9a942
commit 5aa6dcc1e3
9 changed files with 376 additions and 385 deletions

1
.python-version Normal file
View file

@ -0,0 +1 @@
3.10

6
main.py Normal file
View file

@ -0,0 +1,6 @@
def main():
print("Hello from xiaozhi-esp32-server!")
if __name__ == "__main__":
main()

View file

@ -1,19 +1,21 @@
from utils.system_info import setup_opus
setup_opus()
# ruff: noqa: E402 # ruff: noqa: E402
import asyncio
import signal
import sys import sys
import uuid import uuid
import signal
import asyncio
from aioconsole import ainput from aioconsole import ainput
from config.settings import load_config
from config.logger import setup_logging from config.logger import setup_logging
from core.utils.util import get_local_ip, validate_mcp_endpoint from config.opus_loader import setup_opus
from config.settings import load_config
if not setup_opus():
raise RuntimeError("Opus 库加载失败,请确保已正确安装 Opus 并配置环境变量")
from core.http_server import SimpleHttpServer from core.http_server import SimpleHttpServer
from core.websocket_server import WebSocketServer
from core.utils.util import check_ffmpeg_installed
from core.utils.gc_manager import get_gc_manager from core.utils.gc_manager import get_gc_manager
from core.utils.util import check_ffmpeg_installed, get_local_ip, validate_mcp_endpoint
from core.websocket_server import WebSocketServer
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -55,14 +57,14 @@ async def main():
# auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证 # auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证
# 获取配置文件中的auth_key # 获取配置文件中的auth_key
auth_key = config["server"].get("auth_key", "") auth_key = config["server"].get("auth_key", "")
# 验证auth_key,无效则尝试使用manager-api.secret # 验证auth_key,无效则尝试使用manager-api.secret
if not auth_key or len(auth_key) == 0 or "你" in auth_key: if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = config.get("manager-api", {}).get("secret", "") auth_key = config.get("manager-api", {}).get("secret", "")
# 验证secret,无效则生成随机密钥 # 验证secret,无效则生成随机密钥
if not auth_key or len(auth_key) == 0 or "你" in auth_key: if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = str(uuid.uuid4().hex) auth_key = str(uuid.uuid4().hex)
config["server"]["auth_key"] = auth_key config["server"]["auth_key"] = auth_key
# 添加 stdin 监控任务 # 添加 stdin 监控任务

View file

@ -0,0 +1,341 @@
# 在导入 opuslib 之前处理 opus 动态库
import ctypes
import ctypes.util
import os
import platform
import sys
from enum import Enum
from pathlib import Path
from typing import cast
from config.logger import setup_logging
APP_DIR = str(Path(__file__).resolve().parent.parent)
logger = setup_logging()
class PLATFORM(Enum):
WINDOWS = "windows"
MACOS = "darwin"
LINUX = "linux"
class ARCH(Enum):
WINDOWS = {"arm": "x64", "intel": "x64"}
MACOS = {"arm": "arm64", "intel": "x64"}
LINUX = {"arm": "arm64", "intel": "x64"}
class LIB_PATH(Enum):
WINDOWS = "libs/win/x64"
MACOS = "libs/mac/{arch}"
LINUX = "libs/linux/{arch}"
class OPUS_INFO(Enum):
WINDOWS = {"name": "opus.dll", "system_name": ["opus"]}
MACOS = {"name": "libopus.dylib", "system_name": ["libopus.dylib"]}
LINUX = {"name": "libopus.so", "system_name": ["libopus.so.0", "libopus.so"]}
def _get_platform_dict() -> dict[PLATFORM, dict]:
"""获取平台映射字典"""
return {
PLATFORM.WINDOWS: {
"arch": ARCH.WINDOWS,
"lib_path": LIB_PATH.WINDOWS,
"lib_info": OPUS_INFO.WINDOWS,
"dir": "win",
},
PLATFORM.MACOS: {
"arch": ARCH.MACOS,
"lib_path": LIB_PATH.MACOS,
"lib_info": OPUS_INFO.MACOS,
"dir": "mac",
},
PLATFORM.LINUX: {
"arch": ARCH.LINUX,
"lib_path": LIB_PATH.LINUX,
"lib_info": OPUS_INFO.LINUX,
"dir": "linux",
},
}
def get_platform() -> PLATFORM:
"""获取当前平台"""
system = platform.system().lower()
if system in ("windows", "win32", "cygwin"):
return PLATFORM.WINDOWS
if system == "darwin":
return PLATFORM.MACOS
return PLATFORM.LINUX
def get_arch(system: PLATFORM) -> tuple[str, str]:
"""获取当前架构
Args:
system: 平台枚举值
Returns:
(原始架构字符串, 标准化架构名称)
"""
architecture = platform.machine().lower()
is_arm = "arm" in architecture or "aarch64" in architecture
platform_dict = _get_platform_dict()
arch_map = platform_dict[system]["arch"].value
arch_name = arch_map["arm" if is_arm else "intel"]
return architecture, arch_name
def get_lib_path(system: PLATFORM, arch_name: str) -> str:
"""根据平台架构获取 Opus 库文件路径"""
platform_dict = _get_platform_dict()
lib_path_value = platform_dict[system]["lib_path"].value
if isinstance(lib_path_value, str) and "{arch}" in lib_path_value:
return lib_path_value.format(arch=arch_name)
return lib_path_value
def get_lib_name(system: PLATFORM, local: bool = True) -> str | list[str]:
"""根据平台架构获取 Opus 库名称"""
key = "name" if local else "system_name"
platform_dict = _get_platform_dict()
return platform_dict[system]["lib_info"].value[key]
def get_system_info() -> tuple[PLATFORM, str]:
"""获取当前系统信息
Returns:
(平台, 架构名称)
"""
system = get_platform()
_, arch_name = get_arch(system)
logger.info(f"检测到平台架构: {system.value} {arch_name}")
return system, arch_name
def _build_lib_candidates(
base_libs_path: Path, system_dir: str, arch_name: str
) -> list[Path]:
"""构建库目录候选路径列表(按优先级排序)
Args:
base_libs_path: 基础 libs 目录路径
system_dir: 系统目录名称(如 win、mac、linux)
arch_name: 架构名称(如 x64、arm64)
Returns:
候选路径列表(按优先级排序)
"""
candidates = []
# 优先级 1: 特定平台和架构的目录
specific_path = base_libs_path / system_dir / arch_name
if specific_path.is_dir():
candidates.append(specific_path)
# 优先级 2: 特定平台的目录
platform_path = base_libs_path / system_dir
if platform_path.is_dir() and platform_path not in candidates:
candidates.append(platform_path)
# 优先级 3: 基础 libs 目录
if base_libs_path.is_dir() and base_libs_path not in candidates:
candidates.append(base_libs_path)
return candidates
def get_search_paths(system: PLATFORM, arch_name: str) -> list[tuple[str, str]]:
"""获取库文件搜索路径列表
按优先级:特定平台/架构 > 特定平台 > 通用 > 项目根目录
Args:
system: 平台枚举值
arch_name: 架构名称
Returns:
(目录路径, 文件名) 元组列表
"""
lib_name = cast(str, get_lib_name(system))
search_paths: list[tuple[str, str]] = []
platform_dict = _get_platform_dict()
system_dir = platform_dict[system]["dir"]
base_libs_path = Path(APP_DIR) / "libs"
# 如果 libs 目录不存在,直接返回项目根目录
if not base_libs_path.is_dir():
logger.debug(f"未找到 libs 目录: {base_libs_path}")
return [(APP_DIR, lib_name)]
# 候选路径列表
lib_candidates = _build_lib_candidates(base_libs_path, system_dir, arch_name)
for lib_path in lib_candidates:
search_paths.append((str(lib_path), lib_name))
logger.debug(f"找到 libs 目录: {lib_path}")
# 添加项目根目录作为最后的备选
if not search_paths or str(Path(APP_DIR) / "libs") not in [
s[0] for s in search_paths
]:
search_paths.append((APP_DIR, lib_name))
# 调试日志:显示所有搜索路径
for dir_path, filename in search_paths:
full_path = os.path.join(dir_path, filename)
exists = os.path.exists(full_path)
logger.debug(f"搜索路径: {full_path} (存在: {exists})")
return search_paths
def find_system_opus(system: PLATFORM) -> str:
"""从系统路径查找 Opus 库
Args:
system: 平台枚举值
Returns:
找到的库路径,未找到返回空字符串
"""
lib_names = get_lib_name(system, local=False)
if isinstance(lib_names, str):
lib_names = [lib_names]
for lib_name in lib_names:
try:
system_lib_path = ctypes.util.find_library(lib_name)
if system_lib_path:
logger.info(f"在系统路径中找到 Opus 库: {system_lib_path}")
return system_lib_path
# 直接尝试加载库名
_ = ctypes.cdll.LoadLibrary(lib_name)
logger.info(f"直接加载系统 Opus 库: {lib_name}")
return lib_name
except (OSError, TypeError) as e:
logger.debug(f"加载系统库失败: {lib_name} - {e}")
continue
logger.debug("在系统中未找到 Opus 库")
return ""
def _find_local_opus(system: PLATFORM, arch_name: str) -> str:
"""从本地搜索路径查找 Opus 库
Args:
system: 平台枚举值
arch_name: 架构名称
Returns:
找到的库文件路径,未找到返回空字符串
"""
search_paths = get_search_paths(system, arch_name)
for dir_path, file_name in search_paths:
full_path = os.path.join(dir_path, file_name)
if os.path.exists(full_path):
logger.info(f"在本地找到 Opus 库文件: {full_path}")
return str(full_path)
logger.debug("本地未找到 Opus 库文件")
return ""
def _setup_dll_search_path(system: PLATFORM, lib_dir: str) -> None:
"""在Windows上设置DLL搜索路径
Args:
system: 平台枚举值
lib_dir: 库文件所在目录
"""
if system != PLATFORM.WINDOWS or not lib_dir:
return
try:
if hasattr(os, "add_dll_directory"):
os.add_dll_directory(lib_dir)
logger.debug(f"已添加DLL搜索路径: {lib_dir}")
except OSError as e:
logger.warning(f"添加DLL搜索路径失败: {e}")
os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "")
def _patch_find_library(lib_name: str, lib_path: str) -> None:
"""修补ctypes.util.find_library函数
Args:
lib_name: 库名称
lib_path: 库文件路径
"""
original_find_library = ctypes.util.find_library
def patched_find_library(name: str) -> str | None:
if name == lib_name:
return lib_path
return original_find_library(name)
ctypes.util.find_library = patched_find_library
def _load_opus_library(lib_path: str) -> bool:
"""尝试加载opus库
Args:
lib_path: 库文件路径
Returns:
加载成功返回True,否则返回False
"""
try:
_ = ctypes.CDLL(lib_path)
logger.info(f"成功加载 Opus 库: {lib_path}")
setattr(sys, "_opus_loaded", True)
return True
except OSError as e:
logger.error(f"加载 Opus 库失败: {lib_path} - {e}")
return False
def setup_opus() -> bool:
"""加载 Opus 动态库 - 优先级:系统库 > 本地库"""
# 检查是否已经由 runtime_hook 加载
if hasattr(sys, "_opus_loaded"):
logger.info("Opus 库已由运行时钩子加载")
return True
system, arch_name = get_system_info()
# 1. 从系统路径加载
logger.info("尝试从系统路径加载 Opus 库")
system_lib_path = find_system_opus(system)
if system_lib_path:
logger.info(f"在系统中找到 Opus 库: {system_lib_path}")
return _load_opus_library(system_lib_path)
# 2. 从本地搜索路径查找
logger.info("系统路径未找到,尝试从本地加载 Opus 库")
local_lib_path = _find_local_opus(system, arch_name)
if local_lib_path:
lib_dir = str(Path(local_lib_path).parent)
_setup_dll_search_path(system, lib_dir)
_patch_find_library("opus", local_lib_path)
return _load_opus_library(local_lib_path)
logger.error("无法加载 Opus 库")
return False

View file

@ -1,3 +0,0 @@
import os
APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

View file

@ -1,36 +0,0 @@
import os
from logging import getLogger
from .constant import APP_DIR
logger = getLogger(__name__)
def find_libs_dir(system: str = "", arch: str = "") -> str | None:
"""查找libs目录(用于动态库)
Args:
system: 系统名称(如Windows、Linux、Darwin)
arch: 架构名称(如x64、x86、arm64)
Returns:
找到的libs目录绝对路径,未找到返回None
"""
# 基础libs目录
libs_dir = os.path.join(APP_DIR, "libs")
if not os.path.exists(libs_dir):
logger.error(f"未找到libs目录: {libs_dir}")
return None
# 如果指定了系统和架构,查找具体的子目录
if system and arch:
specific_dir = os.path.join(libs_dir, system, arch)
logger.info(f"spec: {specific_dir}")
if os.path.isdir(specific_dir):
return specific_dir
elif system:
system_dir = os.path.join(libs_dir, system)
if os.path.isdir(system_dir):
return system_dir
return libs_dir

View file

@ -1,335 +0,0 @@
# 在导入 opuslib 之前处理 opus 动态库
import ctypes
import os
import platform
import shutil
import sys
from enum import Enum
# 获取日志记录器
from logging import getLogger
from pathlib import Path
from typing import cast
from .constant import APP_DIR
logger = getLogger(__name__)
# 平台常量定义
class PLATFORM(Enum):
WINDOWS = "windows"
MACOS = "darwin"
LINUX = "linux"
# 架构常量定义
class ARCH(Enum):
WINDOWS = {"arm": "x64", "intel": "x64"}
MACOS = {"arm": "arm64", "intel": "x64"}
LINUX = {"arm": "arm64", "intel": "x64"}
# 动态链接库路径常量定义
class LIB_PATH(Enum):
WINDOWS = "libs/win/x64"
MACOS = "libs/mac/{arch}"
LINUX = "libs/linux/{arch}"
# 动态链接库名称常量定义
class LIB_INFO(Enum):
WINDOWS = {"name": "opus.dll", "system_name": ["opus"]}
MACOS = {"name": "libopus.dylib", "system_name": ["libopus.dylib"]}
LINUX = {"name": "libopus.so", "system_name": ["libopus.so.0", "libopus.so"]}
def get_platform() -> PLATFORM:
system = platform.system().lower()
if system == "windows" or system.startswith("win"):
system = PLATFORM.WINDOWS
elif system == "darwin":
system = PLATFORM.MACOS
else:
system = PLATFORM.LINUX
return system
def get_arch(system: PLATFORM) -> tuple[str, str]:
architecture = platform.machine().lower()
is_arm = "arm" in architecture or "aarch64" in architecture
if system == PLATFORM.WINDOWS:
arch_name = ARCH.WINDOWS.value["arm" if is_arm else "intel"]
elif system == PLATFORM.MACOS:
arch_name = ARCH.MACOS.value["arm" if is_arm else "intel"]
else:
arch_name = ARCH.LINUX.value["arm" if is_arm else "intel"]
return architecture, arch_name
def get_lib_path(system: PLATFORM, arch_name: str):
if system == PLATFORM.WINDOWS:
lib_name = LIB_PATH.WINDOWS.value
elif system == PLATFORM.MACOS:
lib_name = LIB_PATH.MACOS.value.format(arch=arch_name)
else:
lib_name = LIB_PATH.LINUX.value.format(arch=arch_name)
return lib_name
def get_lib_name(system: PLATFORM, local: bool = True) -> str | list[str]:
"""获取库名称.
Args:
system (PLATFORM): 平台
local (bool, optional): 是否获取本地名称(str), 默认为 True. 如果为 False, 则获取系统名称列表(list).
Returns:
str | list: 库名称
"""
key = "name" if local else "system_name"
if system == PLATFORM.WINDOWS:
lib_name = LIB_INFO.WINDOWS.value[key]
elif system == PLATFORM.MACOS:
lib_name = LIB_INFO.MACOS.value[key]
else:
lib_name = LIB_INFO.LINUX.value[key]
return lib_name
def get_system_info() -> tuple[PLATFORM, str]:
"""
获取当前系统信息.
"""
# 标准化系统名称
system = get_platform()
# 标准化架构名称
_, arch_name = get_arch(system)
logger.info(f"检测到系统: {system}, 架构: {arch_name}")
return system, arch_name
def get_search_paths(system: PLATFORM, arch_name: str) -> list[tuple[str, str]]:
"""
获取库文件搜索路径列表(使用统一的资源查找器)
"""
from .finder import find_libs_dir
lib_name = cast(str, get_lib_name(system))
search_paths: list[tuple[str, str]] = []
# 映射系统名称到目录名称
system_dir_map = {
PLATFORM.WINDOWS: "win",
PLATFORM.MACOS: "mac",
PLATFORM.LINUX: "linux",
}
system_dir = system_dir_map.get(system)
# 首先尝试查找特定平台和架构的libs目录
if system_dir:
specific_libs_dir = find_libs_dir(system_dir, arch_name)
if specific_libs_dir:
search_paths.append((specific_libs_dir, lib_name))
logger.debug(f"找到特定平台架构libs目录: {specific_libs_dir}")
# 然后查找特定平台的libs目录
if system_dir:
platform_libs_dir = find_libs_dir(system_dir)
if platform_libs_dir:
search_paths.append((platform_libs_dir, lib_name))
logger.debug(f"找到特定平台libs目录: {platform_libs_dir}")
# 查找通用libs目录
general_libs_dir = find_libs_dir()
if general_libs_dir:
search_paths.append((general_libs_dir, lib_name))
logger.debug(f"添加通用libs目录: {general_libs_dir}")
# 添加项目根目录作为最后的备选
project_root = APP_DIR
search_paths.append((project_root, lib_name))
# 打印所有搜索路径,帮助调试
for dir_path, filename in search_paths:
full_path = os.path.join(dir_path, filename)
logger.debug(f"搜索路径: {full_path} (存在: {os.path.exists(full_path)})")
return search_paths
def find_system_opus() -> str:
"""
从系统路径查找opus库.
"""
system, _ = get_system_info()
lib_path = ""
try:
# 获取系统上opus库的名称
lib_names = get_lib_name(system, False)
# 尝试加载每个可能的名称
for lib_name in lib_names:
try:
# 导入ctypes.util以使用find_library函数
import ctypes.util
system_lib_path = ctypes.util.find_library(lib_name)
if system_lib_path:
lib_path = system_lib_path
logger.info(f"在系统路径中找到opus库: {lib_path}")
break
else:
# 直接尝试加载库名
_ = ctypes.cdll.LoadLibrary(lib_name)
lib_path = lib_name
logger.info(f"直接加载系统opus库: {lib_name}")
break
except Exception as e:
logger.debug(f"加载系统库 {lib_name} 失败: {e}")
continue
except Exception as e:
logger.error(f"查找系统opus库失败: {e}")
return lib_path
def copy_opus_to_project(system_lib_path: str):
"""
将系统库复制到项目目录.
"""
system, arch_name = get_system_info()
if not system_lib_path:
logger.error("无法复制opus库:系统库路径为空")
return None
try:
# 使用resource_finder获取项目根目录
project_root = APP_DIR
# 获取目标目录路径 - 使用实际目录结构
target_path = get_lib_path(system, arch_name)
target_dir = os.path.join(project_root, target_path)
# 创建目标目录(如果不存在)
os.makedirs(target_dir, exist_ok=True)
# 确定目标文件名
lib_name = cast(str, get_lib_name(system))
target_file = os.path.join(target_dir, lib_name)
# 复制文件
_ = shutil.copy2(system_lib_path, target_file)
logger.info(f"已将opus库从 {system_lib_path} 复制到 {target_file}")
return str(target_file)
except Exception as e:
logger.error(f"复制opus库到项目目录失败: {e}")
return None
def setup_opus() -> bool:
"""
设置opus动态库.
"""
# 检查是否已经由runtime_hook加载
if hasattr(sys, "_opus_loaded"):
logger.info("opus库已由运行时钩子加载")
return True
# 获取当前系统信息
system, arch_name = get_system_info()
logger.info(f"当前系统: {system}, 架构: {arch_name}")
# 构建搜索路径
search_paths = get_search_paths(system, arch_name)
# 查找本地库文件
lib_path = ""
lib_dir = ""
for dir_path, file_name in search_paths:
full_path = os.path.join(dir_path, file_name)
if os.path.exists(full_path):
lib_path = str(full_path)
lib_dir = str(dir_path)
logger.info(f"找到opus库文件: {lib_path}")
break
# 如果本地没找到,尝试从系统查找
if not lib_path:
logger.warning("本地未找到opus库文件,尝试从系统路径加载")
system_lib_path = find_system_opus()
if system_lib_path:
# 首次尝试直接使用系统库
try:
_ = ctypes.cdll.LoadLibrary(system_lib_path)
logger.info(f"已从系统路径加载opus库: {system_lib_path}")
setattr(sys, "_opus_loaded", True)
return True
except Exception as e:
logger.warning(f"加载系统opus库失败: {e},尝试复制到项目目录")
# 如果直接加载失败,尝试复制到项目目录
lib_path = copy_opus_to_project(system_lib_path)
if lib_path:
lib_dir = str(Path(lib_path).parent)
else:
logger.error("无法找到或复制opus库文件")
return False
else:
logger.error("在系统中也未找到opus库文件")
return False
# Windows平台特殊处理
if system == PLATFORM.WINDOWS and lib_dir:
# 添加DLL搜索路径
if hasattr(os, "add_dll_directory"):
try:
_ = os.add_dll_directory(lib_dir)
logger.debug(f"已添加DLL搜索路径: {lib_dir}")
except Exception as e:
logger.warning(f"添加DLL搜索路径失败: {e}")
# 设置环境变量
os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "")
# 修补库路径
_patch_find_library("opus", lib_path)
# 尝试加载库
try:
# 加载DLL并存储引用以防止垃圾回收
_ = ctypes.CDLL(lib_path)
logger.info(f"成功加载opus库: {lib_path}")
setattr(sys, "_opus_loaded", True)
return True
except Exception as e:
logger.error(f"加载opus库失败: {e}")
return False
def _patch_find_library(lib_name: str, lib_path: str):
"""
修补ctypes.util.find_library函数.
"""
import ctypes.util
original_find_library = ctypes.util.find_library
def patched_find_library(name: str):
if name == lib_name:
return lib_path
return original_find_library(name)
ctypes.util.find_library = patched_find_library

7
pyproject.toml Normal file
View file

@ -0,0 +1,7 @@
[project]
name = "xiaozhi-esp32-server"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.10"
dependencies = []

8
uv.lock Normal file
View file

@ -0,0 +1,8 @@
version = 1
revision = 2
requires-python = ">=3.10"
[[package]]
name = "xiaozhi-esp32-server"
version = "0.1.0"
source = { virtual = "." }