mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
Speechbrain说话人验证
This commit is contained in:
parent
9ca98f6391
commit
57c1a19cce
5 changed files with 188 additions and 0 deletions
|
|
@ -107,6 +107,9 @@ class ConnectionHandler:
|
|||
self.tts = _tts
|
||||
self.memory = _memory
|
||||
self.intent = _intent
|
||||
# 导入SpeechBrainProvider
|
||||
from core.providers.speaker.speechbrain import SpeechBrainProvider
|
||||
self.speaker = SpeechBrainProvider(None,False)
|
||||
|
||||
# vad相关变量
|
||||
self.client_audio_buffer = bytearray()
|
||||
|
|
|
|||
|
|
@ -39,6 +39,15 @@ async def handleAudioMessage(conn, audio):
|
|||
if len(conn.asr_audio) < 15:
|
||||
conn.asr_server_receive = True
|
||||
else:
|
||||
|
||||
|
||||
# 极简流式声纹检测调用
|
||||
is_owner,score = await conn.speaker.handle_audio_data(conn.asr_audio, conn.session_id)
|
||||
if is_owner:
|
||||
conn.logger.bind(tag=TAG).info(f"流式识别到主人音频,score={score}")
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).info(f"流式未识别为主人,忽略音频,score={score}")
|
||||
|
||||
raw_text, _ = await conn.asr.speech_to_text(
|
||||
conn.asr_audio, conn.session_id
|
||||
) # 确保ASR模块返回原始文本
|
||||
|
|
|
|||
81
main/xiaozhi-server/core/providers/speaker/base.py
Normal file
81
main/xiaozhi-server/core/providers/speaker/base.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple, List
|
||||
import opuslib_next
|
||||
from config.logger import setup_logging
|
||||
import os
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class SpeakerProviderBase(ABC):
|
||||
def __init__(self):
|
||||
self.audio_format = "opus"
|
||||
self.output_dir = "tmp"
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
||||
"""PCM数据保存为WAV文件"""
|
||||
pass
|
||||
|
||||
|
||||
async def handle_audio_data(
|
||||
self, opus_data: List[bytes], session_id: str
|
||||
) -> Tuple[Optional[bool], Optional[float]]:
|
||||
"""验证说话人"""
|
||||
try:
|
||||
# 合并所有opus数据包
|
||||
if self.audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
return self.verify_voice(file_path,combined_pcm_data, session_id)
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||
return False, 0.0
|
||||
|
||||
@abstractmethod
|
||||
def verify_voice(
|
||||
self, file_path: str,audio_data: List[bytes], session_id: str
|
||||
) -> Tuple[Optional[bool], Optional[float]]:
|
||||
"""验证说话人处理逻辑"""
|
||||
pass
|
||||
|
||||
def set_audio_format(self, format: str) -> None:
|
||||
"""设置音频格式"""
|
||||
self.audio_format = format
|
||||
|
||||
@staticmethod
|
||||
def decode_opus(opus_data: List[bytes]) -> bytes:
|
||||
"""将Opus音频数据解码为PCM数据"""
|
||||
try:
|
||||
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
|
||||
pcm_data = []
|
||||
buffer_size = 960 # 每次处理960个采样点
|
||||
|
||||
for opus_packet in opus_data:
|
||||
try:
|
||||
# 使用较小的缓冲区大小进行处理
|
||||
pcm_frame = decoder.decode(opus_packet, buffer_size)
|
||||
if pcm_frame:
|
||||
pcm_data.append(pcm_frame)
|
||||
except opuslib_next.OpusError as e:
|
||||
logger.bind(tag=TAG).warning(f"Opus解码错误,跳过当前数据包: {e}")
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"音频处理错误: {e}", exc_info=True)
|
||||
continue
|
||||
|
||||
return pcm_data
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}", exc_info=True)
|
||||
return []
|
||||
92
main/xiaozhi-server/core/providers/speaker/speechbrain.py
Normal file
92
main/xiaozhi-server/core/providers/speaker/speechbrain.py
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import os
|
||||
import time
|
||||
import torch
|
||||
import pyaudio
|
||||
import numpy as np
|
||||
from collections import deque
|
||||
from scipy.io import wavfile
|
||||
from scipy.spatial.distance import cosine
|
||||
from speechbrain.pretrained import SpeakerRecognition
|
||||
|
||||
from core.providers.speaker.base import SpeakerProviderBase
|
||||
from typing import Optional, Tuple, List
|
||||
|
||||
import wave
|
||||
import uuid
|
||||
|
||||
from config.logger import setup_logging
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
# 音频参数
|
||||
SAMPLE_RATE = 16000
|
||||
CHUNK = 1024
|
||||
CHANNELS = 1
|
||||
FORMAT = pyaudio.paInt16
|
||||
BUFFER_SECONDS = 2
|
||||
THRESHOLD = 0.35
|
||||
ENROLL_FILE = "enrolled_voice.wav"
|
||||
|
||||
|
||||
|
||||
class SpeechBrainProvider(SpeakerProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__()
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# 初始化模型
|
||||
print("🔁 正在加载说话人识别模型...")
|
||||
self.model = SpeakerRecognition.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb")
|
||||
print("✅ 模型加载完成")
|
||||
|
||||
def load_audio_embedding(self,filepath):
|
||||
wav_tensor = self.model.load_audio(filepath).unsqueeze(0)
|
||||
embed = self.model.encode_batch(wav_tensor).squeeze().detach().cpu().numpy()
|
||||
return embed
|
||||
|
||||
def verify_from_array(self,audio_array: np.ndarray):
|
||||
global owner_embed
|
||||
print("🔁 正在加载owner_embed...")
|
||||
owner_embed = self.load_audio_embedding(ENROLL_FILE)
|
||||
if audio_array.dtype != np.float32:
|
||||
audio_array = audio_array.astype(np.float32)
|
||||
|
||||
audio_tensor = torch.from_numpy(audio_array).unsqueeze(0)
|
||||
embed = self.model.encode_batch(audio_tensor).squeeze().detach().cpu().numpy()
|
||||
score = 1 - cosine(owner_embed, embed)
|
||||
return score
|
||||
|
||||
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
||||
"""PCM数据保存为WAV文件"""
|
||||
module_name = __name__.split(".")[-1]
|
||||
file_name = f"speaker_{module_name}_{session_id}_{uuid.uuid4()}.wav"
|
||||
file_path = os.path.join(self.output_dir, file_name)
|
||||
|
||||
with wave.open(file_path, "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2) # 2 bytes = 16-bit
|
||||
wf.setframerate(16000)
|
||||
wf.writeframes(b"".join(pcm_data))
|
||||
|
||||
return file_path
|
||||
|
||||
def verify_voice(
|
||||
self, file_path: str,audio_data: List[bytes], session_id: str
|
||||
) -> Tuple[Optional[bool], Optional[float]]:
|
||||
"""验证说话人处理逻辑"""
|
||||
|
||||
# 使用 SpeechBrain 模型对比
|
||||
score, prediction = self.model.verify_files(ENROLL_FILE, file_path)
|
||||
# os.remove(temp_file)
|
||||
|
||||
print(f"[识别结果] 相似度分数:{score.item():.4f}")
|
||||
if prediction:
|
||||
print("✅ 说话人身份通过(与注册声音一致)")
|
||||
return prediction,score
|
||||
else:
|
||||
print("❌ 说话人身份不一致")
|
||||
return False,-1.0
|
||||
|
||||
|
||||
|
||||
|
|
@ -31,3 +31,6 @@ chardet==5.2.0
|
|||
aioconsole==0.8.1
|
||||
markitdown==0.1.1
|
||||
mcp-proxy==0.6.0
|
||||
speechbrain==1.0.3
|
||||
pyaudio
|
||||
scipy
|
||||
|
|
|
|||
Loading…
Reference in a new issue