test/app/services/asr/funasr_streaming.py

89 lines
3.1 KiB
Python

# -*- coding: utf-8 -*-
"""Shared model loader for FunASR's native Paraformer streaming checkpoint."""
import logging
import threading
from typing import Any
from funasr import AutoModel
from app.core.config import settings
from app.core.device import detect_device
from app.infrastructure import resolve_model_path
logger = logging.getLogger(__name__)
FUNASR_STREAMING_MODEL_ID = (
"iic/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online"
)
FUNASR_OFFLINE_MODEL_ID = (
"iic/speech_paraformer-large-contextual_asr_nat-zh-cn-16k-common-vocab8404"
)
_model: Any = None
_model_lock = threading.Lock()
_inference_lock = threading.Lock()
_offline_model: Any = None
_offline_model_lock = threading.Lock()
_offline_inference_lock = threading.Lock()
def unload_models() -> None:
"""Release shared Paraformer instances before switching realtime routes."""
global _model, _offline_model
with _model_lock, _offline_model_lock:
_model = None
_offline_model = None
def get_streaming_model() -> Any:
"""Load one process-wide model instance; per-stream caches live in the caller."""
global _model
if _model is None:
with _model_lock:
if _model is None:
model_path = resolve_model_path(FUNASR_STREAMING_MODEL_ID)
device = detect_device(settings.DEVICE)
kwargs = dict(settings.FUNASR_AUTOMODEL_KWARGS)
kwargs["disable_update"] = settings.FUNASR_DISABLE_UPDATE
logger.info(
"Loading FunASR streaming ASR model: model=%s device=%s disable_update=%s",
model_path,
device,
settings.FUNASR_DISABLE_UPDATE,
)
_model = AutoModel(model=model_path, device=device, **kwargs)
logger.info("FunASR streaming ASR model loaded: %s", model_path)
return _model
def get_inference_lock() -> threading.Lock:
"""Protect mutable AutoModel generate configuration across WebSocket tasks."""
return _inference_lock
def get_offline_model() -> Any:
"""Load FunASR's contextual second-pass model for final text and hotwords."""
global _offline_model
if _offline_model is None:
with _offline_model_lock:
if _offline_model is None:
model_path = resolve_model_path(FUNASR_OFFLINE_MODEL_ID)
device = detect_device(settings.DEVICE)
kwargs = dict(settings.FUNASR_AUTOMODEL_KWARGS)
kwargs["disable_update"] = settings.FUNASR_DISABLE_UPDATE
logger.info(
"Loading FunASR offline final ASR model: model=%s device=%s disable_update=%s",
model_path,
device,
settings.FUNASR_DISABLE_UPDATE,
)
_offline_model = AutoModel(model=model_path, device=device, **kwargs)
logger.info("FunASR offline final ASR model loaded: %s", model_path)
return _offline_model
def get_offline_inference_lock() -> threading.Lock:
"""Serialize access to the shared offline AutoModel instance."""
return _offline_inference_lock