diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py index 5547104d9..c0b91baaa 100644 --- a/main/xiaozhi-server/core/providers/asr/fun_local.py +++ b/main/xiaozhi-server/core/providers/asr/fun_local.py @@ -5,6 +5,7 @@ import time import shutil import psutil import asyncio +import threading from funasr import AutoModel from config.logger import setup_logging @@ -56,6 +57,9 @@ class ASRProvider(ASRProviderBase): self.output_dir = config.get("output_dir") # 修正配置键名 self.language = config.get("language", "auto") self.delete_audio_file = delete_audio_file + # 实例可能被多个连接共享(见 core/utils/asr.py 的本地 ASR 缓存), + # AutoModel.generate 不是线程安全的,这里串行化推理(#3365) + self._generate_lock = threading.Lock() # 确保输出目录存在 os.makedirs(self.output_dir, exist_ok=True) @@ -68,6 +72,16 @@ class ASRProvider(ASRProviderBase): # device="cuda:0", # 启用GPU加速 ) + def _generate_locked(self, pcm_bytes: bytes): + with self._generate_lock: + return self.model.generate( + input=pcm_bytes, + cache={}, + language=self.language, + use_itn=True, + batch_size_s=60, + ) + async def speech_to_text( self, opus_data: List[bytes], session_id: str, artifacts=None ) -> Tuple[Optional[str], Optional[str]]: @@ -82,12 +96,7 @@ class ASRProvider(ASRProviderBase): # 语音识别 - 使用线程池避免阻塞事件循环 start_time = time.time() result = await asyncio.to_thread( - self.model.generate, - input=artifacts.pcm_bytes, - cache={}, - language=self.language, - use_itn=True, - batch_size_s=60, + self._generate_locked, artifacts.pcm_bytes ) text = lang_tag_filter(result[0]["text"]) logger.bind(tag=TAG).debug( diff --git a/main/xiaozhi-server/core/utils/asr.py b/main/xiaozhi-server/core/utils/asr.py index 983114d32..d4c7f309c 100644 --- a/main/xiaozhi-server/core/utils/asr.py +++ b/main/xiaozhi-server/core/utils/asr.py @@ -1,7 +1,9 @@ import importlib +import json import logging import os import sys +import threading import time import wave import uuid @@ -13,12 +15,70 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() +# 本地 ASR:模型常驻内存,单个实例几百 MB ~ 3 GB(FunASR / SenseVoice 约 3 GB)。 +# 同一份配置只加载一次并全进程共享,避免每个 WebSocket 连接各拉一个实例, +# 设备快速连断多次就把内存吃满甚至拖死整台机器(#3365)。 +# +# 只收录"每次调用都自建流/上下文"的 provider: +# - fun_local : AutoModel.generate 每次传新 cache,串行化后安全 +# - sherpa_onnx_local: 每次 create_stream(),模型本身无状态 +# vosk 暂不收录:它的 KaldiRecognizer 在实例上跨调用累积波形状态且非线程安全, +# 多连接共用一个 recognizer 会互相串音(vosk 模型只有几十 MB,复用的收益有限)。 +LOCAL_ASR_TYPES = {"fun_local", "sherpa_onnx_local"} + +_LOCAL_ASR_CACHE: dict = {} +_LOCAL_ASR_CACHE_LOCK = threading.Lock() + + +def _cache_key(class_name: str, args, kwargs): + try: + config = args[0] if len(args) > 0 else kwargs.get("config") + # delete_audio_file 等其余构造参数也要进 key, + # 否则参数不同的两次创建会复用同一个实例 + payload = [config, *args[1:]] if len(args) > 0 else [config] + return class_name + ":" + json.dumps(payload, sort_keys=True, default=str) + except Exception: + return None + + +def cached_local_instance(class_name: str, factory, args, kwargs): + """按「类型 + 配置」复用本地 ASR 实例;非本地类型直接新建。 + + 首次创建时持锁,避免并发连接同时加载模型造成内存翻倍。 + """ + key = _cache_key(class_name, args, kwargs) + if key is None: + return factory() + with _LOCAL_ASR_CACHE_LOCK: + instance = _LOCAL_ASR_CACHE.get(key) + if instance is not None: + logger.bind(tag=TAG).info( + f"复用已加载的本地 ASR 实例: {class_name}(不再为每条连接重复占用内存)" + ) + return instance + instance = factory() + _LOCAL_ASR_CACHE[key] = instance + return instance + + +def clear_local_cache(): + """释放本地 ASR 缓存(测试与热重载用)。""" + with _LOCAL_ASR_CACHE_LOCK: + _LOCAL_ASR_CACHE.clear() + + def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase: """工厂方法创建ASR实例""" if os.path.exists(os.path.join('core', 'providers', 'asr', f'{class_name}.py')): lib_name = f'core.providers.asr.{class_name}' if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') - return sys.modules[lib_name].ASRProvider(*args, **kwargs) - raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确") \ No newline at end of file + def _build(): + return sys.modules[lib_name].ASRProvider(*args, **kwargs) + + if class_name in LOCAL_ASR_TYPES: + return cached_local_instance(class_name, _build, args, kwargs) + return _build() + + raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确") diff --git a/main/xiaozhi-server/tests/core/utils/test_asr_local_cache.py b/main/xiaozhi-server/tests/core/utils/test_asr_local_cache.py new file mode 100644 index 000000000..b8bb29308 --- /dev/null +++ b/main/xiaozhi-server/tests/core/utils/test_asr_local_cache.py @@ -0,0 +1,89 @@ +import pytest + +from core.utils import asr + + +@pytest.fixture(autouse=True) +def _clean_cache(): + asr.clear_local_cache() + yield + asr.clear_local_cache() + + +def test_same_config_reuses_instance(): + created = [] + + def factory(): + instance = object() + created.append(instance) + return instance + + args = ({"model_dir": "models/SenseVoiceSmall", "language": "auto"}, True) + first = asr.cached_local_instance("fun_local", factory, args, {}) + second = asr.cached_local_instance("fun_local", factory, args, {}) + assert first is second + assert len(created) == 1 + + +def test_different_config_creates_new_instance(): + created = [] + + def factory(): + instance = object() + created.append(instance) + return instance + + a = asr.cached_local_instance("fun_local", factory, ({"model_dir": "/a"}, True), {}) + b = asr.cached_local_instance("fun_local", factory, ({"model_dir": "/b"}, True), {}) + assert a is not b + assert len(created) == 2 + + +def test_different_type_creates_new_instance(): + def factory(): + return object() + + a = asr.cached_local_instance("fun_local", factory, ({"model_dir": "/a"}, True), {}) + b = asr.cached_local_instance("vosk", factory, ({"model_dir": "/a"}, True), {}) + assert a is not b + + +class _BadStr: + def __str__(self): + raise ValueError("cannot stringify") + + +def test_unserializable_config_falls_back_to_new_instance(): + def factory(): + return object() + + args = ({"model_dir": _BadStr()}, True) + a = asr.cached_local_instance("fun_local", factory, args, {}) + b = asr.cached_local_instance("fun_local", factory, args, {}) + assert a is not b + + +def test_local_types_cover_known_heavy_providers(): + assert "fun_local" in asr.LOCAL_ASR_TYPES + assert "sherpa_onnx_local" in asr.LOCAL_ASR_TYPES + + +def test_vosk_is_not_cached(): + # vosk 的 KaldiRecognizer 跨调用累积波形状态且非线程安全, + # 共用实例会导致多连接互相串音,所以不进缓存 + assert "vosk" not in asr.LOCAL_ASR_TYPES + + +def test_extra_constructor_args_are_part_of_the_key(): + created = [] + + def factory(): + instance = object() + created.append(instance) + return instance + + config = {"model_dir": "/a"} + keep = asr.cached_local_instance("fun_local", factory, (config, True), {}) + drop = asr.cached_local_instance("fun_local", factory, (config, False), {}) + assert keep is not drop + assert len(created) == 2