mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: support message tag and reconnected
This commit is contained in:
parent
d556aa8396
commit
69b59fb536
10 changed files with 190 additions and 43 deletions
|
|
@ -29,6 +29,7 @@ from core.providers.tts.default import DefaultTTS
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from core.utils.dialogue import Message, Dialogue
|
from core.utils.dialogue import Message, Dialogue
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
from core.handle.textHandle import handleTextMessage
|
from core.handle.textHandle import handleTextMessage
|
||||||
from core.providers.tools.unified_tool_handler import UnifiedToolHandler
|
from core.providers.tools.unified_tool_handler import UnifiedToolHandler
|
||||||
from plugins_func.loadplugins import auto_import_modules
|
from plugins_func.loadplugins import auto_import_modules
|
||||||
|
|
@ -168,6 +169,9 @@ class ConnectionHandler:
|
||||||
self._voice_closing = None
|
self._voice_closing = None
|
||||||
self._language = None
|
self._language = None
|
||||||
|
|
||||||
|
# reconnected flag
|
||||||
|
self.reconnected: bool = False
|
||||||
|
|
||||||
async def handle_connection(self, ws):
|
async def handle_connection(self, ws):
|
||||||
try:
|
try:
|
||||||
# 获取并验证headers
|
# 获取并验证headers
|
||||||
|
|
@ -189,6 +193,9 @@ class ConnectionHandler:
|
||||||
# 认证通过,继续处理
|
# 认证通过,继续处理
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
|
|
||||||
|
# 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}")
|
||||||
# 检查是否来自MQTT连接
|
# 检查是否来自MQTT连接
|
||||||
request_path = ws.request.path
|
request_path = ws.request.path
|
||||||
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
|
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
|
||||||
|
|
@ -450,12 +457,13 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
|
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
|
||||||
|
|
||||||
opening_sentence_id = str(uuid.uuid4().hex)
|
opening_sentence_id = str(uuid.uuid4().hex)
|
||||||
|
message_tag = MessageTag.OPENING
|
||||||
# FIRST: Start session
|
# FIRST: Start session
|
||||||
self.tts.tts_text_queue.put(TTSMessageDTO(
|
self.tts.tts_text_queue.put(TTSMessageDTO(
|
||||||
sentence_id=opening_sentence_id,
|
sentence_id=opening_sentence_id,
|
||||||
sentence_type=SentenceType.FIRST,
|
sentence_type=SentenceType.FIRST,
|
||||||
content_type=ContentType.ACTION,
|
content_type=ContentType.ACTION,
|
||||||
|
message_tag=message_tag,
|
||||||
))
|
))
|
||||||
|
|
||||||
self.tts.tts_text_queue.put(TTSMessageDTO(
|
self.tts.tts_text_queue.put(TTSMessageDTO(
|
||||||
|
|
@ -463,6 +471,7 @@ class ConnectionHandler:
|
||||||
sentence_type=SentenceType.MIDDLE,
|
sentence_type=SentenceType.MIDDLE,
|
||||||
content_type=ContentType.TEXT,
|
content_type=ContentType.TEXT,
|
||||||
content_detail=self._voice_opening,
|
content_detail=self._voice_opening,
|
||||||
|
message_tag=message_tag,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -470,6 +479,7 @@ class ConnectionHandler:
|
||||||
sentence_id=opening_sentence_id,
|
sentence_id=opening_sentence_id,
|
||||||
sentence_type=SentenceType.LAST,
|
sentence_type=SentenceType.LAST,
|
||||||
content_type=ContentType.ACTION,
|
content_type=ContentType.ACTION,
|
||||||
|
message_tag=message_tag,
|
||||||
))
|
))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import time
|
||||||
import base64
|
import base64
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any
|
||||||
from config.live_agent_api_client import report_chat_message
|
from config.live_agent_api_client import report_chat_message
|
||||||
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -112,7 +112,7 @@ def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_t
|
||||||
conn.logger.bind(tag=TAG).error(f"Chat message report failed: {e}")
|
conn.logger.bind(tag=TAG).error(f"Chat message report failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
def enqueue_tts_report(conn, text, opus_data):
|
def enqueue_tts_report(conn, text, opus_data, message_tag=MessageTag.NORMAL):
|
||||||
"""Enqueue TTS data for reporting (Agent message)
|
"""Enqueue TTS data for reporting (Agent message)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -125,6 +125,10 @@ def enqueue_tts_report(conn, text, opus_data):
|
||||||
return
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
|
# if the message is opening and the connection is reconnected, skip the report
|
||||||
|
if message_tag == MessageTag.OPENING and conn.reconnected:
|
||||||
|
conn.logger.bind(tag=TAG).info(f"Opening message is reconnected, skipping report")
|
||||||
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Remove emotion tags from text before reporting
|
# Remove emotion tags from text before reporting
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,19 @@ import time
|
||||||
import asyncio
|
import asyncio
|
||||||
from core.utils import textUtils
|
from core.utils import textUtils
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data
|
||||||
from core.providers.tts.dto.dto import SentenceType
|
from core.providers.tts.dto.dto import (
|
||||||
|
SentenceType,
|
||||||
|
MessageTag,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def sendAudioMessage(conn, sentenceType, audios, text):
|
async def sendAudioMessage(conn, sentenceType, audios, text, message_tag=MessageTag.NORMAL):
|
||||||
if conn.tts.tts_audio_first_sentence:
|
if conn.tts.tts_audio_first_sentence:
|
||||||
conn.tts.tts_audio_first_sentence = False
|
conn.tts.tts_audio_first_sentence = False
|
||||||
await send_tts_message(conn, "start", None)
|
await send_tts_message(conn, "start", None, message_tag)
|
||||||
|
|
||||||
# 记录首句 TTS 播放时间(端到端延迟的终点)
|
# 记录首句 TTS 播放时间(端到端延迟的终点)
|
||||||
first_audio_time = time.time() * 1000
|
first_audio_time = time.time() * 1000
|
||||||
|
|
@ -34,16 +38,16 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
|
||||||
)
|
)
|
||||||
|
|
||||||
if sentenceType == SentenceType.FIRST:
|
if sentenceType == SentenceType.FIRST:
|
||||||
await send_tts_message(conn, "sentence_start", text)
|
await send_tts_message(conn, "sentence_start", text, message_tag)
|
||||||
|
|
||||||
await sendAudio(conn, audios)
|
await sendAudio(conn, audios, message_tag=message_tag)
|
||||||
# 发送句子开始消息
|
# 发送句子开始消息
|
||||||
if sentenceType is not SentenceType.MIDDLE:
|
if sentenceType is not SentenceType.MIDDLE:
|
||||||
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
|
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
|
||||||
|
|
||||||
# 发送结束消息(如果是最后一个文本)
|
# 发送结束消息(如果是最后一个文本)
|
||||||
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
||||||
await send_tts_message(conn, "stop", None)
|
await send_tts_message(conn, "stop", None, message_tag)
|
||||||
conn.client_is_speaking = False
|
conn.client_is_speaking = False
|
||||||
if conn.close_after_chat:
|
if conn.close_after_chat:
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
@ -95,9 +99,19 @@ async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
|
||||||
complete_packet = bytes(header) + opus_packet
|
complete_packet = bytes(header) + opus_packet
|
||||||
await conn.websocket.send(complete_packet)
|
await conn.websocket.send(complete_packet)
|
||||||
|
|
||||||
|
async def _send_audio_with_header(conn, audios, message_tag=MessageTag.NORMAL):
|
||||||
|
if audios is None or len(audios) == 0:
|
||||||
|
return
|
||||||
|
header = bytearray(16)
|
||||||
|
header[0] = 1 # default value is 1 for audio message
|
||||||
|
header[1] = message_tag.value
|
||||||
|
# 3-15 bytes is reserved for future use, currently not used
|
||||||
|
complete_packet = bytes(header) + audios
|
||||||
|
await conn.websocket.send(complete_packet)
|
||||||
|
|
||||||
|
|
||||||
# 播放音频
|
# 播放音频
|
||||||
async def sendAudio(conn, audios, frame_duration=60):
|
async def sendAudio(conn, audios, frame_duration=60, message_tag=MessageTag.NORMAL):
|
||||||
"""
|
"""
|
||||||
发送单个opus包,支持流控
|
发送单个opus包,支持流控
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -157,7 +171,7 @@ async def sendAudio(conn, audios, frame_duration=60):
|
||||||
await _send_to_mqtt_gateway(conn, audios, timestamp, sequence)
|
await _send_to_mqtt_gateway(conn, audios, timestamp, sequence)
|
||||||
else:
|
else:
|
||||||
# 直接发送opus数据包,不添加头部
|
# 直接发送opus数据包,不添加头部
|
||||||
await conn.websocket.send(audios)
|
await _send_audio_with_header(conn, audios, message_tag)
|
||||||
|
|
||||||
# 更新流控状态
|
# 更新流控状态
|
||||||
flow_control["packet_count"] += 1
|
flow_control["packet_count"] += 1
|
||||||
|
|
@ -180,7 +194,7 @@ async def sendAudio(conn, audios, frame_duration=60):
|
||||||
await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence)
|
await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence)
|
||||||
else:
|
else:
|
||||||
# 直接发送预缓冲包,不添加头部
|
# 直接发送预缓冲包,不添加头部
|
||||||
await conn.websocket.send(audios[i])
|
await _send_audio_with_header(conn, audios[i], message_tag)
|
||||||
remaining_audios = audios[pre_buffer_frames:]
|
remaining_audios = audios[pre_buffer_frames:]
|
||||||
|
|
||||||
# 播放剩余音频帧
|
# 播放剩余音频帧
|
||||||
|
|
@ -212,16 +226,22 @@ async def sendAudio(conn, audios, frame_duration=60):
|
||||||
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
|
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
|
||||||
else:
|
else:
|
||||||
# 直接发送opus数据包,不添加头部
|
# 直接发送opus数据包,不添加头部
|
||||||
await conn.websocket.send(opus_packet)
|
await _send_audio_with_header(conn, opus_packet, message_tag)
|
||||||
|
|
||||||
play_position += frame_duration
|
play_position += frame_duration
|
||||||
|
|
||||||
|
|
||||||
async def send_tts_message(conn, state, text=None):
|
async def send_tts_message(conn, state, text=None, message_tag=MessageTag.NORMAL):
|
||||||
"""发送 TTS 状态消息"""
|
"""发送 TTS 状态消息"""
|
||||||
if text is None and state == "sentence_start":
|
if text is None and state == "sentence_start":
|
||||||
return
|
return
|
||||||
message = {"type": "tts", "state": state, "session_id": conn.session_id}
|
|
||||||
|
message = {
|
||||||
|
"type": "tts",
|
||||||
|
"state": state,
|
||||||
|
"session_id": conn.session_id,
|
||||||
|
"message_tag": message_tag.value,
|
||||||
|
}
|
||||||
if text is not None:
|
if text is not None:
|
||||||
message["text"] = textUtils.check_emoji(text)
|
message["text"] = textUtils.check_emoji(text)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
||||||
from core.handle.textMessageProcessor import TextMessageProcessor
|
from core.handle.textMessageProcessor import TextMessageProcessor
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
# 全局处理器注册表
|
# 全局处理器注册表
|
||||||
message_registry = TextMessageHandlerRegistry()
|
message_registry = TextMessageHandlerRegistry()
|
||||||
|
|
@ -11,4 +13,5 @@ message_processor = TextMessageProcessor(message_registry)
|
||||||
|
|
||||||
async def handleTextMessage(conn, message):
|
async def handleTextMessage(conn, message):
|
||||||
"""处理文本消息"""
|
"""处理文本消息"""
|
||||||
|
logger.bind(tag=TAG).info(f"收到文本消息: {message}")
|
||||||
await message_processor.process_message(conn, message)
|
await message_processor.process_message(conn, message)
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import queue
|
||||||
import asyncio
|
import asyncio
|
||||||
import threading
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
|
from typing import Optional
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from core.utils import p3
|
from core.utils import p3
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
@ -23,6 +24,8 @@ from core.providers.tts.dto.dto import (
|
||||||
SentenceType,
|
SentenceType,
|
||||||
ContentType,
|
ContentType,
|
||||||
InterfaceType,
|
InterfaceType,
|
||||||
|
TTSAudioDTO,
|
||||||
|
MessageTag,
|
||||||
)
|
)
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -39,10 +42,12 @@ class TTSProviderBase(ABC):
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
self.audio_file_type = "wav"
|
self.audio_file_type = "wav"
|
||||||
self.output_file = config.get("output_dir", "tmp/")
|
self.output_file = config.get("output_dir", "tmp/")
|
||||||
self.tts_text_queue = queue.Queue()
|
self.tts_text_queue = queue.Queue[TTSMessageDTO]()
|
||||||
self.tts_audio_queue = queue.Queue()
|
# TODO: for long-term, we need to use TTSAudioDTO instead of tuple[SentenceType, Optional[bytes], Optional[str]]
|
||||||
|
self.tts_audio_queue = queue.Queue[TTSAudioDTO | tuple[SentenceType, Optional[bytes], Optional[str]]]()
|
||||||
self.tts_audio_first_sentence = True
|
self.tts_audio_first_sentence = True
|
||||||
self.before_stop_play_files = []
|
self.before_stop_play_files = []
|
||||||
|
self._message_tag = MessageTag.NORMAL
|
||||||
|
|
||||||
self.tts_text_buff = []
|
self.tts_text_buff = []
|
||||||
self.punctuations = (
|
self.punctuations = (
|
||||||
|
|
@ -331,9 +336,22 @@ class TTSProviderBase(ABC):
|
||||||
text = None
|
text = None
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
sentence_type, audio_datas, text = self.tts_audio_queue.get(
|
tts_audio_message = self.tts_audio_queue.get(
|
||||||
timeout=0.1
|
timeout=0.1
|
||||||
)
|
)
|
||||||
|
if isinstance(tts_audio_message, TTSAudioDTO):
|
||||||
|
sentence_type = tts_audio_message.sentence_type
|
||||||
|
audio_datas = tts_audio_message.audio_data
|
||||||
|
text = tts_audio_message.text
|
||||||
|
message_tag = tts_audio_message.message_tag
|
||||||
|
elif isinstance(tts_audio_message, tuple):
|
||||||
|
sentence_type = tts_audio_message[0]
|
||||||
|
audio_datas = tts_audio_message[1]
|
||||||
|
text = tts_audio_message[2]
|
||||||
|
message_tag = MessageTag.NORMAL # tuple format doesn't have message_tag
|
||||||
|
else:
|
||||||
|
logger.bind(tag=TAG).warning(f"Unknown tts_audio_message type: {type(tts_audio_message)}")
|
||||||
|
continue
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
if self.conn.stop_event.is_set():
|
if self.conn.stop_event.is_set():
|
||||||
break
|
break
|
||||||
|
|
@ -349,7 +367,7 @@ class TTSProviderBase(ABC):
|
||||||
if sentence_type is not SentenceType.MIDDLE:
|
if sentence_type is not SentenceType.MIDDLE:
|
||||||
# 上报TTS数据
|
# 上报TTS数据
|
||||||
if enqueue_text is not None and enqueue_audio is not None:
|
if enqueue_text is not None and enqueue_audio is not None:
|
||||||
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio)
|
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag)
|
||||||
enqueue_audio = []
|
enqueue_audio = []
|
||||||
enqueue_text = text
|
enqueue_text = text
|
||||||
|
|
||||||
|
|
@ -366,7 +384,7 @@ class TTSProviderBase(ABC):
|
||||||
|
|
||||||
# 异步发送音频(不阻塞等待)
|
# 异步发送音频(不阻塞等待)
|
||||||
last_send_future = asyncio.run_coroutine_threadsafe(
|
last_send_future = asyncio.run_coroutine_threadsafe(
|
||||||
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
|
sendAudioMessage(self.conn, sentence_type, audio_datas, text, message_tag),
|
||||||
self.conn.loop,
|
self.conn.loop,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Union, Optional
|
from typing import Union, Optional
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
|
||||||
class SentenceType(Enum):
|
class SentenceType(Enum):
|
||||||
|
|
@ -22,6 +23,11 @@ class InterfaceType(Enum):
|
||||||
SINGLE_STREAM = "SINGLE_STREAM" # 单流式
|
SINGLE_STREAM = "SINGLE_STREAM" # 单流式
|
||||||
NON_STREAM = "NON_STREAM" # 非流式
|
NON_STREAM = "NON_STREAM" # 非流式
|
||||||
|
|
||||||
|
class MessageTag(Enum):
|
||||||
|
NORMAL = 0
|
||||||
|
OPENING = 1
|
||||||
|
CLOSING = 2
|
||||||
|
|
||||||
|
|
||||||
class TTSMessageDTO:
|
class TTSMessageDTO:
|
||||||
def __init__(
|
def __init__(
|
||||||
|
|
@ -35,9 +41,25 @@ class TTSMessageDTO:
|
||||||
content_detail: Optional[str] = None,
|
content_detail: Optional[str] = None,
|
||||||
# 如果内容类型为文件,则需要传入文件路径
|
# 如果内容类型为文件,则需要传入文件路径
|
||||||
content_file: Optional[str] = None,
|
content_file: Optional[str] = None,
|
||||||
|
# message tag: identify the tag of the message
|
||||||
|
message_tag: MessageTag = MessageTag.NORMAL,
|
||||||
):
|
):
|
||||||
self.sentence_id = sentence_id
|
self.sentence_id = sentence_id
|
||||||
self.sentence_type = sentence_type
|
self.sentence_type = sentence_type
|
||||||
self.content_type = content_type
|
self.content_type = content_type
|
||||||
self.content_detail = content_detail
|
self.content_detail = content_detail
|
||||||
self.content_file = content_file
|
self.content_file = content_file
|
||||||
|
self.message_tag = message_tag
|
||||||
|
|
||||||
|
class TTSAudioDTO:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
sentence_type: SentenceType,
|
||||||
|
audio_data: Optional[bytes] = None,
|
||||||
|
text: Optional[str] = None,
|
||||||
|
message_tag: MessageTag = MessageTag.NORMAL,
|
||||||
|
):
|
||||||
|
self.sentence_type = sentence_type
|
||||||
|
self.audio_data = audio_data
|
||||||
|
self.text = text
|
||||||
|
self.message_tag = message_tag
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,13 @@ from core.utils.tts import MarkdownCleaner
|
||||||
from core.utils import opus_encoder_utils
|
from core.utils import opus_encoder_utils
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
from core.providers.tts.dto.dto import (
|
||||||
|
SentenceType,
|
||||||
|
ContentType,
|
||||||
|
InterfaceType,
|
||||||
|
TTSAudioDTO,
|
||||||
|
MessageTag,
|
||||||
|
)
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -162,6 +168,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
self._first_sent = False
|
self._first_sent = False
|
||||||
self._session_text_buffer = []
|
self._session_text_buffer = []
|
||||||
self.conn._latency_tts_first_text_time = None # Reset TTS input time
|
self.conn._latency_tts_first_text_time = None # Reset TTS input time
|
||||||
|
self._message_tag = message.message_tag
|
||||||
|
|
||||||
elif self.conn.client_abort:
|
elif self.conn.client_abort:
|
||||||
# ========== Interruption ==========
|
# ========== Interruption ==========
|
||||||
|
|
@ -295,7 +302,13 @@ class TTSProvider(TTSProviderBase):
|
||||||
if not self._first_sent:
|
if not self._first_sent:
|
||||||
self._first_sent = True
|
self._first_sent = True
|
||||||
report_text = ''.join(self._session_text_buffer) if self._session_text_buffer else None
|
report_text = ''.join(self._session_text_buffer) if self._session_text_buffer else None
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, None, report_text))
|
|
||||||
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.FIRST,
|
||||||
|
audio_data=None,
|
||||||
|
text=report_text,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
|
|
||||||
# PCM -> Opus conversion
|
# PCM -> Opus conversion
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
self.opus_encoder.encode_pcm_to_opus_stream(
|
||||||
|
|
@ -318,8 +331,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
# 发送 LAST 触发客户端 stop 和最终上报
|
# 发送 LAST 触发客户端 stop 和最终上报
|
||||||
# 不再发送 FIRST,避免清空之前累积的音频
|
# 不再发送 FIRST,避免清空之前累积的音频
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, None, None))
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.LAST,
|
||||||
|
audio_data=None,
|
||||||
|
text=None,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
# 清理状态
|
# 清理状态
|
||||||
self._session_text_buffer = []
|
self._session_text_buffer = []
|
||||||
self.conn.tts_MessageText = None
|
self.conn.tts_MessageText = None
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,10 @@ class WebSocketServer:
|
||||||
port = int(server_config.get("port", 8000))
|
port = int(server_config.get("port", 8000))
|
||||||
|
|
||||||
async with websockets.serve(
|
async with websockets.serve(
|
||||||
self._handle_connection, host, port, process_request=self._http_response
|
self._handle_connection, host, port, process_request=self._http_response,
|
||||||
|
ping_interval=30, # Interval between keepalive pings in seconds
|
||||||
|
ping_timeout=20, # Timeout for keepalive pings in seconds
|
||||||
|
close_timeout=10, # Timeout for closing the connection in seconds
|
||||||
):
|
):
|
||||||
await asyncio.Future()
|
await asyncio.Future()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -207,7 +207,7 @@ language: zh
|
||||||
|
|
||||||
# 结束语prompt
|
# 结束语prompt
|
||||||
end_prompt:
|
end_prompt:
|
||||||
enable: true # 是否开启结束语
|
enable: false # 是否开启结束语
|
||||||
# 结束语
|
# 结束语
|
||||||
prompt: |
|
prompt: |
|
||||||
请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧!
|
请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧!
|
||||||
|
|
|
||||||
|
|
@ -1009,20 +1009,40 @@
|
||||||
|
|
||||||
if (message.type === 'hello') {
|
if (message.type === 'hello') {
|
||||||
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
|
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
|
||||||
|
// Check if this is a reconnect - if opening was played before, skip it
|
||||||
|
if (openingPlayedInSession) {
|
||||||
|
skipCurrentOpening = true;
|
||||||
|
log('检测到重连,将跳过开场白', 'info');
|
||||||
|
}
|
||||||
} else if (message.type === 'tts') {
|
} else if (message.type === 'tts') {
|
||||||
// TTS状态消息
|
// TTS状态消息
|
||||||
|
const msgTag = message.message_tag !== undefined ? message.message_tag : MESSAGE_TAG.NORMAL;
|
||||||
|
const tagName = msgTag === MESSAGE_TAG.OPENING ? '[开场白]' :
|
||||||
|
msgTag === MESSAGE_TAG.CLOSING ? '[结束语]' : '';
|
||||||
|
|
||||||
if (message.state === 'start') {
|
if (message.state === 'start') {
|
||||||
log('服务器开始发送语音', 'info');
|
log(`服务器开始发送语音 ${tagName}`, 'info');
|
||||||
} else if (message.state === 'sentence_start') {
|
} else if (message.state === 'sentence_start') {
|
||||||
log(`服务器发送语音段: ${message.text}`, 'info');
|
log(`服务器发送语音段${tagName}: ${message.text}`, 'info');
|
||||||
// 添加文本到会话记录
|
// Handle opening text - skip if this is a reconnect
|
||||||
|
if (msgTag === MESSAGE_TAG.OPENING && skipCurrentOpening) {
|
||||||
|
log('跳过重复的开场白文本显示', 'debug');
|
||||||
|
} else {
|
||||||
if (message.text) {
|
if (message.text) {
|
||||||
addMessage(message.text);
|
addMessage(message.text);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} else if (message.state === 'sentence_end') {
|
} else if (message.state === 'sentence_end') {
|
||||||
log(`语音段结束: ${message.text}`, 'info');
|
log(`语音段结束${tagName}: ${message.text}`, 'info');
|
||||||
} else if (message.state === 'stop') {
|
} else if (message.state === 'stop') {
|
||||||
log('服务器语音传输结束', 'info');
|
log('服务器语音传输结束', 'info');
|
||||||
|
// Mark opening as played after TTS completes
|
||||||
|
if (!openingPlayedInSession) {
|
||||||
|
openingPlayedInSession = true;
|
||||||
|
log('开场白播放完成,后续重连将跳过', 'debug');
|
||||||
|
}
|
||||||
|
// Reset skip flag for next session
|
||||||
|
skipCurrentOpening = false;
|
||||||
// 结束后更新UI状态
|
// 结束后更新UI状态
|
||||||
if (recordButton.disabled) {
|
if (recordButton.disabled) {
|
||||||
recordButton.disabled = false;
|
recordButton.disabled = false;
|
||||||
|
|
@ -1760,32 +1780,62 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Message tag constants (sync with server MessageTag enum)
|
||||||
|
const MESSAGE_TAG = {
|
||||||
|
NORMAL: 0,
|
||||||
|
OPENING: 1,
|
||||||
|
CLOSING: 2
|
||||||
|
};
|
||||||
|
|
||||||
|
// Track opening state across reconnections
|
||||||
|
let openingPlayedInSession = false; // Has opening been played in this page session?
|
||||||
|
let skipCurrentOpening = false; // Should we skip the current opening (on reconnect)?
|
||||||
|
|
||||||
async function handleBinaryMessage(data) {
|
async function handleBinaryMessage(data) {
|
||||||
try {
|
try {
|
||||||
let arrayBuffer;
|
let arrayBuffer;
|
||||||
// 根据数据类型进行处理
|
// Convert to ArrayBuffer based on data type
|
||||||
if (data instanceof ArrayBuffer) {
|
if (data instanceof ArrayBuffer) {
|
||||||
arrayBuffer = data;
|
arrayBuffer = data;
|
||||||
log(`收到ArrayBuffer音频数据,大小: ${data.byteLength}字节`, 'debug');
|
|
||||||
} else if (data instanceof Blob) {
|
} else if (data instanceof Blob) {
|
||||||
// 如果是Blob类型,转换为ArrayBuffer
|
|
||||||
arrayBuffer = await data.arrayBuffer();
|
arrayBuffer = await data.arrayBuffer();
|
||||||
log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug');
|
|
||||||
} else {
|
} else {
|
||||||
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
|
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 创建Uint8Array用于处理
|
|
||||||
const opusData = new Uint8Array(arrayBuffer);
|
// Parse 16-byte header + opus payload
|
||||||
if (opusData.length > 0) {
|
// Header structure:
|
||||||
// 将数据添加到缓冲队列
|
// byte 0: type (1 = audio)
|
||||||
queue.enqueue(opusData);
|
// byte 1: message_tag (0=normal, 1=opening, 2=notification)
|
||||||
} else {
|
// bytes 2-15: reserved
|
||||||
|
const HEADER_SIZE = 16;
|
||||||
|
|
||||||
|
if (arrayBuffer.byteLength <= HEADER_SIZE) {
|
||||||
log('收到空音频数据帧,可能是结束标志', 'warning');
|
log('收到空音频数据帧,可能是结束标志', 'warning');
|
||||||
// 如果正在播放,发送结束信号
|
|
||||||
if (isAudioPlaying && streamingContext) {
|
if (isAudioPlaying && streamingContext) {
|
||||||
streamingContext.endOfStream = true;
|
streamingContext.endOfStream = true;
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const headerView = new DataView(arrayBuffer);
|
||||||
|
const type = headerView.getUint8(0);
|
||||||
|
const messageTag = headerView.getUint8(1);
|
||||||
|
|
||||||
|
// Extract opus data (skip 16-byte header)
|
||||||
|
const opusData = new Uint8Array(arrayBuffer, HEADER_SIZE);
|
||||||
|
|
||||||
|
log(`收到音频数据: type=${type}, tag=${messageTag}, payload=${opusData.length}字节`, 'debug');
|
||||||
|
|
||||||
|
// Handle opening message - skip if this is a reconnect
|
||||||
|
if (messageTag === MESSAGE_TAG.OPENING && skipCurrentOpening) {
|
||||||
|
log('跳过重复的开场白音频', 'debug');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (opusData.length > 0) {
|
||||||
|
queue.enqueue(opusData);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(`处理二进制消息出错: ${error.message}`, 'error');
|
log(`处理二进制消息出错: ${error.message}`, 'error');
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue