test/app/services/asr/funasr_speaker.py

94 lines
3.7 KiB
Python

# -*- coding: utf-8 -*-
"""FunASR-native speaker embedding extraction for realtime diarization."""
from __future__ import annotations
import logging
import threading
from typing import Any, Iterable
import numpy as np
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__)
_model: Any = None
_model_lock = threading.Lock()
_inference_lock = threading.Lock()
def _get_model() -> Any:
"""Load the configured realtime SV checkpoint through FunASR AutoModel."""
global _model
if _model is None:
with _model_lock:
if _model is None:
model_path = resolve_model_path(settings.REALTIME_SV_MODEL)
device = detect_device(settings.DEVICE)
kwargs = dict(settings.FUNASR_AUTOMODEL_KWARGS)
kwargs["disable_update"] = settings.FUNASR_DISABLE_UPDATE
logger.info(
"Loading FunASR realtime speaker model: model_id=%s model_path=%s device=%s disable_update=%s",
settings.REALTIME_SV_MODEL,
model_path,
device,
settings.FUNASR_DISABLE_UPDATE,
)
# Keep the registered ModelScope ID as ``model`` so FunASR can
# resolve ERes2NetV2's model class; pass the local cache path
# separately to load its config and weights without downloading.
_model = AutoModel(
model=settings.REALTIME_SV_MODEL,
model_path=model_path,
device=device,
**kwargs,
)
logger.info("FunASR realtime speaker model loaded: %s", model_path)
return _model
def extract_realtime_speaker_embeddings(audio_chunks: Iterable[np.ndarray]) -> list[np.ndarray]:
"""Extract normalized embeddings using FunASR's generate/preprocess path.
FunASR's ERes2Net inference converts waveform chunks to normalized fbank
features before calling the network. Calling the model's inner ``forward``
directly skips that preprocessing and can make cosine speaker matching
unreliable, so realtime diarization must go through ``AutoModel.generate``.
"""
chunks = [np.asarray(audio, dtype=np.float32).reshape(-1) for audio in audio_chunks]
if not chunks:
return []
if any(chunk.size == 0 for chunk in chunks):
raise ValueError("speaker audio chunks must not be empty")
model = _get_model()
# Match FunASR's realtime tracker: infer all 1.5 s windows together through
# generate(), which runs the model's own audio loading and feature frontend.
with _inference_lock:
results = model.generate(input=chunks, cache={}, is_final=True)
if not isinstance(results, (list, tuple)) or len(results) != len(chunks):
raise RuntimeError(
"FunASR speaker model returned an unexpected result count: "
f"expected={len(chunks)} actual={len(results) if hasattr(results, '__len__') else 'unknown'}"
)
embeddings: list[np.ndarray] = []
for result in results:
value = result.get("spk_embedding") if isinstance(result, dict) else None
if value is None:
raise RuntimeError("FunASR speaker model result has no spk_embedding")
if hasattr(value, "detach"):
value = value.detach().cpu().numpy()
embedding = np.asarray(value, dtype=np.float32).reshape(-1)
norm = float(np.linalg.norm(embedding))
if norm <= 1e-12:
raise RuntimeError("FunASR speaker model returned an empty embedding")
embeddings.append((embedding / norm).astype(np.float32))
return embeddings