mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: turn detection && fsmn && interruption strategy
This commit is contained in:
parent
57c6fc4432
commit
0ca74f6283
28 changed files with 880 additions and 3720 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -1,27 +0,0 @@
|
|||
# 如果你只想轻量化安装xiaozhi-server,只使用本地的配置文件,不需要理会这个文件,不需要改动本文件任何东西
|
||||
# 如果你想从manager-api获取配置,请往下看:
|
||||
# 请将本文件复制到xiaozhi-server/data目录下,没有data目录,请创建一个,并将复制过去的文件命名为.config.yaml
|
||||
# 注意如果data目录有.config.yaml文件,请先删除它
|
||||
# 先启动manager-api和manager-web,注册一个账号,第一个注册的账号为管理员
|
||||
# 使用管理员,进入【参数管理】页面,找到【server.secret】,复制它到参数值,注意每次从零部署,server.secret都会变化
|
||||
# 打开本data目录下的.config.yaml文件,修改manager-api.secret为刚才复制出来的server.secret
|
||||
server:
|
||||
ip: 0.0.0.0
|
||||
port: 8000
|
||||
# http服务的端口,用于视觉分析接口
|
||||
http_port: 8003
|
||||
# 视觉分析接口地址
|
||||
# 向设备发送的视觉分析的接口地址
|
||||
# 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下
|
||||
# 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
|
||||
# 所以如果你使用docker部署时,将vision_explain设置成局域网地址
|
||||
# 如果你使用公网部署时,将vision_explain设置成公网地址
|
||||
vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
|
||||
manager-api:
|
||||
# 你的manager-api的地址,最好使用局域网ip
|
||||
# 如果使用docker部署,请使用填写成 http://xiaozhi-esp32-server-web:8002/xiaozhi
|
||||
url: http://127.0.0.1:8002/xiaozhi
|
||||
# 你的manager-api的token,就是刚才复制出来的server.secret
|
||||
secret: 你的server.secret值
|
||||
# 默认系统提示词模板文件
|
||||
prompt_template: agent-base-prompt.txt
|
||||
|
|
@ -13,9 +13,6 @@ import websockets
|
|||
|
||||
from core.utils.util import (
|
||||
extract_json_from_string,
|
||||
check_vad_update,
|
||||
check_asr_update,
|
||||
filter_sensitive_info,
|
||||
)
|
||||
from typing import Dict, Any
|
||||
from collections import deque
|
||||
|
|
@ -25,7 +22,7 @@ from core.utils.modules_initialize import (
|
|||
initialize_asr,
|
||||
)
|
||||
from core.utils import turn_detection as turn_detection_factory
|
||||
from core.handle.reportHandle import report
|
||||
from core.handle.reportHandle import report, enqueue_asr_report
|
||||
from core.providers.tts.default import DefaultTTS
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from core.utils.dialogue import Message, Dialogue
|
||||
|
|
@ -38,18 +35,16 @@ from core.providers.tools.unified_tool_handler import UnifiedToolHandler
|
|||
from plugins_func.loadplugins import auto_import_modules
|
||||
from plugins_func.register import Action
|
||||
from core.auth import AuthenticationError
|
||||
from config.config_loader import get_private_config_from_api
|
||||
from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
|
||||
from config.logger import setup_logging, build_module_string, create_connection_logger
|
||||
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
|
||||
from core.utils.prompt_manager import PromptManager
|
||||
from core.utils.voiceprint_provider import VoiceprintProvider
|
||||
from core.utils import textUtils
|
||||
from config.live_agent_api_client import (
|
||||
get_agent_config_from_api,
|
||||
get_agent_by_wake_from_api,
|
||||
extract_user_id_from_jwt,
|
||||
)
|
||||
from core.utils import tokenize
|
||||
|
||||
TAG = __name__
|
||||
auto_import_modules("plugins_func.functions")
|
||||
|
|
@ -133,6 +128,9 @@ class ConnectionHandler:
|
|||
self.client_voice_stop = False
|
||||
self.last_is_voice = False
|
||||
self._vad_states = {}
|
||||
|
||||
# Updated when VAD inference event detects speaking (milliseconds)
|
||||
self._last_speaking_time: int | None = None
|
||||
|
||||
# asr相关变量
|
||||
# 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
|
||||
|
|
@ -144,6 +142,18 @@ class ConnectionHandler:
|
|||
self.vad_stream: VADStream = None
|
||||
# VAD event processor task
|
||||
self._vad_event_task = None
|
||||
|
||||
# ASR text buffer for current turn (used for smart interrupt)
|
||||
# Accumulated ASR transcription text in current conversation turn
|
||||
self.asr_text_buffer: str = ""
|
||||
|
||||
# Interruption Configuration
|
||||
# Only interrupt when both conditions are met:
|
||||
# 1. Speech duration >= min_interrupt_speech_duration_ms
|
||||
# 2. len(asr_text_buffer) >= min_interrupt_text_length
|
||||
self.enable_interruption: bool = self.config["Interruption"]["enabled"]
|
||||
self.min_interrupt_speech_duration_ms: float = self.config["Interruption"]["min_interrupt_speech_duration_ms"]
|
||||
self.min_interrupt_text_length: int = self.config["Interruption"]["min_interrupt_text_length"]
|
||||
|
||||
# llm相关变量
|
||||
self.llm_finish_task = True
|
||||
|
|
@ -224,7 +234,7 @@ class ConnectionHandler:
|
|||
|
||||
# check if the connection is reconnected by the mobile-end
|
||||
self.reconnected = self.headers.get("reconnected", "0") == "1"
|
||||
self.logger.bind(tag=TAG).info(f"reconnected: {self.reconnected}")
|
||||
self.logger.bind(tag=TAG).debug(f"reconnected: {self.reconnected}")
|
||||
# 检查是否来自MQTT连接
|
||||
request_path = ws.request.path
|
||||
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
|
||||
|
|
@ -1333,6 +1343,31 @@ class ConnectionHandler:
|
|||
self.client_is_speaking = False
|
||||
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
|
||||
|
||||
async def on_end_of_turn(self) -> None:
|
||||
"""Called when user's turn ends (detected by turn detection or ASR)
|
||||
|
||||
Handles:
|
||||
1. Get text from asr_text_buffer
|
||||
2. Clear the buffer
|
||||
3. Start chat with the accumulated text
|
||||
4. Report ASR message
|
||||
"""
|
||||
from core.handle.receiveAudioHandle import startToChat
|
||||
|
||||
full_text = self.asr_text_buffer
|
||||
if len(tokenize.split_words(full_text, ignore_punctuation=True, split_character=True)) < self.min_interrupt_text_length:
|
||||
return
|
||||
|
||||
# Clear buffer before processing
|
||||
self.asr_text_buffer = ""
|
||||
|
||||
# Start chat with accumulated text
|
||||
asr_report_time = int(time.time())
|
||||
await startToChat(self, full_text)
|
||||
|
||||
# Report ASR message
|
||||
enqueue_asr_report(self, full_text, [], report_time=asr_report_time)
|
||||
|
||||
async def close(self, ws=None):
|
||||
"""资源清理方法"""
|
||||
try:
|
||||
|
|
@ -1490,6 +1525,53 @@ class ConnectionHandler:
|
|||
# self.vad.reset_filter()
|
||||
self.logger.bind(tag=TAG).debug("VAD states reset.")
|
||||
|
||||
def _interrupt_by_audio(self, speech_duration_ms: float) -> None:
|
||||
"""Check interruption conditions and trigger interrupt if met
|
||||
|
||||
Interruption strategy:
|
||||
1. Interruption must be enabled
|
||||
2. TTS must be speaking (client_is_speaking = True)
|
||||
3. Not in manual listen mode
|
||||
4. Speech duration >= min_interrupt_speech_duration_ms
|
||||
5. ASR text buffer length >= min_interrupt_text_length
|
||||
|
||||
Args:
|
||||
speech_duration_ms: Current speech duration in milliseconds
|
||||
"""
|
||||
if not self.enable_interruption:
|
||||
return
|
||||
if not self.client_is_speaking:
|
||||
return
|
||||
if self.client_listen_mode == "manual":
|
||||
return
|
||||
|
||||
# Check if meeting interruption thresholds
|
||||
words = tokenize.split_words(
|
||||
self.asr_text_buffer,
|
||||
ignore_punctuation=True,
|
||||
split_character=True,
|
||||
retain_format=False,
|
||||
)
|
||||
asr_text_len = len(words)
|
||||
speech_ok = speech_duration_ms >= self.min_interrupt_speech_duration_ms
|
||||
text_ok = asr_text_len >= self.min_interrupt_text_length
|
||||
|
||||
if speech_ok and text_ok:
|
||||
self.logger.bind(tag=TAG).info(
|
||||
f"Interrupt triggered: speech={speech_duration_ms:.0f}ms >= {self.min_interrupt_speech_duration_ms:.0f}ms, "
|
||||
f"text_len={asr_text_len} >= {self.min_interrupt_text_length}"
|
||||
)
|
||||
# Trigger interrupt
|
||||
self.client_abort = True
|
||||
self.clear_queues()
|
||||
# Send stop message to client
|
||||
async def send_stop_message():
|
||||
await self.websocket.send(
|
||||
json.dumps({"type": "tts", "state": "stop", "session_id": self.session_id})
|
||||
)
|
||||
asyncio.create_task(send_stop_message())
|
||||
self.clearSpeakStatus()
|
||||
|
||||
def chat_and_close(self, text):
|
||||
"""Chat with the user and then close the connection"""
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -1,248 +0,0 @@
|
|||
import http.client
|
||||
import json
|
||||
import asyncio
|
||||
from typing import Optional, Tuple, List
|
||||
import os
|
||||
import uuid
|
||||
import hmac
|
||||
import hashlib
|
||||
import base64
|
||||
import requests
|
||||
from urllib import parse
|
||||
import time
|
||||
from datetime import datetime
|
||||
from config.logger import setup_logging
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class AccessToken:
|
||||
@staticmethod
|
||||
def _encode_text(text):
|
||||
encoded_text = parse.quote_plus(text)
|
||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
||||
|
||||
@staticmethod
|
||||
def _encode_dict(dic):
|
||||
keys = dic.keys()
|
||||
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
|
||||
encoded_text = parse.urlencode(dic_sorted)
|
||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
||||
|
||||
@staticmethod
|
||||
def create_token(access_key_id, access_key_secret):
|
||||
parameters = {
|
||||
"AccessKeyId": access_key_id,
|
||||
"Action": "CreateToken",
|
||||
"Format": "JSON",
|
||||
"RegionId": "cn-shanghai",
|
||||
"SignatureMethod": "HMAC-SHA1",
|
||||
"SignatureNonce": str(uuid.uuid1()),
|
||||
"SignatureVersion": "1.0",
|
||||
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"Version": "2019-02-28",
|
||||
}
|
||||
# 构造规范化的请求字符串
|
||||
query_string = AccessToken._encode_dict(parameters)
|
||||
# print('规范化的请求字符串: %s' % query_string)
|
||||
# 构造待签名字符串
|
||||
string_to_sign = (
|
||||
"GET"
|
||||
+ "&"
|
||||
+ AccessToken._encode_text("/")
|
||||
+ "&"
|
||||
+ AccessToken._encode_text(query_string)
|
||||
)
|
||||
# print('待签名的字符串: %s' % string_to_sign)
|
||||
# 计算签名
|
||||
secreted_string = hmac.new(
|
||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
||||
bytes(string_to_sign, encoding="utf-8"),
|
||||
hashlib.sha1,
|
||||
).digest()
|
||||
signature = base64.b64encode(secreted_string)
|
||||
# print('签名: %s' % signature)
|
||||
# 进行URL编码
|
||||
signature = AccessToken._encode_text(signature)
|
||||
# print('URL编码后的签名: %s' % signature)
|
||||
# 调用服务
|
||||
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
|
||||
signature,
|
||||
query_string,
|
||||
)
|
||||
# print('url: %s' % full_url)
|
||||
# 提交HTTP GET请求
|
||||
response = requests.get(full_url)
|
||||
if response.ok:
|
||||
root_obj = response.json()
|
||||
key = "Token"
|
||||
if key in root_obj:
|
||||
token = root_obj[key]["Id"]
|
||||
expire_time = root_obj[key]["ExpireTime"]
|
||||
return token, expire_time
|
||||
# print(response.text)
|
||||
return None, None
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
"""阿里云ASR初始化"""
|
||||
# 新增空值判断逻辑
|
||||
self.access_key_id = config.get("access_key_id")
|
||||
self.access_key_secret = config.get("access_key_secret")
|
||||
|
||||
self.app_key = config.get("appkey")
|
||||
self.host = "nls-gateway-cn-shanghai.aliyuncs.com"
|
||||
self.base_url = f"https://{self.host}/stream/v1/asr"
|
||||
self.sample_rate = 16000
|
||||
self.format = "wav"
|
||||
self.output_dir = config.get("output_dir", "./audio_output")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
if self.access_key_id and self.access_key_secret:
|
||||
# 使用密钥对生成临时token
|
||||
self._refresh_token()
|
||||
else:
|
||||
# 直接使用预生成的长期token
|
||||
self.token = config.get("token")
|
||||
self.expire_time = None
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
def _refresh_token(self):
|
||||
"""刷新Token并记录过期时间"""
|
||||
if self.access_key_id and self.access_key_secret:
|
||||
self.token, expire_time_str = AccessToken.create_token(
|
||||
self.access_key_id, self.access_key_secret
|
||||
)
|
||||
if not expire_time_str:
|
||||
raise ValueError("无法获取有效的Token过期时间")
|
||||
|
||||
try:
|
||||
# 统一转换为字符串处理
|
||||
expire_str = str(expire_time_str).strip()
|
||||
|
||||
if expire_str.isdigit():
|
||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
||||
else:
|
||||
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
|
||||
self.expire_time = expire_time.timestamp() - 60
|
||||
except Exception as e:
|
||||
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
|
||||
|
||||
else:
|
||||
self.expire_time = None
|
||||
|
||||
if not self.token:
|
||||
raise ValueError("无法获取有效的访问Token")
|
||||
|
||||
def _is_token_expired(self):
|
||||
"""检查Token是否过期"""
|
||||
if not self.expire_time:
|
||||
return False # 长期Token不过期
|
||||
# 新增调试日志
|
||||
# current_time = time.time()
|
||||
# remaining = self.expire_time - current_time
|
||||
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
|
||||
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
|
||||
# f"剩余 {remaining:.2f}秒")
|
||||
return time.time() > self.expire_time
|
||||
|
||||
def _construct_request_url(self) -> str:
|
||||
"""构造请求URL,包含参数"""
|
||||
request = f"{self.base_url}?appkey={self.app_key}"
|
||||
request += f"&format={self.format}"
|
||||
request += f"&sample_rate={self.sample_rate}"
|
||||
request += "&enable_punctuation_prediction=true"
|
||||
request += "&enable_inverse_text_normalization=true"
|
||||
request += "&enable_voice_detection=false"
|
||||
return request
|
||||
|
||||
async def _send_request(self, pcm_data: bytes) -> Optional[str]:
|
||||
"""发送请求到阿里云ASR服务"""
|
||||
try:
|
||||
# 设置HTTP头
|
||||
headers = {
|
||||
"X-NLS-Token": self.token,
|
||||
"Content-type": "application/octet-stream",
|
||||
"Content-Length": str(len(pcm_data)),
|
||||
}
|
||||
|
||||
# 创建连接并发送请求
|
||||
conn = http.client.HTTPSConnection(self.host)
|
||||
request_url = self._construct_request_url()
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(
|
||||
None,
|
||||
lambda: conn.request(
|
||||
method="POST", url=request_url, body=pcm_data, headers=headers
|
||||
),
|
||||
)
|
||||
|
||||
# 获取响应
|
||||
response = await loop.run_in_executor(None, conn.getresponse)
|
||||
body = await loop.run_in_executor(None, response.read)
|
||||
conn.close()
|
||||
|
||||
# 解析响应
|
||||
try:
|
||||
body_json = json.loads(body)
|
||||
status = body_json.get("status")
|
||||
|
||||
if status == 20000000:
|
||||
result = body_json.get("result", "")
|
||||
logger.bind(tag=TAG).debug(f"ASR结果: {result}")
|
||||
return result
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}")
|
||||
return None
|
||||
|
||||
except ValueError:
|
||||
logger.bind(tag=TAG).error("响应不是JSON格式")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""将语音数据转换为文本"""
|
||||
if self._is_token_expired():
|
||||
logger.warning("Token已过期,正在自动刷新...")
|
||||
self._refresh_token()
|
||||
|
||||
file_path = None
|
||||
try:
|
||||
# 解码Opus为PCM
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if self.delete_audio_file:
|
||||
pass
|
||||
else:
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# 发送请求并获取文本
|
||||
text = await self._send_request(combined_pcm_data)
|
||||
|
||||
if text:
|
||||
return text, file_path
|
||||
|
||||
return "", file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||
return "", file_path
|
||||
|
|
@ -1,350 +0,0 @@
|
|||
import json
|
||||
import time
|
||||
import uuid
|
||||
import hmac
|
||||
import base64
|
||||
import hashlib
|
||||
import asyncio
|
||||
import requests
|
||||
import websockets
|
||||
import opuslib_next
|
||||
import random
|
||||
from typing import Optional, Tuple, List
|
||||
from urllib import parse
|
||||
from datetime import datetime
|
||||
from config.logger import setup_logging
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class AccessToken:
|
||||
@staticmethod
|
||||
def _encode_text(text):
|
||||
encoded_text = parse.quote_plus(text)
|
||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
||||
|
||||
@staticmethod
|
||||
def _encode_dict(dic):
|
||||
keys = dic.keys()
|
||||
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
|
||||
encoded_text = parse.urlencode(dic_sorted)
|
||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
||||
|
||||
@staticmethod
|
||||
def create_token(access_key_id, access_key_secret):
|
||||
parameters = {
|
||||
"AccessKeyId": access_key_id,
|
||||
"Action": "CreateToken",
|
||||
"Format": "JSON",
|
||||
"RegionId": "cn-shanghai",
|
||||
"SignatureMethod": "HMAC-SHA1",
|
||||
"SignatureNonce": str(uuid.uuid1()),
|
||||
"SignatureVersion": "1.0",
|
||||
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"Version": "2019-02-28",
|
||||
}
|
||||
query_string = AccessToken._encode_dict(parameters)
|
||||
string_to_sign = (
|
||||
"GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string)
|
||||
)
|
||||
secreted_string = hmac.new(
|
||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
||||
bytes(string_to_sign, encoding="utf-8"),
|
||||
hashlib.sha1,
|
||||
).digest()
|
||||
signature = base64.b64encode(secreted_string)
|
||||
signature = AccessToken._encode_text(signature)
|
||||
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string)
|
||||
response = requests.get(full_url)
|
||||
if response.ok:
|
||||
root_obj = response.json()
|
||||
if "Token" in root_obj:
|
||||
return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"]
|
||||
return None, None
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config, delete_audio_file):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.STREAM
|
||||
self.config = config
|
||||
self.text = ""
|
||||
self.decoder = opuslib_next.Decoder(16000, 1)
|
||||
self.asr_ws = None
|
||||
self.forward_task = None
|
||||
self.is_processing = False
|
||||
self.server_ready = False # 服务器准备状态
|
||||
|
||||
# 基础配置
|
||||
self.access_key_id = config.get("access_key_id")
|
||||
self.access_key_secret = config.get("access_key_secret")
|
||||
self.appkey = config.get("appkey")
|
||||
self.token = config.get("token")
|
||||
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
||||
# 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议
|
||||
if "-internal." in self.host:
|
||||
self.ws_url = f"ws://{self.host}/ws/v1"
|
||||
else:
|
||||
# 默认使用wss协议
|
||||
self.ws_url = f"wss://{self.host}/ws/v1"
|
||||
|
||||
self.max_sentence_silence = config.get("max_sentence_silence")
|
||||
self.output_dir = config.get("output_dir", "./audio_output")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
self.expire_time = None
|
||||
|
||||
self.task_id = uuid.uuid4().hex
|
||||
|
||||
# Token管理
|
||||
if self.access_key_id and self.access_key_secret:
|
||||
self._refresh_token()
|
||||
elif not self.token:
|
||||
raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token")
|
||||
|
||||
def _refresh_token(self):
|
||||
"""刷新Token"""
|
||||
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
|
||||
if not self.token:
|
||||
raise ValueError("无法获取有效的访问Token")
|
||||
|
||||
try:
|
||||
expire_str = str(expire_time_str).strip()
|
||||
if expire_str.isdigit():
|
||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
||||
else:
|
||||
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
|
||||
self.expire_time = expire_time.timestamp() - 60
|
||||
except:
|
||||
self.expire_time = None
|
||||
|
||||
def _is_token_expired(self):
|
||||
"""检查Token是否过期"""
|
||||
return self.expire_time and time.time() > self.expire_time
|
||||
|
||||
async def open_audio_channels(self, conn):
|
||||
await super().open_audio_channels(conn)
|
||||
|
||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||
# 初始化音频缓存
|
||||
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
|
||||
# 存储音频数据
|
||||
if audio:
|
||||
conn.asr_audio_for_voiceprint.append(audio)
|
||||
|
||||
conn.asr_audio.append(audio)
|
||||
conn.asr_audio = conn.asr_audio[-10:]
|
||||
|
||||
# 只在有声音且没有连接时建立连接
|
||||
if audio_have_voice and not self.is_processing:
|
||||
try:
|
||||
await self._start_recognition(conn)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}")
|
||||
await self._cleanup(conn)
|
||||
return
|
||||
|
||||
if self.asr_ws and self.is_processing and self.server_ready:
|
||||
try:
|
||||
pcm_frame = self.decoder.decode(audio, 960)
|
||||
await self.asr_ws.send(pcm_frame)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
|
||||
await self._cleanup(conn)
|
||||
|
||||
async def _start_recognition(self, conn):
|
||||
"""开始识别会话"""
|
||||
if self._is_token_expired():
|
||||
self._refresh_token()
|
||||
|
||||
# 建立连接
|
||||
headers = {"X-NLS-Token": self.token}
|
||||
self.asr_ws = await websockets.connect(
|
||||
self.ws_url,
|
||||
additional_headers=headers,
|
||||
max_size=1000000000,
|
||||
ping_interval=None,
|
||||
ping_timeout=None,
|
||||
close_timeout=5,
|
||||
)
|
||||
|
||||
self.task_id = uuid.uuid4().hex
|
||||
|
||||
logger.bind(tag=TAG).info(f"WebSocket连接建立成功, task_id: {self.task_id}")
|
||||
|
||||
self.is_processing = True
|
||||
self.server_ready = False # 重置服务器准备状态
|
||||
self.forward_task = asyncio.create_task(self._forward_results(conn))
|
||||
|
||||
# 发送开始请求
|
||||
start_request = {
|
||||
"header": {
|
||||
"namespace": "SpeechTranscriber",
|
||||
"name": "StartTranscription",
|
||||
"status": 20000000,
|
||||
"message_id": uuid.uuid4().hex,
|
||||
"task_id": self.task_id,
|
||||
"status_text": "Gateway:SUCCESS:Success.",
|
||||
"appkey": self.appkey
|
||||
},
|
||||
"payload": {
|
||||
"format": "pcm",
|
||||
"sample_rate": 16000,
|
||||
"enable_intermediate_result": True,
|
||||
"enable_punctuation_prediction": True,
|
||||
"enable_inverse_text_normalization": True,
|
||||
"max_sentence_silence": self.max_sentence_silence,
|
||||
"enable_voice_detection": False,
|
||||
}
|
||||
}
|
||||
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
|
||||
logger.bind(tag=TAG).info("已发送开始请求,等待服务器准备...")
|
||||
|
||||
async def _forward_results(self, conn):
|
||||
"""转发识别结果"""
|
||||
try:
|
||||
while self.asr_ws and not conn.stop_event.is_set():
|
||||
try:
|
||||
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
|
||||
result = json.loads(response)
|
||||
|
||||
header = result.get("header", {})
|
||||
payload = result.get("payload", {})
|
||||
message_name = header.get("name", "")
|
||||
status = header.get("status", 0)
|
||||
|
||||
if status != 20000000:
|
||||
if status in [40000004, 40010004]: # 连接超时或客户端断开
|
||||
logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}")
|
||||
break
|
||||
elif status in [40270002, 40270003]: # 音频问题
|
||||
logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}")
|
||||
continue
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}")
|
||||
continue
|
||||
|
||||
# 收到TranscriptionStarted表示服务器准备好接收音频数据
|
||||
if message_name == "TranscriptionStarted":
|
||||
self.server_ready = True
|
||||
logger.bind(tag=TAG).info("服务器已准备,开始发送缓存音频...")
|
||||
|
||||
# 发送缓存音频
|
||||
if conn.asr_audio:
|
||||
for cached_audio in conn.asr_audio[-10:]:
|
||||
try:
|
||||
pcm_frame = self.decoder.decode(cached_audio, 960)
|
||||
await self.asr_ws.send(pcm_frame)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
|
||||
break
|
||||
continue
|
||||
|
||||
if message_name == "TranscriptionResultChanged":
|
||||
# 中间结果
|
||||
text = payload.get("result", "")
|
||||
if text:
|
||||
self.text = text
|
||||
elif message_name == "SentenceEnd":
|
||||
# 最终结果
|
||||
text = payload.get("result", "")
|
||||
if text:
|
||||
self.text = text
|
||||
conn.reset_vad_states()
|
||||
# 传递缓存的音频数据
|
||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
||||
await self.handle_voice_stop(conn, audio_data)
|
||||
# 清空缓存
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
break
|
||||
elif message_name == "TranscriptionCompleted":
|
||||
# 识别完成
|
||||
self.is_processing = False
|
||||
break
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}")
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
|
||||
finally:
|
||||
await self._cleanup(conn)
|
||||
|
||||
async def _cleanup(self, conn):
|
||||
"""清理资源"""
|
||||
logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
|
||||
|
||||
# 清理连接的音频缓存
|
||||
if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
|
||||
# 判断是否需要发送终止请求
|
||||
should_stop = self.is_processing or self.server_ready
|
||||
|
||||
# 发送停止识别请求
|
||||
if self.asr_ws and should_stop:
|
||||
try:
|
||||
stop_msg = {
|
||||
"header": {
|
||||
"namespace": "SpeechTranscriber",
|
||||
"name": "StopTranscription",
|
||||
"status": 20000000,
|
||||
"message_id": uuid.uuid4().hex,
|
||||
"task_id": self.task_id,
|
||||
"status_text": "Client:Stop",
|
||||
"appkey": self.appkey
|
||||
}
|
||||
}
|
||||
logger.bind(tag=TAG).info("正在发送ASR终止请求")
|
||||
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
|
||||
await asyncio.sleep(0.1)
|
||||
logger.bind(tag=TAG).info("ASR终止请求已发送")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"ASR终止请求发送失败: {e}")
|
||||
|
||||
# 状态重置(在终止请求发送后)
|
||||
self.is_processing = False
|
||||
self.server_ready = False
|
||||
logger.bind(tag=TAG).info("ASR状态已重置")
|
||||
|
||||
# 清理任务
|
||||
if self.forward_task and not self.forward_task.done():
|
||||
self.forward_task.cancel()
|
||||
try:
|
||||
await asyncio.wait_for(self.forward_task, timeout=1.0)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}")
|
||||
finally:
|
||||
self.forward_task = None
|
||||
|
||||
# 关闭连接
|
||||
if self.asr_ws:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
|
||||
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
|
||||
logger.bind(tag=TAG).debug("WebSocket连接已关闭")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
|
||||
finally:
|
||||
self.asr_ws = None
|
||||
|
||||
logger.bind(tag=TAG).info("ASR会话清理完成")
|
||||
|
||||
async def speech_to_text(self, opus_data, session_id, audio_format):
|
||||
"""获取识别结果"""
|
||||
result = self.text
|
||||
self.text = ""
|
||||
return result, None
|
||||
|
||||
async def close(self):
|
||||
"""关闭资源"""
|
||||
await self._cleanup()
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
import time
|
||||
import os
|
||||
from typing import Optional, Tuple, List
|
||||
from aip import AipSpeech
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from config.logger import setup_logging
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool = True):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
self.app_id = config.get("app_id")
|
||||
self.api_key = config.get("api_key")
|
||||
self.secret_key = config.get("secret_key")
|
||||
|
||||
dev_pid = config.get("dev_pid", "1537")
|
||||
self.dev_pid = int(dev_pid) if dev_pid else 1537
|
||||
|
||||
self.output_dir = config.get("output_dir")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key)
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""将语音数据转换为文本"""
|
||||
if not opus_data:
|
||||
logger.bind(tag=TAG).warning("音频数据为空!")
|
||||
return None, None
|
||||
|
||||
file_path = None
|
||||
try:
|
||||
# 检查配置是否已设置
|
||||
if not self.app_id or not self.api_key or not self.secret_key:
|
||||
logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别")
|
||||
return None, file_path
|
||||
|
||||
# 将Opus音频数据解码为PCM
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if self.delete_audio_file:
|
||||
pass
|
||||
else:
|
||||
self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
start_time = time.time()
|
||||
# 识别本地文件
|
||||
result = self.client.asr(
|
||||
combined_pcm_data,
|
||||
"pcm",
|
||||
16000,
|
||||
{
|
||||
"dev_pid": str(self.dev_pid),
|
||||
},
|
||||
)
|
||||
|
||||
if result and result["err_no"] == 0:
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
|
||||
)
|
||||
result = result["result"][0]
|
||||
return result, file_path
|
||||
else:
|
||||
raise Exception(
|
||||
f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}"
|
||||
)
|
||||
return None, file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
|
||||
return None, file_path
|
||||
|
|
@ -252,27 +252,20 @@ class ASRProviderBase(ABC):
|
|||
self.stop_ws_connection()
|
||||
|
||||
if text_len > 0:
|
||||
# Turn Detection: check if user finished speaking
|
||||
if conn.turn_detection:
|
||||
end_of_turn, full_text = await conn.turn_detection.check_end_of_turn(raw_text)
|
||||
|
||||
if not end_of_turn:
|
||||
# User hasn't finished, continue waiting for more speech
|
||||
logger.bind(tag=TAG).info(f"User hasn't finished, continue waiting for more speech")
|
||||
return
|
||||
|
||||
# Use accumulated text from turn detection
|
||||
enhanced_text = self._build_enhanced_text(full_text, speaker_name)
|
||||
# Append to ASR text buffer
|
||||
if conn.asr_text_buffer:
|
||||
conn.asr_text_buffer += " " + raw_text
|
||||
else:
|
||||
# No Turn Detection: use single segment text
|
||||
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
|
||||
conn.asr_text_buffer = raw_text
|
||||
|
||||
asr_report_time = int(time.time())
|
||||
# Turn Detection: let turn detection handle end of turn
|
||||
if conn.turn_detection:
|
||||
# Turn detection will wait for endpoint delay, then call on_end_of_turn
|
||||
conn.turn_detection.check_end_of_turn(conn)
|
||||
return
|
||||
|
||||
await startToChat(conn, enhanced_text)
|
||||
# Note: For report, we need to convert PCM back to opus or use PCM directly
|
||||
# For now, pass empty list as audio data for report
|
||||
enqueue_asr_report(conn, enhanced_text, [], report_time=asr_report_time)
|
||||
# No Turn Detection: process immediately
|
||||
await conn.on_end_of_turn()
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Process speech segment failed: {e}")
|
||||
|
|
|
|||
|
|
@ -1,271 +0,0 @@
|
|||
import time
|
||||
import os
|
||||
import uuid
|
||||
import json
|
||||
import gzip
|
||||
import websockets
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
CLIENT_FULL_REQUEST = 0b0001
|
||||
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
|
||||
|
||||
NO_SEQUENCE = 0b0000
|
||||
NEG_SEQUENCE = 0b0010
|
||||
|
||||
SERVER_FULL_RESPONSE = 0b1001
|
||||
SERVER_ACK = 0b1011
|
||||
SERVER_ERROR_RESPONSE = 0b1111
|
||||
|
||||
NO_SERIALIZATION = 0b0000
|
||||
JSON = 0b0001
|
||||
THRIFT = 0b0011
|
||||
CUSTOM_TYPE = 0b1111
|
||||
NO_COMPRESSION = 0b0000
|
||||
GZIP = 0b0001
|
||||
CUSTOM_COMPRESSION = 0b1111
|
||||
|
||||
|
||||
def parse_response(res):
|
||||
"""
|
||||
protocol_version(4 bits), header_size(4 bits),
|
||||
message_type(4 bits), message_type_specific_flags(4 bits)
|
||||
serialization_method(4 bits) message_compression(4 bits)
|
||||
reserved (8bits) 保留字段
|
||||
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
|
||||
payload 类似与http 请求体
|
||||
"""
|
||||
protocol_version = res[0] >> 4
|
||||
header_size = res[0] & 0x0F
|
||||
message_type = res[1] >> 4
|
||||
message_type_specific_flags = res[1] & 0x0F
|
||||
serialization_method = res[2] >> 4
|
||||
message_compression = res[2] & 0x0F
|
||||
reserved = res[3]
|
||||
header_extensions = res[4 : header_size * 4]
|
||||
payload = res[header_size * 4 :]
|
||||
result = {}
|
||||
payload_msg = None
|
||||
payload_size = 0
|
||||
if message_type == SERVER_FULL_RESPONSE:
|
||||
payload_size = int.from_bytes(payload[:4], "big", signed=True)
|
||||
payload_msg = payload[4:]
|
||||
elif message_type == SERVER_ACK:
|
||||
seq = int.from_bytes(payload[:4], "big", signed=True)
|
||||
result["seq"] = seq
|
||||
if len(payload) >= 8:
|
||||
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
||||
payload_msg = payload[8:]
|
||||
elif message_type == SERVER_ERROR_RESPONSE:
|
||||
code = int.from_bytes(payload[:4], "big", signed=False)
|
||||
result["code"] = code
|
||||
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
||||
payload_msg = payload[8:]
|
||||
if payload_msg is None:
|
||||
return result
|
||||
if message_compression == GZIP:
|
||||
payload_msg = gzip.decompress(payload_msg)
|
||||
if serialization_method == JSON:
|
||||
payload_msg = json.loads(str(payload_msg, "utf-8"))
|
||||
elif serialization_method != NO_SERIALIZATION:
|
||||
payload_msg = str(payload_msg, "utf-8")
|
||||
result["payload_msg"] = payload_msg
|
||||
result["payload_size"] = payload_size
|
||||
return result
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
self.appid = config.get("appid")
|
||||
self.cluster = config.get("cluster")
|
||||
self.access_token = config.get("access_token")
|
||||
self.boosting_table_name = config.get("boosting_table_name", "")
|
||||
self.correct_table_name = config.get("correct_table_name", "")
|
||||
self.output_dir = config.get("output_dir")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
self.host = "openspeech.bytedance.com"
|
||||
self.ws_url = f"wss://{self.host}/api/v2/asr"
|
||||
self.success_code = 1000
|
||||
self.seg_duration = 15000
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def _generate_header(
|
||||
message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE
|
||||
) -> bytearray:
|
||||
"""Generate protocol header."""
|
||||
header = bytearray()
|
||||
header_size = 1
|
||||
header.append((0b0001 << 4) | header_size) # Protocol version
|
||||
header.append((message_type << 4) | message_type_specific_flags)
|
||||
header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression
|
||||
header.append(0x00) # reserved
|
||||
return header
|
||||
|
||||
def _construct_request(self, reqid) -> dict:
|
||||
"""Construct the request payload."""
|
||||
return {
|
||||
"app": {
|
||||
"appid": f"{self.appid}",
|
||||
"cluster": self.cluster,
|
||||
"token": self.access_token,
|
||||
},
|
||||
"user": {
|
||||
"uid": str(uuid.uuid4()),
|
||||
},
|
||||
"request": {
|
||||
"reqid": reqid,
|
||||
"show_utterances": False,
|
||||
"sequence": 1,
|
||||
"boosting_table_name": self.boosting_table_name,
|
||||
"correct_table_name": self.correct_table_name,
|
||||
},
|
||||
"audio": {
|
||||
"format": "raw",
|
||||
"rate": 16000,
|
||||
"language": "zh-CN",
|
||||
"bits": 16,
|
||||
"channel": 1,
|
||||
"codec": "raw",
|
||||
},
|
||||
}
|
||||
|
||||
async def _send_request(
|
||||
self, audio_data: List[bytes], segment_size: int
|
||||
) -> Optional[str]:
|
||||
"""Send request to Volcano ASR service."""
|
||||
try:
|
||||
auth_header = {"Authorization": "Bearer; {}".format(self.access_token)}
|
||||
async with websockets.connect(
|
||||
self.ws_url, additional_headers=auth_header
|
||||
) as websocket:
|
||||
# Prepare request data
|
||||
request_params = self._construct_request(str(uuid.uuid4()))
|
||||
payload_bytes = str.encode(json.dumps(request_params))
|
||||
payload_bytes = gzip.compress(payload_bytes)
|
||||
full_client_request = self._generate_header()
|
||||
full_client_request.extend(
|
||||
(len(payload_bytes)).to_bytes(4, "big")
|
||||
) # payload size(4 bytes)
|
||||
full_client_request.extend(payload_bytes) # payload
|
||||
|
||||
# Send header and metadata
|
||||
# full_client_request
|
||||
await websocket.send(full_client_request)
|
||||
res = await websocket.recv()
|
||||
result = parse_response(res)
|
||||
if (
|
||||
"payload_msg" in result
|
||||
and result["payload_msg"]["code"] != self.success_code
|
||||
and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误
|
||||
):
|
||||
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||
return None
|
||||
|
||||
for seq, (chunk, last) in enumerate(
|
||||
self.slice_data(audio_data, segment_size), 1
|
||||
):
|
||||
if last:
|
||||
audio_only_request = self._generate_header(
|
||||
message_type=CLIENT_AUDIO_ONLY_REQUEST,
|
||||
message_type_specific_flags=NEG_SEQUENCE,
|
||||
)
|
||||
else:
|
||||
audio_only_request = self._generate_header(
|
||||
message_type=CLIENT_AUDIO_ONLY_REQUEST
|
||||
)
|
||||
payload_bytes = gzip.compress(chunk)
|
||||
audio_only_request.extend(
|
||||
(len(payload_bytes)).to_bytes(4, "big")
|
||||
) # payload size(4 bytes)
|
||||
audio_only_request.extend(payload_bytes) # payload
|
||||
# Send audio data
|
||||
await websocket.send(audio_only_request)
|
||||
|
||||
# Receive response
|
||||
response = await websocket.recv()
|
||||
result = parse_response(response)
|
||||
|
||||
if (
|
||||
"payload_msg" in result
|
||||
and result["payload_msg"]["code"] == self.success_code
|
||||
):
|
||||
if len(result["payload_msg"]["result"]) > 0:
|
||||
return result["payload_msg"]["result"][0]["text"]
|
||||
return None
|
||||
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
|
||||
# 无有效语音,返回空字符串
|
||||
return ""
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def slice_data(data: bytes, chunk_size: int) -> (list, bool):
|
||||
"""
|
||||
slice data
|
||||
:param data: wav data
|
||||
:param chunk_size: the segment size in one request
|
||||
:return: segment data, last flag
|
||||
"""
|
||||
data_len = len(data)
|
||||
offset = 0
|
||||
while offset + chunk_size < data_len:
|
||||
yield data[offset : offset + chunk_size], False
|
||||
offset += chunk_size
|
||||
else:
|
||||
yield data[offset:data_len], True
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""将语音数据转换为文本"""
|
||||
|
||||
file_path = None
|
||||
try:
|
||||
# 合并所有opus数据包
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if self.delete_audio_file:
|
||||
pass
|
||||
else:
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# 直接使用PCM数据
|
||||
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
|
||||
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
|
||||
segment_size = int(size_per_sec * self.seg_duration / 1000)
|
||||
|
||||
# 语音识别
|
||||
start_time = time.time()
|
||||
text = await self._send_request(combined_pcm_data, segment_size)
|
||||
if text:
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
|
||||
)
|
||||
return text, file_path
|
||||
return "", file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||
return "", file_path
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
import time
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
import psutil
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from funasr import AutoModel
|
||||
from funasr.utils.postprocess_utils import rich_transcription_postprocess
|
||||
import shutil
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
MAX_RETRIES = 2
|
||||
RETRY_DELAY = 1 # 重试延迟(秒)
|
||||
|
||||
|
||||
# 捕获标准输出
|
||||
class CaptureOutput:
|
||||
def __enter__(self):
|
||||
self._output = io.StringIO()
|
||||
self._original_stdout = sys.stdout
|
||||
sys.stdout = self._output
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
sys.stdout = self._original_stdout
|
||||
self.output = self._output.getvalue()
|
||||
self._output.close()
|
||||
|
||||
# 将捕获到的内容通过 logger 输出
|
||||
if self.output:
|
||||
logger.bind(tag=TAG).info(self.output.strip())
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__()
|
||||
|
||||
# 内存检测,要求大于2G
|
||||
min_mem_bytes = 2 * 1024 * 1024 * 1024
|
||||
total_mem = psutil.virtual_memory().total
|
||||
if total_mem < min_mem_bytes:
|
||||
logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR")
|
||||
|
||||
self.interface_type = InterfaceType.LOCAL
|
||||
self.model_dir = config.get("model_dir")
|
||||
self.output_dir = config.get("output_dir") # 修正配置键名
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
with CaptureOutput():
|
||||
self.model = AutoModel(
|
||||
model=self.model_dir,
|
||||
vad_kwargs={"max_single_segment_time": 30000},
|
||||
disable_update=True,
|
||||
hub="hf",
|
||||
# device="cuda:0", # 启用GPU加速
|
||||
)
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""语音转文本主处理逻辑"""
|
||||
file_path = None
|
||||
retry_count = 0
|
||||
|
||||
while retry_count < MAX_RETRIES:
|
||||
try:
|
||||
# 合并所有opus数据包
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 检查磁盘空间
|
||||
if not self.delete_audio_file:
|
||||
free_space = shutil.disk_usage(self.output_dir).free
|
||||
if free_space < len(combined_pcm_data) * 2: # 预留2倍空间
|
||||
raise OSError("磁盘空间不足")
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if self.delete_audio_file:
|
||||
pass
|
||||
else:
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# 语音识别
|
||||
start_time = time.time()
|
||||
result = self.model.generate(
|
||||
input=combined_pcm_data,
|
||||
cache={},
|
||||
language="auto",
|
||||
use_itn=True,
|
||||
batch_size_s=60,
|
||||
)
|
||||
text = rich_transcription_postprocess(result[0]["text"])
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
|
||||
)
|
||||
|
||||
return text, file_path
|
||||
|
||||
except OSError as e:
|
||||
retry_count += 1
|
||||
if retry_count >= MAX_RETRIES:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
|
||||
)
|
||||
return "", file_path
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
|
||||
)
|
||||
time.sleep(RETRY_DELAY)
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||
return "", file_path
|
||||
|
||||
finally:
|
||||
# 文件清理逻辑
|
||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||
try:
|
||||
os.remove(file_path)
|
||||
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"文件删除失败: {file_path} | 错误: {e}"
|
||||
)
|
||||
|
|
@ -1,169 +0,0 @@
|
|||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
import ssl
|
||||
import json
|
||||
import websockets
|
||||
from config.logger import setup_logging
|
||||
import asyncio
|
||||
import re
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
"""
|
||||
Initialize the ASRProvider with server configuration.
|
||||
:param config: Dictionary containing 'host', 'port', and 'is_ssl'.
|
||||
:param delete_audio_file: Boolean to indicate whether to delete audio files after processing.
|
||||
"""
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
self.host = config.get("host", "localhost")
|
||||
self.port = config.get("port", 10095)
|
||||
self.api_key = config.get("api_key", "none")
|
||||
self.is_ssl = str(config.get("is_ssl", True)).lower() in (
|
||||
"true",
|
||||
"1",
|
||||
"yes",
|
||||
)
|
||||
self.output_dir = config.get("output_dir")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
self.uri = (
|
||||
f"wss://{self.host}:{self.port}"
|
||||
if self.is_ssl
|
||||
else f"ws://{self.host}:{self.port}"
|
||||
)
|
||||
self.ssl_context = ssl.SSLContext() if self.is_ssl else None
|
||||
if self.ssl_context:
|
||||
self.ssl_context.check_hostname = False
|
||||
self.ssl_context.verify_mode = ssl.CERT_NONE
|
||||
|
||||
async def _receive_responses(self, ws) -> None:
|
||||
"""
|
||||
Asynchronous generator to receive messages from the WebSocket.
|
||||
Yields each message as it is received.
|
||||
"""
|
||||
text = ""
|
||||
while True:
|
||||
try:
|
||||
response = await asyncio.wait_for(ws.recv(), timeout=5)
|
||||
response_data = json.loads(response)
|
||||
logger.bind(tag=TAG).debug(f"Received response: {response_data}")
|
||||
if response_data.get("is_final", True):
|
||||
text += response_data.get("text", "")
|
||||
break
|
||||
else:
|
||||
text += response_data.get("text", "")
|
||||
except asyncio.TimeoutError:
|
||||
logger.bind(tag=TAG).error(
|
||||
"Timeout while waiting for response from WebSocket."
|
||||
)
|
||||
break
|
||||
except websockets.exceptions.ConnectionClosed as e:
|
||||
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
|
||||
break
|
||||
return text
|
||||
|
||||
async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple:
|
||||
"""
|
||||
Internal method to handle WebSocket communication.
|
||||
Reuses the persistent WebSocket connection if available.
|
||||
:param pcm_data: PCM audio data to send.
|
||||
:param session_id: Unique session identifier.
|
||||
:return: Tuple containing recognized text and optional timestamp.
|
||||
"""
|
||||
|
||||
# Send initial configuration message
|
||||
config_message = json.dumps(
|
||||
{
|
||||
"mode": "offline",
|
||||
"chunk_size": [5, 10, 5],
|
||||
"chunk_interval": 10,
|
||||
"wav_name": session_id,
|
||||
"is_speaking": True,
|
||||
"itn": False,
|
||||
}
|
||||
)
|
||||
await ws.send(config_message)
|
||||
logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}")
|
||||
|
||||
# Send PCM data
|
||||
await ws.send(pcm_data)
|
||||
logger.bind(tag=TAG).debug(f"Sent PCM data of length: {len(pcm_data)} bytes")
|
||||
|
||||
# Indicate end of speech
|
||||
end_message = json.dumps({"is_speaking": False})
|
||||
await ws.send(end_message)
|
||||
logger.bind(tag=TAG).debug(f"Sent end message: {end_message}")
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
Convert speech data to text using FunASR.
|
||||
:param opus_data: List of Opus-encoded audio data chunks.
|
||||
:param session_id: Unique session identifier.
|
||||
:return: Tuple containing recognized text and optional timestamp.
|
||||
"""
|
||||
file_path = None
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if self.delete_audio_file:
|
||||
pass
|
||||
else:
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
|
||||
async with websockets.connect(
|
||||
self.uri,
|
||||
additional_headers=auth_header,
|
||||
subprotocols=["binary"],
|
||||
ping_interval=None,
|
||||
ssl=self.ssl_context,
|
||||
) as ws:
|
||||
try:
|
||||
# Use asyncio to handle WebSocket communication
|
||||
send_task = asyncio.create_task(
|
||||
self._send_data(ws, combined_pcm_data, session_id)
|
||||
)
|
||||
receive_task = asyncio.create_task(self._receive_responses(ws))
|
||||
|
||||
# Gather tasks with error handling
|
||||
done, pending = await asyncio.wait(
|
||||
[send_task, receive_task], return_when=asyncio.FIRST_EXCEPTION
|
||||
)
|
||||
|
||||
# Cancel any pending tasks
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
|
||||
# Check for exceptions in completed tasks
|
||||
for task in done:
|
||||
if task.exception():
|
||||
raise task.exception()
|
||||
|
||||
# Get the result from the receive task
|
||||
result = receive_task.result()
|
||||
match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result)
|
||||
if match:
|
||||
result = match.group(4).strip()
|
||||
return (
|
||||
result,
|
||||
file_path,
|
||||
) # Return the recognized text and timestamp (if any)
|
||||
|
||||
except websockets.exceptions.ConnectionClosed as e:
|
||||
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
|
||||
return "", file_path
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"Error during speech-to-text conversion: {e}", exc_info=True
|
||||
)
|
||||
return "", file_path
|
||||
|
|
@ -21,6 +21,7 @@ class ASRProvider(ASRProviderBase):
|
|||
self.model = config.get("model_name")
|
||||
self.output_dir = config.get("output_dir")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
self.prompt = config.get("prompt", None)
|
||||
|
||||
self._client = OpenAI(
|
||||
api_key=self.api_key,
|
||||
|
|
@ -49,7 +50,8 @@ class ASRProvider(ASRProviderBase):
|
|||
transcription: str = self._client.audio.transcriptions.create(
|
||||
model=self.model,
|
||||
file=audio_file,
|
||||
response_format="text"
|
||||
response_format="text",
|
||||
prompt=self.prompt if self.prompt else None,
|
||||
)
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription}"
|
||||
|
|
|
|||
|
|
@ -1,169 +0,0 @@
|
|||
import os
|
||||
import json
|
||||
import asyncio
|
||||
import tempfile
|
||||
import difflib
|
||||
from typing import Optional, Tuple, List
|
||||
import dashscope
|
||||
from config.logger import setup_logging
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
tag = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.STREAM
|
||||
"""Qwen3-ASR-Flash ASR初始化"""
|
||||
|
||||
# 配置参数
|
||||
self.api_key = config.get("api_key")
|
||||
if not self.api_key:
|
||||
raise ValueError("Qwen3-ASR-Flash 需要配置 api_key")
|
||||
|
||||
self.model_name = config.get("model_name", "qwen3-asr-flash")
|
||||
self.output_dir = config.get("output_dir", "./audio_output")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# ASR选项配置
|
||||
self.enable_lid = config.get("enable_lid", True) # 自动语种检测
|
||||
self.enable_itn = config.get("enable_itn", True) # 逆文本归一化
|
||||
self.language = config.get("language", None) # 指定语种,默认自动检测
|
||||
self.context = config.get("context", "") # 上下文信息,用于提高识别准确率
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
def _prepare_audio_file(self, pcm_data: bytes) -> str:
|
||||
"""将PCM数据转换为WAV文件并返回文件路径"""
|
||||
try:
|
||||
import wave
|
||||
|
||||
# 创建临时WAV文件
|
||||
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
# 写入WAV格式
|
||||
with wave.open(temp_path, 'wb') as wav_file:
|
||||
wav_file.setnchannels(1) # 单声道
|
||||
wav_file.setsampwidth(2) # 16位
|
||||
wav_file.setframerate(16000) # 16kHz采样率
|
||||
wav_file.writeframes(pcm_data)
|
||||
|
||||
return temp_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=tag).error(f"音频文件准备失败: {e}")
|
||||
return None
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""将语音数据转换为文本"""
|
||||
temp_file_path = None
|
||||
file_path = None
|
||||
|
||||
try:
|
||||
# 解码音频数据
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
if len(combined_pcm_data) == 0:
|
||||
logger.bind(tag=tag).warning("音频数据为空")
|
||||
return "", None
|
||||
|
||||
# 准备音频文件
|
||||
temp_file_path = self._prepare_audio_file(combined_pcm_data)
|
||||
if not temp_file_path:
|
||||
return "", None
|
||||
|
||||
# 保存音频文件(如果需要)
|
||||
if not self.delete_audio_file:
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# 构造请求消息
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"audio": temp_file_path}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
# 如果有上下文信息,添加system消息
|
||||
if self.context:
|
||||
messages.insert(0, {
|
||||
"role": "system",
|
||||
"content": [
|
||||
{"text": self.context}
|
||||
]
|
||||
})
|
||||
|
||||
# 准备ASR选项
|
||||
asr_options = {
|
||||
"enable_lid": self.enable_lid,
|
||||
"enable_itn": self.enable_itn
|
||||
}
|
||||
|
||||
# 如果指定了语种,添加到选项中
|
||||
if self.language:
|
||||
asr_options["language"] = self.language
|
||||
|
||||
# 设置API密钥
|
||||
dashscope.api_key = self.api_key
|
||||
|
||||
# 发送流式请求
|
||||
response = dashscope.MultiModalConversation.call(
|
||||
model=self.model_name,
|
||||
messages=messages,
|
||||
result_format="message",
|
||||
asr_options=asr_options,
|
||||
stream=True
|
||||
)
|
||||
|
||||
# 处理流式响应
|
||||
full_text = ""
|
||||
last_text = "" # 用于存储上一个文本片段
|
||||
for chunk in response:
|
||||
try:
|
||||
text = chunk["output"]["choices"][0]["message"].content[0]["text"]
|
||||
# 标准化文本片段(去除首尾空格)
|
||||
normalized_text = text.strip()
|
||||
# 只有当新文本片段与上一个不同时才处理
|
||||
if normalized_text != last_text:
|
||||
# 提取新增的文本部分
|
||||
# 通过比较当前文本和上一个文本,找到新增的部分
|
||||
if normalized_text.startswith(last_text):
|
||||
# 如果当前文本以最后一个文本开头,则新增部分是两者的差集
|
||||
new_part = normalized_text[len(last_text):]
|
||||
else:
|
||||
# 如果不以最后一个文本开头,说明识别结果发生了较大变化,直接使用当前文本
|
||||
new_part = normalized_text
|
||||
|
||||
# 将新增部分添加到完整文本中
|
||||
full_text += new_part
|
||||
last_text = normalized_text
|
||||
# 这里可以实时处理文本片段,例如通过回调函数
|
||||
except:
|
||||
pass
|
||||
|
||||
return full_text, file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=tag).error(f"语音识别失败: {e}")
|
||||
return "", file_path
|
||||
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if temp_file_path and os.path.exists(temp_file_path):
|
||||
try:
|
||||
os.unlink(temp_file_path)
|
||||
except Exception as e:
|
||||
logger.bind(tag=tag).warning(f"清理临时文件失败: {e}")
|
||||
|
|
@ -1,163 +0,0 @@
|
|||
import time
|
||||
import wave
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
|
||||
import numpy as np
|
||||
import sherpa_onnx
|
||||
|
||||
from modelscope.hub.file_download import model_file_download
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
# 捕获标准输出
|
||||
class CaptureOutput:
|
||||
def __enter__(self):
|
||||
self._output = io.StringIO()
|
||||
self._original_stdout = sys.stdout
|
||||
sys.stdout = self._output
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
sys.stdout = self._original_stdout
|
||||
self.output = self._output.getvalue()
|
||||
self._output.close()
|
||||
|
||||
# 将捕获到的内容通过 logger 输出
|
||||
if self.output:
|
||||
logger.bind(tag=TAG).info(self.output.strip())
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.LOCAL
|
||||
self.model_dir = config.get("model_dir")
|
||||
self.output_dir = config.get("output_dir")
|
||||
self.model_type = config.get("model_type", "sense_voice") # 支持 paraformer
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
# 初始化模型文件路径
|
||||
model_files = {
|
||||
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
|
||||
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
||||
}
|
||||
|
||||
# 下载并检查模型文件
|
||||
try:
|
||||
for file_name, file_path in model_files.items():
|
||||
if not os.path.isfile(file_path):
|
||||
logger.bind(tag=TAG).info(f"正在下载模型文件: {file_name}")
|
||||
model_file_download(
|
||||
model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue",
|
||||
file_path=file_name,
|
||||
local_dir=self.model_dir,
|
||||
)
|
||||
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"模型文件下载失败: {file_path}")
|
||||
|
||||
self.model_path = model_files["model.int8.onnx"]
|
||||
self.tokens_path = model_files["tokens.txt"]
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"模型文件处理失败: {str(e)}")
|
||||
raise
|
||||
|
||||
with CaptureOutput():
|
||||
if self.model_type == "paraformer":
|
||||
self.model = sherpa_onnx.OfflineRecognizer.from_paraformer(
|
||||
paraformer=self.model_path,
|
||||
tokens=self.tokens_path,
|
||||
num_threads=2,
|
||||
sample_rate=16000,
|
||||
feature_dim=80,
|
||||
decoding_method="greedy_search",
|
||||
debug=False,
|
||||
)
|
||||
else: # sense_voice
|
||||
self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice(
|
||||
model=self.model_path,
|
||||
tokens=self.tokens_path,
|
||||
num_threads=2,
|
||||
sample_rate=16000,
|
||||
feature_dim=80,
|
||||
decoding_method="greedy_search",
|
||||
debug=False,
|
||||
use_itn=True,
|
||||
)
|
||||
|
||||
def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
|
||||
"""
|
||||
Args:
|
||||
wave_filename:
|
||||
Path to a wave file. It should be single channel and each sample should
|
||||
be 16-bit. Its sample rate does not need to be 16kHz.
|
||||
Returns:
|
||||
Return a tuple containing:
|
||||
- A 1-D array of dtype np.float32 containing the samples, which are
|
||||
normalized to the range [-1, 1].
|
||||
- sample rate of the wave file
|
||||
"""
|
||||
|
||||
with wave.open(wave_filename) as f:
|
||||
assert f.getnchannels() == 1, f.getnchannels()
|
||||
assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes
|
||||
num_samples = f.getnframes()
|
||||
samples = f.readframes(num_samples)
|
||||
samples_int16 = np.frombuffer(samples, dtype=np.int16)
|
||||
samples_float32 = samples_int16.astype(np.float32)
|
||||
|
||||
samples_float32 = samples_float32 / 32768
|
||||
return samples_float32, f.getframerate()
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""语音转文本主处理逻辑"""
|
||||
file_path = None
|
||||
try:
|
||||
# 保存音频文件
|
||||
start_time = time.time()
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}"
|
||||
)
|
||||
|
||||
# 语音识别
|
||||
start_time = time.time()
|
||||
s = self.model.create_stream()
|
||||
samples, sample_rate = self.read_wave(file_path)
|
||||
s.accept_waveform(sample_rate, samples)
|
||||
self.model.decode_stream(s)
|
||||
text = s.result.text
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
|
||||
)
|
||||
|
||||
return text, file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||
return "", file_path
|
||||
finally:
|
||||
# 文件清理逻辑
|
||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||
try:
|
||||
os.remove(file_path)
|
||||
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
||||
|
|
@ -1,238 +0,0 @@
|
|||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
import requests
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from config.logger import setup_logging
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
API_URL = "https://asr.tencentcloudapi.com"
|
||||
API_VERSION = "2019-06-14"
|
||||
FORMAT = "pcm" # 支持的音频格式:pcm, wav, mp3
|
||||
|
||||
def __init__(self, config: dict, delete_audio_file: bool = True):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.NON_STREAM
|
||||
self.secret_id = config.get("secret_id")
|
||||
self.secret_key = config.get("secret_key")
|
||||
self.output_dir = config.get("output_dir")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
async def speech_to_text(
|
||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""将语音数据转换为文本"""
|
||||
if not opus_data:
|
||||
logger.bind(tag=TAG).warning("音频数据为空!")
|
||||
return None, None
|
||||
|
||||
file_path = None
|
||||
try:
|
||||
# 检查配置是否已设置
|
||||
if not self.secret_id or not self.secret_key:
|
||||
logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别")
|
||||
return None, file_path
|
||||
|
||||
# 将Opus音频数据解码为PCM
|
||||
if audio_format == "pcm":
|
||||
pcm_data = opus_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(opus_data)
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if self.delete_audio_file:
|
||||
pass
|
||||
else:
|
||||
self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
# 将音频数据转换为Base64编码
|
||||
base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8")
|
||||
|
||||
# 构建请求体
|
||||
request_body = self._build_request_body(base64_audio)
|
||||
|
||||
# 获取认证头
|
||||
timestamp, authorization = self._get_auth_headers(request_body)
|
||||
|
||||
# 发送请求
|
||||
start_time = time.time()
|
||||
result = self._send_request(request_body, timestamp, authorization)
|
||||
|
||||
if result:
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
|
||||
)
|
||||
|
||||
return result, file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
|
||||
return None, file_path
|
||||
|
||||
def _build_request_body(self, base64_audio: str) -> str:
|
||||
"""构建请求体"""
|
||||
request_map = {
|
||||
"ProjectId": 0,
|
||||
"SubServiceType": 2, # 一句话识别
|
||||
"EngSerViceType": "16k_zh", # 中文普通话通用
|
||||
"SourceType": 1, # 音频数据来源为语音文件
|
||||
"VoiceFormat": self.FORMAT, # 音频格式
|
||||
"Data": base64_audio, # Base64编码的音频数据
|
||||
"DataLen": len(base64_audio), # 数据长度
|
||||
}
|
||||
return json.dumps(request_map)
|
||||
|
||||
def _get_auth_headers(self, request_body: str) -> Tuple[str, str]:
|
||||
"""获取认证头"""
|
||||
try:
|
||||
# 获取当前UTC时间戳
|
||||
now = datetime.now(timezone.utc)
|
||||
timestamp = str(int(now.timestamp()))
|
||||
date = now.strftime("%Y-%m-%d")
|
||||
|
||||
# 服务名称必须是 "asr"
|
||||
service = "asr"
|
||||
|
||||
# 拼接凭证范围
|
||||
credential_scope = f"{date}/{service}/tc3_request"
|
||||
|
||||
# 使用TC3-HMAC-SHA256签名方法
|
||||
algorithm = "TC3-HMAC-SHA256"
|
||||
|
||||
# 构建规范请求字符串
|
||||
http_request_method = "POST"
|
||||
canonical_uri = "/"
|
||||
canonical_query_string = ""
|
||||
|
||||
# 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写
|
||||
# 必须包含content-type和host头部
|
||||
content_type = "application/json; charset=utf-8"
|
||||
host = "asr.tencentcloudapi.com"
|
||||
action = "SentenceRecognition" # 接口名称
|
||||
|
||||
# 构建规范头部信息,注意顺序和格式
|
||||
canonical_headers = (
|
||||
f"content-type:{content_type.lower()}\n"
|
||||
+ f"host:{host.lower()}\n"
|
||||
+ f"x-tc-action:{action.lower()}\n"
|
||||
)
|
||||
|
||||
signed_headers = "content-type;host;x-tc-action"
|
||||
|
||||
# 请求体哈希值
|
||||
payload_hash = self._sha256_hex(request_body)
|
||||
|
||||
# 构建规范请求字符串
|
||||
canonical_request = (
|
||||
f"{http_request_method}\n"
|
||||
+ f"{canonical_uri}\n"
|
||||
+ f"{canonical_query_string}\n"
|
||||
+ f"{canonical_headers}\n"
|
||||
+ f"{signed_headers}\n"
|
||||
+ f"{payload_hash}"
|
||||
)
|
||||
|
||||
# 计算规范请求的哈希值
|
||||
hashed_canonical_request = self._sha256_hex(canonical_request)
|
||||
|
||||
# 构建待签名字符串
|
||||
string_to_sign = (
|
||||
f"{algorithm}\n"
|
||||
+ f"{timestamp}\n"
|
||||
+ f"{credential_scope}\n"
|
||||
+ f"{hashed_canonical_request}"
|
||||
)
|
||||
|
||||
# 计算签名密钥
|
||||
secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date)
|
||||
secret_service = self._hmac_sha256(secret_date, service)
|
||||
secret_signing = self._hmac_sha256(secret_service, "tc3_request")
|
||||
|
||||
# 计算签名
|
||||
signature = self._bytes_to_hex(
|
||||
self._hmac_sha256(secret_signing, string_to_sign)
|
||||
)
|
||||
|
||||
# 构建授权头
|
||||
authorization = (
|
||||
f"{algorithm} "
|
||||
+ f"Credential={self.secret_id}/{credential_scope}, "
|
||||
+ f"SignedHeaders={signed_headers}, "
|
||||
+ f"Signature={signature}"
|
||||
)
|
||||
|
||||
return timestamp, authorization
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True)
|
||||
raise RuntimeError(f"生成认证头失败: {e}")
|
||||
|
||||
def _send_request(
|
||||
self, request_body: str, timestamp: str, authorization: str
|
||||
) -> Optional[str]:
|
||||
"""发送请求到腾讯云API"""
|
||||
headers = {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Host": "asr.tencentcloudapi.com",
|
||||
"Authorization": authorization,
|
||||
"X-TC-Action": "SentenceRecognition",
|
||||
"X-TC-Version": self.API_VERSION,
|
||||
"X-TC-Timestamp": timestamp,
|
||||
"X-TC-Region": "ap-shanghai",
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(self.API_URL, headers=headers, data=request_body)
|
||||
|
||||
if not response.ok:
|
||||
raise IOError(f"请求失败: {response.status_code} {response.reason}")
|
||||
|
||||
response_json = response.json()
|
||||
|
||||
# 检查是否有错误
|
||||
if "Response" in response_json and "Error" in response_json["Response"]:
|
||||
error = response_json["Response"]["Error"]
|
||||
error_code = error["Code"]
|
||||
error_message = error["Message"]
|
||||
raise IOError(f"API返回错误: {error_code}: {error_message}")
|
||||
|
||||
# 提取识别结果
|
||||
if "Response" in response_json and "Result" in response_json["Response"]:
|
||||
return response_json["Response"]["Result"]
|
||||
else:
|
||||
logger.bind(tag=TAG).warning(f"响应中没有识别结果: {response_json}")
|
||||
return ""
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"发送请求失败: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def _sha256_hex(self, data: str) -> str:
|
||||
"""计算字符串的SHA256哈希值"""
|
||||
digest = hashlib.sha256(data.encode("utf-8")).digest()
|
||||
return self._bytes_to_hex(digest)
|
||||
|
||||
def _hmac_sha256(self, key, data: str) -> bytes:
|
||||
"""计算HMAC-SHA256"""
|
||||
if isinstance(key, str):
|
||||
key = key.encode("utf-8")
|
||||
|
||||
return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest()
|
||||
|
||||
def _bytes_to_hex(self, bytes_data: bytes) -> str:
|
||||
"""字节数组转十六进制字符串"""
|
||||
return "".join(f"{b:02x}" for b in bytes_data)
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
import os
|
||||
import json
|
||||
import time
|
||||
from typing import Optional, Tuple, List
|
||||
from .base import ASRProviderBase
|
||||
from config.logger import setup_logging
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
import vosk
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config: dict, delete_audio_file: bool = True):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.LOCAL
|
||||
self.model_path = config.get("model_path")
|
||||
self.output_dir = config.get("output_dir", "tmp/")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
# 初始化VOSK模型
|
||||
self.model = None
|
||||
self.recognizer = None
|
||||
self._load_model()
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(self.output_dir, exist_ok=True)
|
||||
|
||||
def _load_model(self):
|
||||
"""加载VOSK模型"""
|
||||
try:
|
||||
if not os.path.exists(self.model_path):
|
||||
raise FileNotFoundError(f"VOSK模型路径不存在: {self.model_path}")
|
||||
|
||||
logger.bind(tag=TAG).info(f"正在加载VOSK模型: {self.model_path}")
|
||||
self.model = vosk.Model(self.model_path)
|
||||
|
||||
# 初始化VOSK识别器(采样率必须为16kHz)
|
||||
self.recognizer = vosk.KaldiRecognizer(self.model, 16000)
|
||||
|
||||
logger.bind(tag=TAG).info("VOSK模型加载成功")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"加载VOSK模型失败: {e}")
|
||||
raise
|
||||
|
||||
async def speech_to_text(
|
||||
self, audio_data: List[bytes], session_id: str, audio_format: str = "opus"
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""将语音数据转换为文本"""
|
||||
file_path = None
|
||||
try:
|
||||
# 检查模型是否加载成功
|
||||
if not self.model:
|
||||
logger.bind(tag=TAG).error("VOSK模型未加载,无法进行识别")
|
||||
return "", None
|
||||
|
||||
# 解码音频(如果原始格式是Opus)
|
||||
if audio_format == "pcm":
|
||||
pcm_data = audio_data
|
||||
else:
|
||||
pcm_data = self.decode_opus(audio_data)
|
||||
|
||||
if not pcm_data:
|
||||
logger.bind(tag=TAG).warning("解码后的PCM数据为空,无法进行识别")
|
||||
return "", None
|
||||
|
||||
# 合并PCM数据
|
||||
combined_pcm_data = b"".join(pcm_data)
|
||||
if len(combined_pcm_data) == 0:
|
||||
logger.bind(tag=TAG).warning("合并后的PCM数据为空")
|
||||
return "", None
|
||||
|
||||
# 判断是否保存为WAV文件
|
||||
if not self.delete_audio_file:
|
||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
|
||||
# 进行识别(VOSK推荐每次送入2000字节的数据)
|
||||
chunk_size = 2000
|
||||
text_result = ""
|
||||
|
||||
for i in range(0, len(combined_pcm_data), chunk_size):
|
||||
chunk = combined_pcm_data[i:i+chunk_size]
|
||||
if self.recognizer.AcceptWaveform(chunk):
|
||||
result = json.loads(self.recognizer.Result())
|
||||
text = result.get('text', '')
|
||||
if text:
|
||||
text_result += text + " "
|
||||
|
||||
# 获取最终结果
|
||||
final_result = json.loads(self.recognizer.FinalResult())
|
||||
final_text = final_result.get('text', '')
|
||||
if final_text:
|
||||
text_result += final_text
|
||||
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"VOSK语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text_result.strip()}"
|
||||
)
|
||||
|
||||
return text_result.strip(), file_path
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"VOSK语音识别失败: {e}")
|
||||
return "", None
|
||||
finally:
|
||||
# 文件清理逻辑
|
||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||
try:
|
||||
os.remove(file_path)
|
||||
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
||||
|
|
@ -1,523 +0,0 @@
|
|||
import json
|
||||
import hmac
|
||||
import base64
|
||||
import hashlib
|
||||
import asyncio
|
||||
import websockets
|
||||
import opuslib_next
|
||||
from time import mktime
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
from typing import List
|
||||
from config.logger import setup_logging
|
||||
from wsgiref.handlers import format_date_time
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from core.providers.asr.dto.dto import InterfaceType
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
# 帧状态常量
|
||||
STATUS_FIRST_FRAME = 0 # 第一帧的标识
|
||||
STATUS_CONTINUE_FRAME = 1 # 中间帧标识
|
||||
STATUS_LAST_FRAME = 2 # 最后一帧的标识
|
||||
|
||||
|
||||
class ASRProvider(ASRProviderBase):
|
||||
def __init__(self, config, delete_audio_file):
|
||||
super().__init__()
|
||||
self.interface_type = InterfaceType.STREAM
|
||||
self.config = config
|
||||
self.text = ""
|
||||
self.decoder = opuslib_next.Decoder(16000, 1)
|
||||
self.asr_ws = None
|
||||
self.forward_task = None
|
||||
self.is_processing = False
|
||||
self.server_ready = False
|
||||
self.last_frame_sent = False # 标记是否已发送最终帧
|
||||
self.best_text = "" # 保存最佳识别结果
|
||||
self.has_final_result = False # 标记是否收到最终识别结果
|
||||
|
||||
# 讯飞配置
|
||||
self.app_id = config.get("app_id")
|
||||
self.api_key = config.get("api_key")
|
||||
self.api_secret = config.get("api_secret")
|
||||
|
||||
if not all([self.app_id, self.api_key, self.api_secret]):
|
||||
raise ValueError("必须提供app_id、api_key和api_secret")
|
||||
|
||||
# 识别参数
|
||||
self.iat_params = {
|
||||
"domain": config.get("domain", "slm"),
|
||||
"language": config.get("language", "zh_cn"),
|
||||
"accent": config.get("accent", "mandarin"),
|
||||
"dwa": config.get("dwa", "wpgs"),
|
||||
"result": {"encoding": "utf8", "compress": "raw", "format": "plain"},
|
||||
}
|
||||
|
||||
self.output_dir = config.get("output_dir", "tmp/")
|
||||
self.delete_audio_file = delete_audio_file
|
||||
|
||||
def create_url(self) -> str:
|
||||
"""生成认证URL"""
|
||||
url = "ws://iat.cn-huabei-1.xf-yun.com/v1"
|
||||
# 生成RFC1123格式的时间戳
|
||||
now = datetime.now()
|
||||
date = format_date_time(mktime(now.timetuple()))
|
||||
|
||||
# 拼接字符串
|
||||
signature_origin = "host: " + "iat.cn-huabei-1.xf-yun.com" + "\n"
|
||||
signature_origin += "date: " + date + "\n"
|
||||
signature_origin += "GET " + "/v1 " + "HTTP/1.1"
|
||||
|
||||
# 进行hmac-sha256进行加密
|
||||
signature_sha = hmac.new(
|
||||
self.api_secret.encode("utf-8"),
|
||||
signature_origin.encode("utf-8"),
|
||||
digestmod=hashlib.sha256,
|
||||
).digest()
|
||||
signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
|
||||
|
||||
authorization_origin = (
|
||||
'api_key="%s", algorithm="%s", headers="%s", signature="%s"'
|
||||
% (self.api_key, "hmac-sha256", "host date request-line", signature_sha)
|
||||
)
|
||||
authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(
|
||||
encoding="utf-8"
|
||||
)
|
||||
|
||||
# 将请求的鉴权参数组合为字典
|
||||
v = {
|
||||
"authorization": authorization,
|
||||
"date": date,
|
||||
"host": "iat.cn-huabei-1.xf-yun.com",
|
||||
}
|
||||
|
||||
# 拼接鉴权参数,生成url
|
||||
url = url + "?" + urlencode(v)
|
||||
return url
|
||||
|
||||
async def open_audio_channels(self, conn):
|
||||
await super().open_audio_channels(conn)
|
||||
|
||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||
# 先调用父类方法处理基础逻辑
|
||||
await super().receive_audio(conn, audio, audio_have_voice)
|
||||
|
||||
# 存储音频数据用于声纹识别
|
||||
if not hasattr(conn, "asr_audio_for_voiceprint"):
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
conn.asr_audio_for_voiceprint.append(audio)
|
||||
|
||||
# 如果本次有声音,且之前没有建立连接
|
||||
if audio_have_voice and self.asr_ws is None and not self.is_processing:
|
||||
try:
|
||||
await self._start_recognition(conn)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
|
||||
await self._cleanup(conn)
|
||||
return
|
||||
|
||||
# 发送当前音频数据
|
||||
if self.asr_ws and self.is_processing and self.server_ready:
|
||||
try:
|
||||
pcm_frame = self.decoder.decode(audio, 960)
|
||||
await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"发送音频数据时发生错误: {e}")
|
||||
await self._cleanup(conn)
|
||||
|
||||
async def _start_recognition(self, conn):
|
||||
"""开始识别会话"""
|
||||
try:
|
||||
self.is_processing = True
|
||||
# 建立WebSocket连接
|
||||
ws_url = self.create_url()
|
||||
logger.bind(tag=TAG).info(f"正在连接ASR服务: {ws_url[:50]}...")
|
||||
|
||||
self.asr_ws = await websockets.connect(
|
||||
ws_url,
|
||||
max_size=1000000000,
|
||||
ping_interval=None,
|
||||
ping_timeout=None,
|
||||
close_timeout=10,
|
||||
)
|
||||
|
||||
logger.bind(tag=TAG).info("ASR WebSocket连接已建立")
|
||||
self.server_ready = False
|
||||
self.last_frame_sent = False
|
||||
self.best_text = ""
|
||||
self.forward_task = asyncio.create_task(self._forward_results(conn))
|
||||
|
||||
# 发送首帧音频
|
||||
if conn.asr_audio and len(conn.asr_audio) > 0:
|
||||
first_audio = conn.asr_audio[-1] if conn.asr_audio else b""
|
||||
pcm_frame = (
|
||||
self.decoder.decode(first_audio, 960) if first_audio else b""
|
||||
)
|
||||
await self._send_audio_frame(pcm_frame, STATUS_FIRST_FRAME)
|
||||
self.server_ready = True
|
||||
logger.bind(tag=TAG).info("已发送首帧,开始识别")
|
||||
|
||||
# 发送缓存的音频数据
|
||||
for cached_audio in conn.asr_audio[-10:]:
|
||||
try:
|
||||
pcm_frame = self.decoder.decode(cached_audio, 960)
|
||||
await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).info(f"发送缓存音频数据时发生错误: {e}")
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
|
||||
if hasattr(e, "__cause__") and e.__cause__:
|
||||
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
|
||||
if self.asr_ws:
|
||||
await self.asr_ws.close()
|
||||
self.asr_ws = None
|
||||
self.is_processing = False
|
||||
raise
|
||||
|
||||
async def _send_audio_frame(self, audio_data: bytes, status: int):
|
||||
"""发送音频帧"""
|
||||
if not self.asr_ws:
|
||||
return
|
||||
|
||||
audio_b64 = base64.b64encode(audio_data).decode("utf-8")
|
||||
|
||||
frame_data = {
|
||||
"header": {"status": status, "app_id": self.app_id},
|
||||
"parameter": {"iat": self.iat_params},
|
||||
"payload": {
|
||||
"audio": {"audio": audio_b64, "sample_rate": 16000, "encoding": "raw"}
|
||||
},
|
||||
}
|
||||
|
||||
await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False))
|
||||
|
||||
# 标记是否发送了最终帧
|
||||
if status == STATUS_LAST_FRAME:
|
||||
self.last_frame_sent = True
|
||||
logger.bind(tag=TAG).info("标记最终帧已发送")
|
||||
|
||||
async def _forward_results(self, conn):
|
||||
"""转发识别结果"""
|
||||
try:
|
||||
while self.asr_ws and not conn.stop_event.is_set():
|
||||
# 获取当前连接的音频数据
|
||||
audio_data = getattr(conn, "asr_audio_for_voiceprint", [])
|
||||
try:
|
||||
# 如果已发送最终帧,增加超时时间等待完整结果
|
||||
timeout = 3.0 if self.last_frame_sent else 30.0
|
||||
response = await asyncio.wait_for(
|
||||
self.asr_ws.recv(), timeout=timeout
|
||||
)
|
||||
result = json.loads(response)
|
||||
logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
|
||||
|
||||
header = result.get("header", {})
|
||||
payload = result.get("payload", {})
|
||||
code = header.get("code", 0)
|
||||
status = header.get("status", 0)
|
||||
|
||||
if code != 0:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"识别错误,错误码: {code}, 消息: {header.get('message', '')}"
|
||||
)
|
||||
if code in [10114, 10160]: # 连接问题
|
||||
break
|
||||
continue
|
||||
|
||||
# 处理识别结果
|
||||
if payload and "result" in payload:
|
||||
text_data = payload["result"]["text"]
|
||||
if text_data:
|
||||
# 解码base64文本
|
||||
decoded_text = base64.b64decode(text_data).decode("utf-8")
|
||||
text_json = json.loads(decoded_text)
|
||||
|
||||
# 提取文本内容
|
||||
text_ws = text_json.get("ws", [])
|
||||
result_text = ""
|
||||
for i in text_ws:
|
||||
for j in i.get("cw", []):
|
||||
w = j.get("w", "")
|
||||
result_text += w
|
||||
|
||||
# 更新识别文本 - 实时更新策略
|
||||
# 只检查是否为空字符串,不再过滤任何标点符号
|
||||
# 这样可以确保所有识别到的内容,包括标点符号都能被实时更新
|
||||
if result_text and result_text.strip():
|
||||
# 实时更新:正常情况下都更新,提高响应速度
|
||||
should_update = True
|
||||
|
||||
# 保存最佳文本
|
||||
# 1. 如果是识别完成状态或最终帧后收到的结果,优先保存
|
||||
# 2. 否则保存最长的有意义文本
|
||||
# 取消对标点符号的过滤,只检查是否为空
|
||||
# 这样可以保留所有识别到的内容,包括各种标点符号
|
||||
is_valid_text = len(result_text.strip()) > 0
|
||||
|
||||
if (
|
||||
self.last_frame_sent or status == 2
|
||||
) and is_valid_text:
|
||||
self.best_text = result_text
|
||||
self.has_final_result = True # 标记已收到最终结果
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"保存最终识别结果: {self.best_text}"
|
||||
)
|
||||
elif (
|
||||
len(result_text) > len(self.best_text)
|
||||
and is_valid_text
|
||||
and not self.has_final_result
|
||||
):
|
||||
self.best_text = result_text
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"保存中间最佳文本: {self.best_text}"
|
||||
)
|
||||
|
||||
# 如果已发送最终帧,只过滤空文本
|
||||
if self.last_frame_sent:
|
||||
# 只拒绝完全空的结果
|
||||
if not result_text.strip():
|
||||
should_update = False
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"最终帧后拒绝空文本"
|
||||
)
|
||||
|
||||
if should_update:
|
||||
# 处理流式识别结果,避免简单替换导致内容丢失
|
||||
# 1. 如果是中间状态(非最终帧后),可能需要替换为更完整的识别
|
||||
# 2. 如果是最终帧后收到的结果,可能是对前面文本的补充
|
||||
if self.last_frame_sent:
|
||||
# 最终帧后收到的结果可能是标点符号等补充内容
|
||||
# 检查是否需要合并文本而不是替换
|
||||
# 如果当前文本是纯标点而前面已有内容,应该追加而不是替换
|
||||
if len(
|
||||
self.text
|
||||
) > 0 and result_text.strip() in [
|
||||
"。",
|
||||
".",
|
||||
"?",
|
||||
"?",
|
||||
"!",
|
||||
"!",
|
||||
",",
|
||||
",",
|
||||
";",
|
||||
";",
|
||||
]:
|
||||
# 对于标点符号,追加到现有文本后
|
||||
self.text = (
|
||||
self.text.rstrip().rstrip("。.")
|
||||
+ result_text
|
||||
)
|
||||
else:
|
||||
# 其他情况保持替换逻辑
|
||||
self.text = result_text
|
||||
else:
|
||||
# 中间状态替换为新的识别结果
|
||||
self.text = result_text
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"实时更新识别文本: {self.text} (最终帧已发送: {self.last_frame_sent})"
|
||||
)
|
||||
|
||||
# 识别完成,但如果还没发送最终帧,继续等待
|
||||
if status == 2:
|
||||
logger.bind(tag=TAG).info(
|
||||
f"识别完成状态已到达,当前识别文本: {self.text}"
|
||||
)
|
||||
|
||||
# 如果还没发送最终帧,继续等待
|
||||
if not self.last_frame_sent:
|
||||
logger.bind(tag=TAG).info(
|
||||
"识别完成但最终帧未发送,继续等待..."
|
||||
)
|
||||
continue
|
||||
|
||||
# 已发送最终帧且收到完成状态,使用最佳策略选择最终结果
|
||||
# 优先使用识别完成状态下的最新结果,而不是仅仅基于长度
|
||||
if self.best_text:
|
||||
# 如果当前文本是在最终帧发送后或识别完成状态下收到的,优先使用
|
||||
if (
|
||||
self.last_frame_sent or status == 2
|
||||
) and self.text.strip():
|
||||
logger.bind(tag=TAG).info(
|
||||
f"使用完成状态下的最新识别结果: {self.text}"
|
||||
)
|
||||
elif len(self.best_text) > len(self.text):
|
||||
logger.bind(tag=TAG).info(
|
||||
f"使用更长的最佳文本作为最终结果: {self.text} -> {self.best_text}"
|
||||
)
|
||||
self.text = self.best_text
|
||||
|
||||
logger.bind(tag=TAG).info(f"获取到最终完整文本: {self.text}")
|
||||
conn.reset_vad_states()
|
||||
if len(audio_data) > 15: # 确保有足够音频数据
|
||||
# 准备处理结果
|
||||
pass
|
||||
break
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
if self.last_frame_sent:
|
||||
# 超时时也使用最佳文本
|
||||
if self.best_text and len(self.best_text) > len(self.text):
|
||||
logger.bind(tag=TAG).info(
|
||||
f"超时,使用最佳文本: {self.text} -> {self.best_text}"
|
||||
)
|
||||
self.text = self.best_text
|
||||
logger.bind(tag=TAG).info(
|
||||
f"最终帧后超时,使用结果: {self.text}"
|
||||
)
|
||||
break
|
||||
# 如果还没发送最终帧,继续等待
|
||||
continue
|
||||
except websockets.ConnectionClosed:
|
||||
logger.bind(tag=TAG).info("ASR服务连接已关闭")
|
||||
self.is_processing = False
|
||||
break
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
|
||||
if hasattr(e, "__cause__") and e.__cause__:
|
||||
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
|
||||
self.is_processing = False
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
|
||||
if hasattr(e, "__cause__") and e.__cause__:
|
||||
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
|
||||
finally:
|
||||
if self.asr_ws:
|
||||
await self.asr_ws.close()
|
||||
self.asr_ws = None
|
||||
self.is_processing = False
|
||||
if conn:
|
||||
if hasattr(conn, "asr_audio_for_voiceprint"):
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
if hasattr(conn, "asr_audio"):
|
||||
conn.asr_audio = []
|
||||
if hasattr(conn, "has_valid_voice"):
|
||||
conn.has_valid_voice = False
|
||||
|
||||
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
||||
"""处理语音停止,发送最后一帧并处理识别结果"""
|
||||
try:
|
||||
# 先发送最后一帧表示音频结束
|
||||
if self.asr_ws and self.is_processing:
|
||||
try:
|
||||
# 取最后一个有效的音频帧作为最后一帧数据
|
||||
last_frame = b""
|
||||
if asr_audio_task:
|
||||
last_audio = asr_audio_task[-1]
|
||||
last_frame = self.decoder.decode(last_audio, 960)
|
||||
await self._send_audio_frame(last_frame, STATUS_LAST_FRAME)
|
||||
logger.bind(tag=TAG).info("已发送最后一帧")
|
||||
|
||||
# 发送最终帧后,给_forward_results适当时间处理最终结果
|
||||
await asyncio.sleep(0.25)
|
||||
|
||||
logger.bind(tag=TAG).info(f"准备处理最终识别结果: {self.text}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"发送最后一帧失败: {e}")
|
||||
|
||||
# 调用父类的handle_voice_stop方法处理识别结果
|
||||
await super().handle_voice_stop(conn, asr_audio_task)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
||||
import traceback
|
||||
|
||||
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
|
||||
|
||||
def stop_ws_connection(self):
|
||||
if self.asr_ws:
|
||||
asyncio.create_task(self.asr_ws.close())
|
||||
self.asr_ws = None
|
||||
self.is_processing = False
|
||||
|
||||
async def _cleanup(self, conn):
|
||||
"""清理资源"""
|
||||
logger.bind(tag=TAG).info(
|
||||
f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}"
|
||||
)
|
||||
|
||||
# 发送最后一帧
|
||||
if self.asr_ws and self.is_processing:
|
||||
try:
|
||||
await self._send_audio_frame(b"", STATUS_LAST_FRAME)
|
||||
await asyncio.sleep(0.1)
|
||||
logger.bind(tag=TAG).info("已发送最后一帧")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"发送最后一帧失败: {e}")
|
||||
|
||||
# 状态重置
|
||||
self.is_processing = False
|
||||
self.server_ready = False
|
||||
self.last_frame_sent = False
|
||||
self.best_text = ""
|
||||
self.has_final_result = False
|
||||
logger.bind(tag=TAG).info("ASR状态已重置")
|
||||
|
||||
# 清理任务
|
||||
if self.forward_task and not self.forward_task.done():
|
||||
self.forward_task.cancel()
|
||||
try:
|
||||
await asyncio.wait_for(self.forward_task, timeout=1.0)
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}")
|
||||
finally:
|
||||
self.forward_task = None
|
||||
|
||||
# 关闭连接
|
||||
if self.asr_ws:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
|
||||
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
|
||||
logger.bind(tag=TAG).debug("WebSocket连接已关闭")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
|
||||
finally:
|
||||
self.asr_ws = None
|
||||
|
||||
# 清理连接的音频缓存
|
||||
if conn:
|
||||
if hasattr(conn, "asr_audio_for_voiceprint"):
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
if hasattr(conn, "asr_audio"):
|
||||
conn.asr_audio = []
|
||||
if hasattr(conn, "has_valid_voice"):
|
||||
conn.has_valid_voice = False
|
||||
|
||||
logger.bind(tag=TAG).info("ASR会话清理完成")
|
||||
|
||||
async def speech_to_text(self, opus_data, session_id, audio_format):
|
||||
"""获取识别结果"""
|
||||
result = self.text
|
||||
self.text = ""
|
||||
return result, None
|
||||
|
||||
async def close(self):
|
||||
"""资源清理方法"""
|
||||
if self.asr_ws:
|
||||
await self.asr_ws.close()
|
||||
self.asr_ws = None
|
||||
if self.forward_task:
|
||||
self.forward_task.cancel()
|
||||
try:
|
||||
await self.forward_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self.forward_task = None
|
||||
self.is_processing = False
|
||||
# 清理所有连接的音频缓冲区
|
||||
if hasattr(self, "_connections"):
|
||||
for conn in self._connections.values():
|
||||
if hasattr(conn, "asr_audio_for_voiceprint"):
|
||||
conn.asr_audio_for_voiceprint = []
|
||||
if hasattr(conn, "asr_audio"):
|
||||
conn.asr_audio = []
|
||||
if hasattr(conn, "has_valid_voice"):
|
||||
conn.has_valid_voice = False
|
||||
|
|
@ -2,10 +2,14 @@ from abc import ABC, abstractmethod
|
|||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
import time
|
||||
from typing import List, Optional, Tuple
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from config.logger import setup_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.connection import ConnectionHandler
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
|
@ -29,45 +33,68 @@ class TurnDetectionProviderBase(ABC):
|
|||
Turn Detection determines whether the user has finished speaking
|
||||
and it's time for the system to respond.
|
||||
|
||||
Manages text buffer internally - subclasses can override buffer behavior.
|
||||
Uses conn.asr_text_buffer for accumulated text (maintained by ASR).
|
||||
|
||||
Endpoint delay mechanism:
|
||||
- When check_end_of_turn is called, first call turn detection service
|
||||
- If result is "finished", wait min_endpoint_delay
|
||||
- If result is "unfinished/waiting", wait max_endpoint_delay
|
||||
- If user continues speaking (new check_end_of_turn call), the task is cancelled
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict):
|
||||
self._text_buffer: List[str] = []
|
||||
self._buffer_start_time: float = 0.0
|
||||
self._buffer_timeout: float = float(config.get("buffer_timeout", 10.0))
|
||||
# Endpoint delay: time to wait after last speech before forcing end of turn
|
||||
# min_endpoint_delay: used when turn detection says "finished"
|
||||
# max_endpoint_delay: used when turn detection says "unfinished/waiting"
|
||||
self.min_endpoint_delay: int = config.get("min_endpoint_delay", 500)
|
||||
self.max_endpoint_delay: int = config.get("max_endpoint_delay", 2000)
|
||||
# Pending turn detection task (can be cancelled when new speech arrives)
|
||||
self._turn_detection_task: asyncio.Task = None
|
||||
|
||||
def _append_text(self, text: str) -> str:
|
||||
if not self._text_buffer:
|
||||
self._buffer_start_time = time.time()
|
||||
self._text_buffer.append(text)
|
||||
return " ".join(self._text_buffer)
|
||||
def _cancel_pending_task(self) -> None: # noqa: F821
|
||||
"""Cancel pending turn detection task if exists"""
|
||||
if self._turn_detection_task and not self._turn_detection_task.done():
|
||||
self._turn_detection_task.cancel()
|
||||
logger.bind(tag=TAG).debug("Cancelled pending turn detection task")
|
||||
self._turn_detection_task = None
|
||||
|
||||
def _clear_buffer(self) -> None:
|
||||
"""Clear the text buffer"""
|
||||
self._text_buffer.clear()
|
||||
self._buffer_start_time = 0.0
|
||||
|
||||
def _is_buffer_timeout(self) -> bool:
|
||||
"""Check if buffer has timed out (to avoid infinite accumulation)"""
|
||||
if not self._text_buffer:
|
||||
return False
|
||||
return (time.time() - self._buffer_start_time) > self._buffer_timeout
|
||||
|
||||
@abstractmethod
|
||||
async def check_end_of_turn(self, text: str) -> Tuple[bool, str]:
|
||||
"""Check if the user has finished their turn
|
||||
def _calculate_sleep_time(self, conn: "ConnectionHandler", is_finished: bool) -> float:
|
||||
"""Calculate how long to sleep based on turn detection result
|
||||
|
||||
Args:
|
||||
text: New ASR text segment
|
||||
conn: Connection handler containing _last_speaking_time (in ms)
|
||||
is_finished: True if turn detection says finished, False otherwise
|
||||
|
||||
Returns:
|
||||
Tuple of (end_of_turn: bool, full_text: str)
|
||||
- end_of_turn: True if user finished speaking, False to continue buffering
|
||||
- full_text: Accumulated text from buffer
|
||||
Sleep time in seconds (>= 0)
|
||||
"""
|
||||
# Choose delay based on turn detection result
|
||||
endpoint_delay = self.min_endpoint_delay if is_finished else self.max_endpoint_delay
|
||||
|
||||
if conn._last_speaking_time is None:
|
||||
return endpoint_delay
|
||||
|
||||
# Convert ms to seconds for calculation
|
||||
elapsed = conn._last_speaking_time - int(time.time() * 1000)
|
||||
sleep_time = endpoint_delay - elapsed
|
||||
return sleep_time
|
||||
|
||||
@abstractmethod
|
||||
def check_end_of_turn(self, conn: "ConnectionHandler"):
|
||||
"""Check if the user has finished their turn
|
||||
|
||||
This method manages the endpoint delay mechanism:
|
||||
1. Cancel any pending task from previous call
|
||||
2. Create a new task that:
|
||||
- Calls turn detection service with conn.asr_text_buffer
|
||||
- Wait min_endpoint_delay (if finished) or max_endpoint_delay (if unfinished)
|
||||
- If not cancelled, call conn.on_end_of_turn()
|
||||
|
||||
Args:
|
||||
conn: Connection handler containing asr_text_buffer and _last_speaking_time
|
||||
"""
|
||||
...
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Clean up resources - clears buffer"""
|
||||
self._clear_buffer()
|
||||
"""Clean up resources"""
|
||||
pass
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
from typing import Tuple
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from config.logger import setup_logging
|
||||
from .base import TurnDetectionProviderBase
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.connection import ConnectionHandler
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
|
@ -18,14 +21,11 @@ class TurnDetectionProvider(TurnDetectionProviderBase):
|
|||
super().__init__(config)
|
||||
logger.bind(tag=TAG).info("NoopTurnDetection initialized (Turn Detection disabled)")
|
||||
|
||||
async def check_end_of_turn(self, text: str) -> Tuple[bool, str]:
|
||||
"""Always return end_of_turn=True immediately
|
||||
def check_end_of_turn(self, conn: "ConnectionHandler"):
|
||||
"""Immediately trigger end of turn (no delay)
|
||||
|
||||
Args:
|
||||
text: The ASR text
|
||||
|
||||
Returns:
|
||||
Tuple of (True, text) - always signals turn finished
|
||||
conn: Connection handler
|
||||
"""
|
||||
# No buffering needed for noop - just return the text as-is
|
||||
return True, text
|
||||
import asyncio
|
||||
asyncio.create_task(conn.on_end_of_turn())
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
from typing import Tuple
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING
|
||||
import httpx
|
||||
|
||||
from config.logger import setup_logging
|
||||
from .base import TurnDetectionProviderBase, TurnDetectionState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.connection import ConnectionHandler
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
|
|
@ -12,7 +16,14 @@ class TurnDetectionProvider(TurnDetectionProviderBase):
|
|||
"""HTTP-based Turn Detection provider using httpx async client
|
||||
|
||||
Calls an external Turn Detection service via HTTP POST.
|
||||
Gracefully degrades to end_of_turn=True on timeout or errors.
|
||||
Uses conn.asr_text_buffer for accumulated text (maintained by ASR).
|
||||
|
||||
Implements endpoint delay mechanism:
|
||||
- First calls turn detection service to get result
|
||||
- If result is "finished", wait min_endpoint_delay
|
||||
- If result is "unfinished/waiting", wait max_endpoint_delay
|
||||
- If user continues speaking during the delay, the task is cancelled
|
||||
- After delay completes, directly calls startToChat and reports ASR
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict):
|
||||
|
|
@ -27,31 +38,19 @@ class TurnDetectionProvider(TurnDetectionProviderBase):
|
|||
self._client = httpx.AsyncClient(timeout=self.timeout)
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"TenTurnDetection initialized: url={self.url}, timeout={self.timeout}s"
|
||||
f"TenTurnDetection initialized: url={self.url}, timeout={self.timeout}s, "
|
||||
f"min_endpoint_delay={self.min_endpoint_delay}ms, max_endpoint_delay={self.max_endpoint_delay}ms"
|
||||
)
|
||||
|
||||
async def check_end_of_turn(self, text: str) -> Tuple[bool, str]:
|
||||
"""Check if the user has finished their turn via HTTP call
|
||||
async def _call_turn_detection(self, full_text: str) -> bool:
|
||||
"""Call Turn Detection HTTP service to get result
|
||||
|
||||
Args:
|
||||
text: New ASR text segment
|
||||
full_text: Accumulated text to check
|
||||
|
||||
Returns:
|
||||
Tuple of (end_of_turn: bool, full_text: str)
|
||||
On timeout/error, returns (True, full_text) to avoid blocking
|
||||
True if turn detection says finished, False otherwise
|
||||
"""
|
||||
# Append to buffer
|
||||
full_text = self._append_text(text)
|
||||
|
||||
# Check buffer timeout
|
||||
if self._is_buffer_timeout():
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"Turn buffer timeout, forcing send: '{full_text[:50]}...'"
|
||||
)
|
||||
self._clear_buffer()
|
||||
return True, full_text
|
||||
|
||||
# Call Turn Detection service
|
||||
try:
|
||||
response = await self._client.post(
|
||||
self.url,
|
||||
|
|
@ -60,45 +59,97 @@ class TurnDetectionProvider(TurnDetectionProviderBase):
|
|||
response.raise_for_status()
|
||||
data = response.json()
|
||||
logger.bind(tag=TAG).info(f"TD raw response: {data}")
|
||||
# Parse result string
|
||||
|
||||
result_str = data.get("result", "finished")
|
||||
is_finished = result_str == TurnDetectionState.FINISHED.value
|
||||
|
||||
if result_str == TurnDetectionState.FINISHED.value:
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Turn finished, buffering: '{full_text[:50]}'"
|
||||
)
|
||||
self._clear_buffer()
|
||||
return True, full_text
|
||||
|
||||
# UNFINISHED or WAITING: continue buffering
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Turn unfinished, buffering: '{full_text[:50]}'"
|
||||
f"Turn detection result: {result_str}, text: '{full_text[:50]}'"
|
||||
)
|
||||
return False, full_text
|
||||
return is_finished
|
||||
|
||||
except httpx.TimeoutException:
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"TurnDetection timeout ({self.timeout}s), defaulting to finished"
|
||||
)
|
||||
self._clear_buffer()
|
||||
return True, full_text
|
||||
return True
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"TurnDetection HTTP error: {e.response.status_code}, defaulting to finished"
|
||||
)
|
||||
self._clear_buffer()
|
||||
return True, full_text
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(
|
||||
f"TurnDetection error: {e}, defaulting to finished"
|
||||
)
|
||||
self._clear_buffer()
|
||||
return True, full_text
|
||||
return True
|
||||
|
||||
async def _delayed_turn_detection_task(
|
||||
self,
|
||||
conn: "ConnectionHandler",
|
||||
):
|
||||
"""Task that calls turn detection, then waits for appropriate delay
|
||||
|
||||
Flow:
|
||||
1. Call turn detection service to get result
|
||||
2. If finished: wait min_endpoint_delay
|
||||
3. If unfinished: wait max_endpoint_delay
|
||||
4. After delay completes, call startToChat and report ASR
|
||||
|
||||
Args:
|
||||
conn: Connection handler
|
||||
|
||||
Returns:
|
||||
True if end of turn, False if cancelled
|
||||
|
||||
Raises:
|
||||
asyncio.CancelledError: If cancelled by new speech
|
||||
"""
|
||||
full_text = conn.asr_text_buffer
|
||||
|
||||
# Step 1: Call turn detection service
|
||||
is_finished = await self._call_turn_detection(full_text)
|
||||
|
||||
# Step 2: Calculate sleep time based on result
|
||||
sleep_time = self._calculate_sleep_time(conn, is_finished)
|
||||
|
||||
# Step 3: Wait for the delay
|
||||
if sleep_time > 0:
|
||||
await asyncio.sleep(sleep_time / 1000) # Convert ms to seconds
|
||||
|
||||
# Step 4: After delay, trigger end of turn processing
|
||||
logger.bind(tag=TAG).info("Endpoint delay completed, triggering on_end_of_turn")
|
||||
await conn.on_end_of_turn()
|
||||
|
||||
def check_end_of_turn(self, conn: "ConnectionHandler"):
|
||||
"""Check if the user has finished their turn with endpoint delay mechanism
|
||||
|
||||
Flow:
|
||||
1. Cancel any pending task from previous call
|
||||
2. Create a new task that:
|
||||
- Calls turn detection service
|
||||
- Waits min_endpoint_delay (if finished) or max_endpoint_delay (if unfinished)
|
||||
- Calls conn.on_end_of_turn() after delay
|
||||
|
||||
Args:
|
||||
conn: Connection handler containing asr_text_buffer and _last_speaking_time
|
||||
"""
|
||||
# Step 1: Cancel pending task
|
||||
self._cancel_pending_task()
|
||||
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"check_end_of_turn called: buffer='{conn.asr_text_buffer[:50]}...'"
|
||||
)
|
||||
|
||||
# Step 2: Create the delayed task (don't await, let it run in background)
|
||||
self._turn_detection_task = asyncio.create_task(
|
||||
self._delayed_turn_detection_task(conn)
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the httpx client and clear buffer"""
|
||||
"""Close the httpx client"""
|
||||
await super().close()
|
||||
await self._client.aclose()
|
||||
logger.bind(tag=TAG).debug("TenTurnDetection client closed")
|
||||
|
|
|
|||
|
|
@ -213,7 +213,8 @@ class VADStream(ABC):
|
|||
|
||||
1. Update conn state (client_have_voice = True)
|
||||
2. Send FIRST message to ASR queue
|
||||
3. Check if interrupt is needed (client_is_speaking)
|
||||
|
||||
Note: Interrupt check is done in _handle_inference_done via conn.check_and_interrupt()
|
||||
"""
|
||||
logger.bind(tag=TAG).debug(
|
||||
f"Speech start detected: prob={event.probability:.2f}, "
|
||||
|
|
@ -239,18 +240,6 @@ class VADStream(ABC):
|
|||
logger.bind(tag=TAG).info(
|
||||
f"ASR FIRST message sent: audio={asr_message.audio_duration_ms:.0f}ms"
|
||||
)
|
||||
|
||||
# Check if interrupt is needed
|
||||
# When TTS is speaking and user starts talking, trigger interrupt
|
||||
if conn.client_is_speaking and conn.client_listen_mode != "manual":
|
||||
logger.bind(tag=TAG).info(
|
||||
"User started speaking while Agent is speaking, triggering interrupt"
|
||||
)
|
||||
if interrupt_callback:
|
||||
try:
|
||||
await interrupt_callback(conn)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Interrupt callback failed: {e}")
|
||||
|
||||
async def _handle_inference_done(
|
||||
self,
|
||||
|
|
@ -261,12 +250,17 @@ class VADStream(ABC):
|
|||
) -> None:
|
||||
"""Handle INFERENCE_DONE event
|
||||
|
||||
Only send MIDDLE message if speech is ongoing (conn.client_have_voice)
|
||||
1. Send MIDDLE message if speech is ongoing
|
||||
2. Check smart interrupt via conn.check_and_interrupt()
|
||||
3. Update _last_speaking_time for turn detection endpoint delay
|
||||
"""
|
||||
# Only send audio if client is speaking
|
||||
if not conn.client_have_voice or not event.speaking:
|
||||
return
|
||||
|
||||
# Update last speaking time for turn detection endpoint delay (ms)
|
||||
conn._last_speaking_time = int(time.time() * 1000)
|
||||
|
||||
# Send MIDDLE message to ASR queue
|
||||
asr_message = ASRInputMessage(
|
||||
message_type=ASRMessageType.MIDDLE,
|
||||
|
|
@ -281,6 +275,9 @@ class VADStream(ABC):
|
|||
f"ASR MIDDLE message sent: prob={event.probability:.2f}, "
|
||||
f"speech={event.speech_duration:.2f}s"
|
||||
)
|
||||
|
||||
# Check if meeting interruption strategies
|
||||
conn._interrupt_by_audio(event.speech_duration)
|
||||
|
||||
async def _handle_speech_end(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -16,9 +16,15 @@ logger = setup_logging()
|
|||
@dataclass
|
||||
class FsmnVADOptions:
|
||||
"""FSMN VAD specific options"""
|
||||
prefix_padding_duration: float = 0.3 # 300ms prefix padding
|
||||
# User-side parameters (used in _run_task)
|
||||
prefix_padding_duration: float = 0.3 # 300ms prefix padding (aligned with FSMN lookback)
|
||||
sample_rate: int = 16000 # 16kHz
|
||||
chunk_size_ms: int = 100 # FSMN chunk size
|
||||
chunk_size_ms: int = 100 # streaming chunk size in ms
|
||||
|
||||
# FSMN model parameters (passed to AutoModel)
|
||||
min_silence_duration_ms: int = 500 # silence detection duration (ms)
|
||||
speech_noise_threshold: float = 0.6 # speech/noise threshold, higher = stricter
|
||||
sil_to_speech_time_thres: int = 150 # silence→speech transition time (ms), higher = less noise sensitive
|
||||
|
||||
|
||||
class VADProvider(VADProviderBase):
|
||||
|
|
@ -29,17 +35,26 @@ class VADProvider(VADProviderBase):
|
|||
|
||||
model_name = config.get("model", "fsmn-vad")
|
||||
model_revision = config.get("model_revision", "v2.0.4")
|
||||
|
||||
self._model = AutoModel(model=model_name, model_revision=model_revision)
|
||||
|
||||
|
||||
# Parse config
|
||||
chunk_size_ms = int(config.get("chunk_size_ms", "100"))
|
||||
self._opts = FsmnVADOptions(
|
||||
prefix_padding_duration=float(config.get("prefix_padding_duration", "0.3")),
|
||||
prefix_padding_duration=float(config.get("prefix_padding_duration", 0.3)),
|
||||
sample_rate=16000,
|
||||
chunk_size_ms=chunk_size_ms,
|
||||
chunk_size_ms=int(config.get("chunk_size_ms", 100)),
|
||||
min_silence_duration_ms=int(config.get("min_silence_duration_ms", 500)),
|
||||
speech_noise_threshold=float(config.get("speech_noise_threshold", 0.6)),
|
||||
sil_to_speech_time_thres=int(config.get("sil_to_speech_time_thres", 150)),
|
||||
)
|
||||
|
||||
# Pass FSMN model parameters to AutoModel
|
||||
self._model = AutoModel(
|
||||
model=model_name,
|
||||
model_revision=model_revision,
|
||||
max_end_silence_time=self._opts.min_silence_duration_ms,
|
||||
speech_noise_thres=self._opts.speech_noise_threshold,
|
||||
sil_to_speech_time_thres=self._opts.sil_to_speech_time_thres,
|
||||
disable_pbar=True, # disable progress bar
|
||||
)
|
||||
|
||||
|
||||
def stream(self) -> VADStream:
|
||||
|
|
@ -65,7 +80,7 @@ class FsmnVADStream(VADStream):
|
|||
# FSMN chunk size
|
||||
self._chunk_samples = int(opts.chunk_size_ms * opts.sample_rate / 1000)
|
||||
self._chunk_bytes = self._chunk_samples * 2 # int16
|
||||
self._chunk_duration = opts.chunk_size_ms / 1000 # seconds
|
||||
self._chunk_duration_ms = opts.chunk_size_ms # milliseconds
|
||||
|
||||
# Speech buffer for prefix padding (in bytes, not samples)
|
||||
self._prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2
|
||||
|
|
@ -159,7 +174,7 @@ class FsmnVADStream(VADStream):
|
|||
seg = res[0]["value"][0] # Take first segment
|
||||
seg_start, seg_end = seg[0], seg[1]
|
||||
|
||||
if seg_start > 0 and seg_end == -1:
|
||||
if seg_start >= 0 and seg_end == -1:
|
||||
# Speech start event
|
||||
if not speaking:
|
||||
speaking = True
|
||||
|
|
@ -183,8 +198,7 @@ class FsmnVADStream(VADStream):
|
|||
# Speech end event
|
||||
if speaking:
|
||||
speaking = False
|
||||
speech_duration_ms = seg_end - speech_start_ms
|
||||
speech_duration = speech_duration_ms / 1000
|
||||
speech_duration = seg_end - speech_start_ms # ms
|
||||
|
||||
# Emit END_OF_SPEECH
|
||||
self._output_queue.put_nowait(VADEvent(
|
||||
|
|
@ -197,7 +211,7 @@ class FsmnVADStream(VADStream):
|
|||
))
|
||||
logger.bind(tag=TAG).info(
|
||||
f"🔇 FSMN VAD END_OF_SPEECH @{seg_end}ms | "
|
||||
f"duration={speech_duration:.2f}s"
|
||||
f"duration={speech_duration:.0f}ms"
|
||||
)
|
||||
|
||||
# Reset for next utterance
|
||||
|
|
@ -211,11 +225,11 @@ class FsmnVADStream(VADStream):
|
|||
f"FSMN: short segment [{seg_start}, {seg_end}]ms (ignored)"
|
||||
)
|
||||
|
||||
# Update durations based on current state
|
||||
# Update durations based on current state (in milliseconds)
|
||||
if speaking:
|
||||
speech_duration += self._chunk_duration
|
||||
speech_duration += self._chunk_duration_ms
|
||||
else:
|
||||
silence_duration += self._chunk_duration
|
||||
silence_duration += self._chunk_duration_ms
|
||||
_reset_write_cursor()
|
||||
|
||||
# Always emit INFERENCE_DONE
|
||||
|
|
|
|||
|
|
@ -12,10 +12,10 @@ from .dto import VADEvent, VADEventType
|
|||
|
||||
@dataclass
|
||||
class SileroVADOptions:
|
||||
"""Silero VAD specific options"""
|
||||
min_speech_duration: float = 0.05 # 50ms to confirm speech start
|
||||
min_silence_duration: float = 0.40 # 400ms to confirm speech end
|
||||
prefix_padding_duration: float = 0.3 # 300ms prefix padding
|
||||
"""Silero VAD specific options (all durations in milliseconds)"""
|
||||
min_speech_duration_ms: float = 50.0 # 50ms to confirm speech start
|
||||
min_silence_duration_ms: float = 400.0 # 400ms to confirm speech end
|
||||
prefix_padding_duration_ms: float = 300.0 # 300ms prefix padding
|
||||
activation_threshold: float = 0.5 # probability threshold
|
||||
sample_rate: int = 16000 # 16kHz
|
||||
|
||||
|
|
@ -37,12 +37,12 @@ class VADProvider(VADProviderBase):
|
|||
force_reload=False,
|
||||
)
|
||||
|
||||
# Parse config
|
||||
# Parse config (all durations in milliseconds)
|
||||
self._opts = SileroVADOptions(
|
||||
min_speech_duration=float(config.get("min_speech_duration", "0.05")),
|
||||
min_silence_duration=float(config.get("min_silence_duration", "0.40")),
|
||||
prefix_padding_duration=float(config.get("prefix_padding_duration", "0.3")),
|
||||
activation_threshold=float(config.get("threshold", "0.5")),
|
||||
min_speech_duration_ms=float(config.get("min_speech_duration_ms", 50.0)),
|
||||
min_silence_duration_ms=float(config.get("min_silence_duration_ms", 400.0)),
|
||||
prefix_padding_duration_ms=float(config.get("prefix_padding_duration_ms", 300.0)),
|
||||
activation_threshold=float(config.get("threshold", 0.5)),
|
||||
sample_rate=16000,
|
||||
)
|
||||
|
||||
|
|
@ -57,7 +57,7 @@ class SileroVADStream(VADStream):
|
|||
# Silero requires 512 samples per inference (32ms at 16kHz)
|
||||
WINDOW_SIZE_SAMPLES = 512
|
||||
WINDOW_SIZE_BYTES = WINDOW_SIZE_SAMPLES * 2 # int16
|
||||
WINDOW_DURATION = WINDOW_SIZE_SAMPLES / 16000 # seconds
|
||||
WINDOW_DURATION_MS = WINDOW_SIZE_SAMPLES / 16000 * 1000 # milliseconds (32ms)
|
||||
SLOW_INFERENCE_THRESHOLD = 0.2 # seconds
|
||||
|
||||
def __init__(self, vad: VADProvider, model, opts: SileroVADOptions):
|
||||
|
|
@ -67,7 +67,7 @@ class SileroVADStream(VADStream):
|
|||
self._exp_filter = ExpFilter(alpha=0.35)
|
||||
|
||||
# Speech buffer for prefix padding (in bytes, not samples)
|
||||
self._prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2
|
||||
self._prefix_padding_bytes = int(opts.prefix_padding_duration_ms / 1000 * opts.sample_rate) * 2
|
||||
# Pre-allocate max speech buffer (60s + prefix padding)
|
||||
max_speech_bytes = 60 * opts.sample_rate * 2 + self._prefix_padding_bytes
|
||||
self._speech_buffer = bytearray(max_speech_bytes)
|
||||
|
|
@ -133,7 +133,7 @@ class SileroVADStream(VADStream):
|
|||
inference_duration = time.perf_counter() - inference_start
|
||||
extra_inference_time = max(
|
||||
0.0,
|
||||
extra_inference_time + inference_duration - self.WINDOW_DURATION,
|
||||
extra_inference_time + inference_duration - self.WINDOW_DURATION_MS / 1000,
|
||||
)
|
||||
|
||||
if inference_duration > self.SLOW_INFERENCE_THRESHOLD:
|
||||
|
|
@ -163,11 +163,11 @@ class SileroVADStream(VADStream):
|
|||
assert self._speech_buffer is not None
|
||||
return bytes(self._speech_buffer[:speech_buffer_index])
|
||||
|
||||
# Update durations
|
||||
# Update durations (in milliseconds)
|
||||
if pub_speaking:
|
||||
pub_speech_duration += self.WINDOW_DURATION
|
||||
pub_speech_duration += self.WINDOW_DURATION_MS
|
||||
else:
|
||||
pub_silence_duration += self.WINDOW_DURATION
|
||||
pub_silence_duration += self.WINDOW_DURATION_MS
|
||||
|
||||
# Emit INFERENCE_DONE
|
||||
self._output_queue.put_nowait(VADEvent(
|
||||
|
|
@ -180,13 +180,13 @@ class SileroVADStream(VADStream):
|
|||
inference_duration=inference_duration,
|
||||
))
|
||||
|
||||
# State machine logic
|
||||
# State machine logic (all durations in ms)
|
||||
if prob >= self._opts.activation_threshold:
|
||||
speech_threshold_duration += self.WINDOW_DURATION
|
||||
speech_threshold_duration += self.WINDOW_DURATION_MS
|
||||
silence_threshold_duration = 0.0
|
||||
|
||||
if not pub_speaking:
|
||||
if speech_threshold_duration >= self._opts.min_speech_duration:
|
||||
if speech_threshold_duration >= self._opts.min_speech_duration_ms:
|
||||
pub_speaking = True
|
||||
pub_silence_duration = 0.0
|
||||
pub_speech_duration = speech_threshold_duration
|
||||
|
|
@ -202,13 +202,13 @@ class SileroVADStream(VADStream):
|
|||
inference_duration=inference_duration,
|
||||
))
|
||||
else:
|
||||
silence_threshold_duration += self.WINDOW_DURATION
|
||||
silence_threshold_duration += self.WINDOW_DURATION_MS
|
||||
speech_threshold_duration = 0.0
|
||||
|
||||
if not pub_speaking:
|
||||
_reset_write_cursor()
|
||||
|
||||
if pub_speaking and silence_threshold_duration >= self._opts.min_silence_duration:
|
||||
if pub_speaking and silence_threshold_duration >= self._opts.min_silence_duration_ms:
|
||||
pub_speaking = False
|
||||
pub_silence_duration = silence_threshold_duration
|
||||
|
||||
|
|
|
|||
100
main/xiaozhi-server/core/utils/tokenize.py
Normal file
100
main/xiaozhi-server/core/utils/tokenize.py
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import re
|
||||
|
||||
|
||||
# Punctuation list
|
||||
PUNCTUATIONS = [
|
||||
'!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/',
|
||||
':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|',
|
||||
'}', '~', '±', '—', ''', ''', '"', '"', '…'
|
||||
]
|
||||
|
||||
|
||||
def split_words(
|
||||
text: str,
|
||||
*,
|
||||
ignore_punctuation: bool = True,
|
||||
split_character: bool = False,
|
||||
retain_format: bool = False,
|
||||
) -> list[tuple[str, int, int]]:
|
||||
"""
|
||||
Split text into words, supporting both space-separated languages (like English)
|
||||
and character-based languages (like Chinese, Japanese, Korean, Thai).
|
||||
|
||||
For non-spaced scripts, each character is treated as a separate word if split_character is True.
|
||||
For other languages, words are split by whitespace.
|
||||
|
||||
Returns a list of words with their start and end indices of the original text.
|
||||
"""
|
||||
words: list[tuple[str, int, int]] = []
|
||||
|
||||
# CJK: \u4e00-\u9fff, \u3040-\u30ff, \u3400-\u4dbf
|
||||
# Thai: \u0E00-\u0E7F
|
||||
char_based_codes = (
|
||||
re.compile(
|
||||
r"[\u4e00-\u9fff\u3040-\u30ff\u3400-\u4dbf" # CJK scripts
|
||||
r"\u0E00-\u0E7F]" # Thai
|
||||
)
|
||||
if split_character
|
||||
else None
|
||||
)
|
||||
|
||||
pos = 0
|
||||
word_start = 0
|
||||
|
||||
translation_table = (
|
||||
str.maketrans("", "", "".join(PUNCTUATIONS)) if ignore_punctuation else None
|
||||
)
|
||||
|
||||
def _add_current_word(start: int, end: int) -> None:
|
||||
word = text[start:end]
|
||||
if translation_table and word:
|
||||
word = word.translate(translation_table)
|
||||
|
||||
if word:
|
||||
words.append((word, start, end))
|
||||
|
||||
for pos, char in enumerate(text):
|
||||
if char.isspace():
|
||||
if retain_format and not text[word_start:pos].strip():
|
||||
continue
|
||||
|
||||
# reached whitespace, commit current word
|
||||
_add_current_word(word_start, pos)
|
||||
word_start = pos if retain_format else pos + 1
|
||||
|
||||
elif char_based_codes and char_based_codes.match(char):
|
||||
if word_start < pos:
|
||||
_add_current_word(word_start, pos)
|
||||
|
||||
# commit character as a word
|
||||
_add_current_word(pos, pos + 1)
|
||||
word_start = pos + 1
|
||||
|
||||
# add the last word if there is one
|
||||
_add_current_word(word_start, len(text))
|
||||
|
||||
return words
|
||||
|
||||
|
||||
# ===== usage example =====
|
||||
if __name__ == "__main__":
|
||||
# English
|
||||
print(split_words("Hello world"))
|
||||
# [('Hello', 0, 5), ('world', 6, 11)]
|
||||
|
||||
# Chinese (not split by character)
|
||||
print(split_words("你好世界"))
|
||||
# [('你好世界', 0, 4)]
|
||||
|
||||
# Chinese (split by character)
|
||||
print(split_words("你好世界", split_character=True))
|
||||
# [('你', 0, 1), ('好', 1, 2), ('世', 2, 3), ('界', 3, 4)]
|
||||
|
||||
# Mixed
|
||||
print(split_words("Hello 你好", split_character=True))
|
||||
# [('Hello', 0, 5), ('你', 6, 7), ('好', 7, 8)]
|
||||
|
||||
# Only get word list
|
||||
words_only = [w[0] for w in split_words("Hello 你好", split_character=True)]
|
||||
print(words_only) # ['Hello', '你', '好']
|
||||
print(len(words_only)) # 3
|
||||
|
|
@ -85,6 +85,7 @@ class WebSocketServer:
|
|||
"authorization"
|
||||
][0]
|
||||
if "timezone" in query_params:
|
||||
self.logger.bind(tag=TAG).info(f"timezone: {query_params['timezone'][0]}")
|
||||
websocket.request.headers["timezone"] = query_params["timezone"][0]
|
||||
|
||||
"""处理新连接,每次创建独立的ConnectionHandler"""
|
||||
|
|
|
|||
|
|
@ -420,6 +420,7 @@ ASR:
|
|||
base_url: https://api.groq.com/openai/v1
|
||||
model_name: whisper-large-v3-turbo
|
||||
output_dir: tmp/
|
||||
prompt: "Hello, 这是一个测试。We discuss the plan, 请加上标点符号。"
|
||||
VoskASR:
|
||||
# 官方网站:https://alphacephei.com/vosk/
|
||||
# 配置说明:
|
||||
|
|
@ -483,9 +484,9 @@ VAD:
|
|||
type: silero
|
||||
model_dir: models/snakers4_silero-vad
|
||||
threshold: 0.5 # high threshold to confirm voice
|
||||
min_silence_duration: 0.40 # silence detection duration (s)
|
||||
min_speech_duration: 0.05 # speech detection duration (s)
|
||||
prefix_padding_duration: 0.3 # prefix padding duration (s)
|
||||
min_silence_duration_ms: 400 # silence detection duration (ms)
|
||||
min_speech_duration_ms: 100 # speech detection duration (ms)
|
||||
prefix_padding_duration_ms: 300 # prefix padding duration (ms)
|
||||
activation_threshold: 0.5 # activation threshold
|
||||
sample_rate: 16000 # sample rate
|
||||
# FSMN VAD from FunASR, optimized for Chinese
|
||||
|
|
@ -495,9 +496,14 @@ VAD:
|
|||
model: fsmn-vad
|
||||
model_revision: v2.0.4
|
||||
chunk_size_ms: 100 # streaming chunk size in ms
|
||||
min_silence_duration_ms: 400 # silence detection duration (ms)
|
||||
frame_window_threshold: 3 # sliding window threshold
|
||||
min_silence_duration_ms: 500 # silence detection duration (ms)
|
||||
speech_noise_threshold: 0.6 # speech/noise threshold (0.6-0.9), higher = stricter
|
||||
sil_to_speech_time_thres: 200 # silence->speech transition time (ms), higher = less noise sensitive
|
||||
|
||||
Interruption:
|
||||
enabled: true
|
||||
min_interrupt_speech_duration_ms: 500 # Minimum speech duration before interrupt (ms)
|
||||
min_interrupt_text_length: 5 # Minimum ASR text buffer length before interrupt
|
||||
# Turn Detection: Determines if user has finished speaking
|
||||
# Use NoopTurnDetection to disable, HTTPTurnDetection to enable
|
||||
TurnDetection:
|
||||
|
|
@ -509,7 +515,8 @@ TurnDetection:
|
|||
port: 8002
|
||||
timeout: 0.5 # HTTP request timeout (seconds)
|
||||
endpoint: /turn-detect # API endpoint path
|
||||
buffer_timeout: 10.0 # Max time to accumulate text (seconds)
|
||||
min_endpoint_delay: 500 # Min time to wait after last speech before forcing end of turn (milliseconds)
|
||||
max_endpoint_delay: 2000 # Max time to wait after last speech before forcing end of turn (milliseconds)
|
||||
|
||||
LLM:
|
||||
# 所有openai类型均可以修改超参,以AliLLM为例
|
||||
|
|
@ -1122,8 +1129,9 @@ TTS:
|
|||
# ============================= Module Selection ================================
|
||||
# ===============================================================================
|
||||
selected_module:
|
||||
VAD: SileroVAD
|
||||
TurnDetection: NoopTurnDetection # Set to TenTurnDetection to enable
|
||||
# VAD: FsmnVAD
|
||||
VAD: FsmnVAD
|
||||
TurnDetection: TenTurnDetection # Set to TenTurnDetection to enable
|
||||
ASR: GroqASR
|
||||
# ASR: ByteplusStreamASR
|
||||
# LLM: GroqLLM
|
||||
|
|
|
|||
BIN
main/xiaozhi-server/test/vad/test_audio.mp3
Normal file
BIN
main/xiaozhi-server/test/vad/test_audio.mp3
Normal file
Binary file not shown.
443
main/xiaozhi-server/test/vad/test_fsmn_vad_stream.py
Normal file
443
main/xiaozhi-server/test/vad/test_fsmn_vad_stream.py
Normal file
|
|
@ -0,0 +1,443 @@
|
|||
"""
|
||||
FSMN VAD Stream Test Script
|
||||
|
||||
This script tests FSMN VAD with audio files, simulating the streaming behavior:
|
||||
|
||||
1. Load an audio file
|
||||
2. Convert to 16kHz mono PCM
|
||||
3. Split into 60ms chunks (simulating WebSocket protocol)
|
||||
4. Feed chunks to FSMN VAD stream
|
||||
5. Print VAD events (START_OF_SPEECH, END_OF_SPEECH)
|
||||
|
||||
Usage:
|
||||
python test_fsmn_vad_stream.py <audio_file>
|
||||
python test_fsmn_vad_stream.py --help
|
||||
|
||||
Example:
|
||||
python test_fsmn_vad_stream.py test_audio.wav
|
||||
python test_fsmn_vad_stream.py test_audio.mp3
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import argparse
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Optional, List, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Add project root to path
|
||||
project_root = Path(__file__).parent.parent.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Audio Loading Utilities
|
||||
# ============================================================================
|
||||
|
||||
def load_audio_file(file_path: str, target_sample_rate: int = 16000) -> Tuple[np.ndarray, int]:
|
||||
"""
|
||||
Load audio file and convert to target sample rate.
|
||||
|
||||
Args:
|
||||
file_path: Path to audio file (wav, mp3, etc.)
|
||||
target_sample_rate: Target sample rate (default 16000Hz)
|
||||
|
||||
Returns:
|
||||
Tuple of (audio_samples as int16 numpy array, sample_rate)
|
||||
"""
|
||||
try:
|
||||
import librosa
|
||||
except ImportError:
|
||||
print("Error: librosa is required. Install with: pip install librosa")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Loading audio file: {file_path}")
|
||||
|
||||
# Load audio with librosa (auto-converts to mono, resamples)
|
||||
audio, sr = librosa.load(file_path, sr=target_sample_rate, mono=True)
|
||||
|
||||
# Convert float32 [-1, 1] to int16 [-32768, 32767]
|
||||
audio_int16 = (audio * 32767).astype(np.int16)
|
||||
|
||||
duration = len(audio_int16) / target_sample_rate
|
||||
print(f" Sample rate: {sr}Hz")
|
||||
print(f" Duration: {duration:.2f}s")
|
||||
print(f" Samples: {len(audio_int16)}")
|
||||
|
||||
return audio_int16, sr
|
||||
|
||||
|
||||
def split_audio_to_chunks(audio: np.ndarray, chunk_duration_ms: int, sample_rate: int) -> List[bytes]:
|
||||
"""
|
||||
Split audio into fixed-duration chunks.
|
||||
|
||||
Args:
|
||||
audio: Audio samples as int16 numpy array
|
||||
chunk_duration_ms: Duration of each chunk in milliseconds
|
||||
sample_rate: Sample rate in Hz
|
||||
|
||||
Returns:
|
||||
List of PCM byte chunks
|
||||
"""
|
||||
samples_per_chunk = int(chunk_duration_ms * sample_rate / 1000)
|
||||
chunks = []
|
||||
|
||||
for i in range(0, len(audio), samples_per_chunk):
|
||||
chunk = audio[i:i + samples_per_chunk]
|
||||
# Pad last chunk if necessary
|
||||
if len(chunk) < samples_per_chunk:
|
||||
chunk = np.pad(chunk, (0, samples_per_chunk - len(chunk)), mode='constant')
|
||||
chunks.append(chunk.tobytes())
|
||||
|
||||
print(f"Split into {len(chunks)} chunks of {chunk_duration_ms}ms each")
|
||||
return chunks
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# VAD Event Types (copied to avoid import issues)
|
||||
# ============================================================================
|
||||
|
||||
class VADEventType(Enum):
|
||||
"""VAD event types"""
|
||||
START_OF_SPEECH = "start_of_speech"
|
||||
INFERENCE_DONE = "inference_done"
|
||||
END_OF_SPEECH = "end_of_speech"
|
||||
|
||||
|
||||
@dataclass
|
||||
class VADEvent:
|
||||
"""VAD event data structure"""
|
||||
type: VADEventType
|
||||
speech_duration: float = 0.0
|
||||
silence_duration: float = 0.0
|
||||
speaking: bool = False
|
||||
audio_data: bytes = b""
|
||||
inference_duration: float = 0.0
|
||||
|
||||
def __repr__(self) -> str:
|
||||
audio_len_ms = len(self.audio_data) / 32 if self.audio_data else 0
|
||||
return (
|
||||
f"VADEvent(type={self.type.value}, "
|
||||
f"speaking={self.speaking}, "
|
||||
f"speech={self.speech_duration:.2f}s, "
|
||||
f"silence={self.silence_duration:.2f}s, "
|
||||
f"audio={audio_len_ms:.0f}ms, "
|
||||
f"inference={self.inference_duration*1000:.1f}ms)"
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# FSMN VAD Test Runner
|
||||
# ============================================================================
|
||||
|
||||
class FsmnVADTester:
|
||||
"""Test FSMN VAD with audio file input"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
chunk_size_ms: int = 100,
|
||||
min_silence_duration_ms: int = 500,
|
||||
speech_noise_threshold: float = 0.6,
|
||||
prefix_padding_duration: float = 0.3,
|
||||
):
|
||||
self.chunk_size_ms = chunk_size_ms
|
||||
self.min_silence_duration_ms = min_silence_duration_ms
|
||||
self.speech_noise_threshold = speech_noise_threshold
|
||||
self.prefix_padding_duration = prefix_padding_duration
|
||||
self.sample_rate = 16000
|
||||
|
||||
# Initialize FSMN model
|
||||
self._init_model()
|
||||
|
||||
def _init_model(self):
|
||||
"""Initialize FSMN VAD model"""
|
||||
try:
|
||||
from funasr import AutoModel
|
||||
except ImportError:
|
||||
print("Error: funasr is required. Install with: pip install funasr")
|
||||
sys.exit(1)
|
||||
|
||||
print("\nInitializing FSMN VAD model...")
|
||||
self.model = AutoModel(
|
||||
model="fsmn-vad",
|
||||
model_revision="v2.0.4",
|
||||
disable_pbar=True, # disable progress bar
|
||||
max_end_silence_time=self.min_silence_duration_ms,
|
||||
speech_noise_thres=self.speech_noise_threshold,
|
||||
)
|
||||
print("Model initialized.")
|
||||
|
||||
def process_audio_file(self, file_path: str, input_chunk_ms: int = 60, verbose: bool = False) -> List[dict]:
|
||||
"""
|
||||
Process audio file through FSMN VAD.
|
||||
|
||||
Args:
|
||||
file_path: Path to audio file
|
||||
input_chunk_ms: Input chunk size in milliseconds (simulating WebSocket)
|
||||
|
||||
Returns:
|
||||
List of VAD events with timestamps
|
||||
"""
|
||||
# Load and split audio
|
||||
audio, sr = load_audio_file(file_path, self.sample_rate)
|
||||
input_chunks = split_audio_to_chunks(audio, input_chunk_ms, self.sample_rate)
|
||||
|
||||
# FSMN processing parameters
|
||||
chunk_samples = int(self.chunk_size_ms * self.sample_rate / 1000)
|
||||
chunk_bytes = chunk_samples * 2 # int16
|
||||
|
||||
# Buffers
|
||||
input_buffer = bytearray()
|
||||
inference_buffer = bytearray()
|
||||
|
||||
# Prefix padding
|
||||
prefix_padding_bytes = int(self.prefix_padding_duration * self.sample_rate) * 2
|
||||
max_speech_bytes = 60 * self.sample_rate * 2 + prefix_padding_bytes
|
||||
speech_buffer = bytearray(max_speech_bytes)
|
||||
speech_buffer_index = 0
|
||||
|
||||
# State
|
||||
fsmn_cache = {}
|
||||
speaking = False
|
||||
speech_start_ms = 0
|
||||
speech_duration = 0.0
|
||||
silence_duration = 0.0
|
||||
|
||||
# Results
|
||||
events = []
|
||||
current_time_ms = 0
|
||||
total_inference_time = 0.0
|
||||
inference_count = 0
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Processing audio with FSMN VAD")
|
||||
print(f"{'='*60}")
|
||||
print(f"Input chunk size: {input_chunk_ms}ms")
|
||||
print(f"FSMN chunk size: {self.chunk_size_ms}ms")
|
||||
print(f"Min silence duration: {self.min_silence_duration_ms}ms")
|
||||
print(f"Prefix padding: {self.prefix_padding_duration*1000:.0f}ms")
|
||||
print()
|
||||
|
||||
def reset_write_cursor():
|
||||
nonlocal speech_buffer_index
|
||||
if speech_buffer_index <= prefix_padding_bytes:
|
||||
return
|
||||
padding_data = speech_buffer[
|
||||
speech_buffer_index - prefix_padding_bytes : speech_buffer_index
|
||||
]
|
||||
speech_buffer[: prefix_padding_bytes] = padding_data
|
||||
speech_buffer_index = prefix_padding_bytes
|
||||
|
||||
# Process chunks
|
||||
for chunk_idx, pcm_chunk in enumerate(input_chunks):
|
||||
input_buffer.extend(pcm_chunk)
|
||||
inference_buffer.extend(pcm_chunk)
|
||||
current_time_ms += input_chunk_ms
|
||||
|
||||
# Process complete FSMN chunks
|
||||
while len(inference_buffer) >= chunk_bytes:
|
||||
inference_start = time.perf_counter()
|
||||
|
||||
# Convert to float32
|
||||
chunk_int16 = np.frombuffer(inference_buffer[:chunk_bytes], dtype=np.int16)
|
||||
chunk_float32 = chunk_int16.astype(np.float32) / 32768.0
|
||||
|
||||
# Run FSMN inference (is_final=False for streaming scenario)
|
||||
res = self.model.generate(
|
||||
input=chunk_float32,
|
||||
cache=fsmn_cache,
|
||||
is_final=False,
|
||||
chunk_size=self.chunk_size_ms,
|
||||
)
|
||||
|
||||
inference_duration = time.perf_counter() - inference_start
|
||||
total_inference_time += inference_duration
|
||||
inference_count += 1
|
||||
|
||||
# Verbose output: show raw FSMN result
|
||||
if verbose:
|
||||
value = res[0].get("value", []) if res and len(res) > 0 else []
|
||||
print(f" [{current_time_ms:6.0f}ms] inference #{inference_count:3d} | "
|
||||
f"result={value} | "
|
||||
f"time={inference_duration*1000:.2f}ms")
|
||||
|
||||
# Copy to speech buffer
|
||||
available_space = len(speech_buffer) - speech_buffer_index
|
||||
to_copy = min(available_space, chunk_bytes)
|
||||
if to_copy > 0:
|
||||
speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_buffer[:to_copy]
|
||||
speech_buffer_index += to_copy
|
||||
|
||||
# Parse FSMN result
|
||||
if res and len(res) > 0 and res[0].get("value"):
|
||||
seg = res[0]["value"][0]
|
||||
seg_start, seg_end = seg[0], seg[1]
|
||||
|
||||
if seg_start >= 0 and seg_end == -1:
|
||||
# Speech start
|
||||
if not speaking:
|
||||
speaking = True
|
||||
speech_start_ms = seg_start
|
||||
silence_duration = 0.0
|
||||
|
||||
audio_data = bytes(speech_buffer[:speech_buffer_index])
|
||||
events.append({
|
||||
"time_ms": current_time_ms,
|
||||
"type": "START_OF_SPEECH",
|
||||
"seg_start_ms": seg_start,
|
||||
"audio_duration_ms": len(audio_data) / 32,
|
||||
"inference_ms": inference_duration * 1000,
|
||||
})
|
||||
print(f"🎤 [{current_time_ms:6.0f}ms] START_OF_SPEECH @{seg_start}ms | "
|
||||
f"audio={len(audio_data)/32:.0f}ms | "
|
||||
f"inference={inference_duration*1000:.1f}ms")
|
||||
|
||||
elif seg_start == -1 and seg_end > 0:
|
||||
# Speech end
|
||||
if speaking:
|
||||
speaking = False
|
||||
speech_duration_ms = seg_end - speech_start_ms
|
||||
speech_duration = speech_duration_ms / 1000
|
||||
|
||||
audio_data = bytes(speech_buffer[:speech_buffer_index])
|
||||
events.append({
|
||||
"time_ms": current_time_ms,
|
||||
"type": "END_OF_SPEECH",
|
||||
"seg_end_ms": seg_end,
|
||||
"speech_duration_ms": speech_duration_ms,
|
||||
"audio_duration_ms": len(audio_data) / 32,
|
||||
"inference_ms": inference_duration * 1000,
|
||||
})
|
||||
print(f"🔇 [{current_time_ms:6.0f}ms] END_OF_SPEECH @{seg_end}ms | "
|
||||
f"speech={speech_duration:.2f}s | "
|
||||
f"audio={len(audio_data)/32:.0f}ms | "
|
||||
f"inference={inference_duration*1000:.1f}ms")
|
||||
|
||||
# Reset state
|
||||
speech_duration = 0.0
|
||||
fsmn_cache = {}
|
||||
reset_write_cursor()
|
||||
|
||||
elif seg_start > 0 and seg_end > 0:
|
||||
# Short segment (ignored)
|
||||
print(f" [{current_time_ms:6.0f}ms] SHORT_SEGMENT [{seg_start}, {seg_end}]ms (ignored)")
|
||||
|
||||
# Update state
|
||||
if speaking:
|
||||
speech_duration += self.chunk_size_ms / 1000
|
||||
else:
|
||||
silence_duration += self.chunk_size_ms / 1000
|
||||
reset_write_cursor()
|
||||
|
||||
# Remove processed data
|
||||
del inference_buffer[:chunk_bytes]
|
||||
del input_buffer[:to_copy]
|
||||
|
||||
# Summary
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Summary")
|
||||
print(f"{'='*60}")
|
||||
print(f"Total input chunks: {len(input_chunks)}")
|
||||
print(f"Total FSMN inferences: {inference_count}")
|
||||
print(f"Total inference time: {total_inference_time*1000:.1f}ms")
|
||||
print(f"Average inference time: {total_inference_time/inference_count*1000:.1f}ms" if inference_count > 0 else "N/A")
|
||||
print(f"Speech segments detected: {len([e for e in events if e['type'] == 'START_OF_SPEECH'])}")
|
||||
|
||||
return events
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Test FSMN VAD with audio file",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
python test_fsmn_vad_stream.py test_audio.wav
|
||||
python test_fsmn_vad_stream.py test_audio.mp3 --input-chunk-ms 100
|
||||
python test_fsmn_vad_stream.py test_audio.wav --min-silence-ms 800
|
||||
"""
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"audio_file",
|
||||
type=str,
|
||||
help="Path to audio file (wav, mp3, etc.)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--input-chunk-ms",
|
||||
type=int,
|
||||
default=60,
|
||||
help="Input chunk size in milliseconds (default: 60, simulating WebSocket protocol)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--fsmn-chunk-ms",
|
||||
type=int,
|
||||
default=100,
|
||||
help="FSMN inference chunk size in milliseconds (default: 100)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--min-silence-ms",
|
||||
type=int,
|
||||
default=500,
|
||||
help="Minimum silence duration to detect speech end (default: 500)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--speech-noise-threshold",
|
||||
type=float,
|
||||
default=0.6,
|
||||
help="Speech noise threshold (default: 0.6)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--prefix-padding",
|
||||
type=float,
|
||||
default=0.3,
|
||||
help="Prefix padding duration in seconds (default: 0.3)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-v", "--verbose",
|
||||
action="store_true",
|
||||
help="Show raw FSMN inference output for each chunk"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Validate audio file
|
||||
if not os.path.exists(args.audio_file):
|
||||
print(f"Error: Audio file not found: {args.audio_file}")
|
||||
sys.exit(1)
|
||||
|
||||
# Create tester and run
|
||||
tester = FsmnVADTester(
|
||||
chunk_size_ms=args.fsmn_chunk_ms,
|
||||
min_silence_duration_ms=args.min_silence_ms,
|
||||
speech_noise_threshold=args.speech_noise_threshold,
|
||||
prefix_padding_duration=args.prefix_padding,
|
||||
)
|
||||
|
||||
events = tester.process_audio_file(
|
||||
args.audio_file,
|
||||
input_chunk_ms=args.input_chunk_ms,
|
||||
verbose=args.verbose,
|
||||
)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"All Events")
|
||||
print(f"{'='*60}")
|
||||
for event in events:
|
||||
print(f" {event}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
BIN
main/xiaozhi-server/test/vad/test_vad_two_sentences.wav
Normal file
BIN
main/xiaozhi-server/test/vad/test_vad_two_sentences.wav
Normal file
Binary file not shown.
Loading…
Reference in a new issue