feat: semantic eou

This commit is contained in:
xiehao.0527 2025-07-01 22:46:24 +08:00
parent 272db0da9d
commit db0cbdf15e
7 changed files with 148 additions and 5 deletions

View file

@ -0,0 +1,21 @@
-- 增加火山大模型网关VAD供应器
DELETE FROM `ai_model_provider` WHERE `id` = 'SYSTEM_ASR_VOLC_GW';
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
('SYSTEM_ASR_VOLC_GW', 'VAD', 'volcengine', '火山引擎边缘大模型网关', '[{"key":"api_key","label":"网关秘钥","type":"string"},{"key":"model_name","label":"模型名称","type":"string"},{"key":"host","label":"网关域名","type":"string"},{"key":"senmatic_only","label":"仅使用语义判停","type":"boolean"},{"key":"threshold","label":"音量检测阈值","type":"number"},{"key":"min_silence_duration_ms","label":"最小静音时长","type":"number"},{"key":"max_silence_duration_ms","label":"最大静音时长","type":"number"}]', 1, 1, NOW(), 1, NOW());
-- 增加火山大模型网关VAD模型配置
DELETE FROM `ai_model_config` WHERE `id` = 'VAD_VolceAIGateway';
INSERT INTO `ai_model_config` VALUES ('VAD_VolceAIGateway', 'VAD', 'VolceAIGateway', '火山引擎边缘大模型网关', 0, 1, '{\"type\": \"volcengine\", \"api_key\": \"火山引擎边缘大模型网关的秘钥\", \"model_name\": \"semantic-integrity-recognition\", \"host\": \"ai-gateway.vei.volces.com\", \"senmatic_only\": false,\"threshold\": 0.5, \"min_silence_duration_ms\": 700, \"max_silence_duration_ms\": 3000}', NULL, NULL, 16, 1, NOW(), 1, NOW());
-- 火山大模型网关VAD模型配置说明文档
UPDATE `ai_model_config` SET
`doc_link` = 'https://console.volcengine.com/vei/aigateway/',
`remark` = '火山引擎边缘大模型网关VAD配置说明:
1. 访问 https://console.volcengine.com/vei/aigateway/
2. 创建网关访问密钥(个人用户申请时注明来自小智xiaozhi-esp32-server社区,并描述使用背景,可更快获得审批,并有机会获得更多token, VAD模型需要oncall发起开白)
3. 勾选Semantic-Integrity-Recognition,网关支持一个api_key访问ASR,LLM,TTS,VLLM模型,满足智能体使用,推荐同时开通“Doubao-语音识别”、“Doubao-语音合成”、“Doubao-pro-32k-functioncall”、“Doubao-1.5-vision-pro”全量模型
4. 填入配置文件中' WHERE `id` = 'VAD_VolceAIGateway';

View file

@ -233,3 +233,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202506191643.sql
- changeSet:
id: 202506301830
author: hrz
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202506301830.sql

View file

@ -111,6 +111,10 @@ class ASRProviderBase(ABC):
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
pass
def is_eou(self, conn, text) -> bool:
"""判断是否为结束语句"""
return conn.asr_provider.is_eou(conn, text)
@staticmethod
def decode_opus(opus_data: List[bytes]) -> bytes:

View file

@ -94,8 +94,8 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio.clear()
except Exception as e:
logger.bind(tag=TAG).error(f"Error sending audio data: {e}", exc_info=True)
if not have_voice and self.ws and self.is_processing:
# TODO: 是否用conn.client_voice_stop 判断会话结束
if self.is_eou(conn, self.text) and self.ws and self.is_processing:
logger.bind(tag=TAG).info( f"session: {self.current_session_id} 结束会话")
await self.finish_session(self.current_session_id)

View file

@ -7,3 +7,13 @@ class VADProviderBase(ABC):
def is_vad(self, conn, data) -> bool:
"""检测音频数据中的语音活动"""
pass
@abstractmethod
def is_eou(self, conn, data, text) -> bool:
"""End of Utterance(话语结束检测),是基于语义理解的自动判断用户发言是否结束的技术, True 表示结束,False 表示未结束"""
pass
@abstractmethod
def get_silence_duration(self, conn) -> int:
"""返回语音静音时长,单位ms"""
pass

View file

@ -18,7 +18,7 @@ class VADProvider(VADProviderBase):
model="silero_vad",
force_reload=False,
)
self.stop_duration = 0
self.decoder = opuslib_next.Decoder(16000, 1)
# 处理空字符串的情况
@ -66,10 +66,10 @@ class VADProvider(VADProviderBase):
# 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
if conn.client_have_voice and not client_have_voice:
stop_duration = (
self.stop_duration = (
time.time() * 1000 - conn.client_have_voice_last_time
)
if stop_duration >= self.silence_threshold_ms:
if self.stop_duration >= self.silence_threshold_ms:
conn.client_voice_stop = True
if client_have_voice:
conn.client_have_voice = True
@ -80,3 +80,13 @@ class VADProvider(VADProviderBase):
logger.bind(tag=TAG).info(f"解码错误: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")
def is_eou(self, conn, text) :
"""End of Utterance(话语结束检测),是基于语义理解的自动判断用户发言是否结束的技术"""
return conn.client_voice_stop
def get_silence_duration(self, conn) :
"""返回语音静音时长,单位ms"""
if conn.client_voice_stop == True:
return self.stop_duration
return 0

View file

@ -0,0 +1,91 @@
import time
import numpy as np
import torch
import opuslib_next
import openai # 新增OpenAI库导入
from config.logger import setup_logging
from core.providers.vad.base import VADProviderBase
from core.utils.util import create_instance
TAG = __name__
logger = setup_logging()
class VADProvider(VADProviderBase):
def __init__(self, config):
logger.bind(tag=TAG).info("VAD_volcengine", config)
self.base_vad_model = create_instance("silero", config)
# 处理空字符串的情况
min_silence_duration_ms = config.get("min_silence_duration_ms", "1000")
max_silence_duration_ms = config.get("min_silence_duration_ms", "1000")
self.semantic_only = config.get("semantic_only", False)
self.min_silence_threshold_ms = (
int(min_silence_duration_ms) if min_silence_duration_ms else 1000
)
self.max_silence_threshold_ms = (
int(max_silence_duration_ms) if max_silence_duration_ms else 3000
)
self.api_key = config.get("api_key")
self.model_name = config.get("model_name")
self.host = config.get("host")
if self.host is None:
self.host = "ai-gateway.vei.volces.com"
self.base_url = f"https://{self.host}/v1"
def is_vad(self, conn, opus_packet):
if self.semantic_only:
return True
return self.base_vad_model.is_vad(conn, opus_packet)
def is_eou(self, conn, text) :
embedding = self._get_embedding(text)
is_stop = embedding[1] > 0.5
logger.bind(tag=TAG).info( f"EOU Result: text:{text} embedding:{embedding} stop:{is_stop}")
if self.semantic_only:
return is_stop
silence_duration = self.get_silence_duration(conn)
if silence_duration <= self.min_silence_threshold_ms:
# vad 静默时间比较短,倾向于对话未结束,语义判停阈值较高
return embedding[1] > 0.9
elif silence_duration > self.min_silence_threshold_ms and silence_duration < self.max_silence_threshold_ms:
# vad 静默时间比较短,倾向于对话未结束,语义判停阈值较低
return embedding[1] > 0.6
else:
# vad 静默时间比较长,直接判停
return True
def get_silence_duration(self, conn) :
return self.base_vad_model.get_silence_duration(conn)
# 新增嵌入模型调用方法
def _get_embedding(self, text: str) -> list:
"""调用OpenAI嵌入模型获取文本嵌入向量
Args:
text: 需要生成嵌入的文本
Returns:
list: 嵌入向量列表,第一个参数表示未结束的概率
"""
try:
client = openai.OpenAI(
base_url = self.base_url,
api_key = self.api_key
)
response = client.embeddings.create(
model=self.model_name,
input=text
)
return response["data"][0]["embedding"]
except Exception as e:
logger.bind(tag=TAG).error(f"调用嵌入模型失败: {str(e)}")
raise