mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: process remaining report messages after connection closes
This commit is contained in:
parent
f9b4e53230
commit
787bb25472
6 changed files with 92 additions and 50 deletions
|
|
@ -1204,14 +1204,10 @@ class ConnectionHandler:
|
||||||
try:
|
try:
|
||||||
# 从队列获取数据,设置超时以便定期检查停止事件
|
# 从队列获取数据,设置超时以便定期检查停止事件
|
||||||
item = self.report_queue.get(timeout=1)
|
item = self.report_queue.get(timeout=1)
|
||||||
if item is None: # 检测毒丸对象
|
if item is None: # detect poison pill object
|
||||||
|
self.report_queue.task_done()
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
# 检查线程池状态
|
|
||||||
if self.executor is None:
|
|
||||||
continue
|
|
||||||
# 提交任务到线程池
|
|
||||||
# self.executor.submit(self._process_report, *item)
|
|
||||||
self._process_report(*item)
|
self._process_report(*item)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
|
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
|
||||||
|
|
@ -1220,6 +1216,21 @@ class ConnectionHandler:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
|
self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
|
||||||
|
|
||||||
|
# stop_event is set, continue processing remaining messages in report_queue
|
||||||
|
self.logger.bind(tag=TAG).info("processing remaining report messages...")
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
item = self.report_queue.get_nowait()
|
||||||
|
if item is None: # detect poison pill object
|
||||||
|
self.report_queue.task_done()
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
self._process_report(*item)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"processing remaining report messages failed: {e}")
|
||||||
|
except queue.Empty:
|
||||||
|
break
|
||||||
|
|
||||||
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
|
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
|
||||||
|
|
||||||
def _process_report(self, role, text, audio_data, report_time, attachments=None):
|
def _process_report(self, role, text, audio_data, report_time, attachments=None):
|
||||||
|
|
@ -1266,9 +1277,21 @@ class ConnectionHandler:
|
||||||
if self.stop_event:
|
if self.stop_event:
|
||||||
self.stop_event.set()
|
self.stop_event.set()
|
||||||
|
|
||||||
# 清空任务队列
|
# clear TTS text queue and audio queue, except report_queue
|
||||||
self.clear_queues()
|
self.clear_queues()
|
||||||
|
|
||||||
|
# process remaining messages in report_queue
|
||||||
|
if self._report_enabled and self.report_queue:
|
||||||
|
try:
|
||||||
|
self.logger.bind(tag=TAG).info("waiting for report queue to be processed...")
|
||||||
|
# send poison pill object to notify report_worker to exit and process remaining messages
|
||||||
|
self.report_queue.put(None)
|
||||||
|
# wait for all messages to be processed
|
||||||
|
self.report_queue.join()
|
||||||
|
self.logger.bind(tag=TAG).info("report queue processed")
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).warning(f"waiting for report queue timeout or failed: {e}")
|
||||||
|
|
||||||
# 关闭WebSocket连接
|
# 关闭WebSocket连接
|
||||||
try:
|
try:
|
||||||
if ws:
|
if ws:
|
||||||
|
|
@ -1327,17 +1350,16 @@ class ConnectionHandler:
|
||||||
self.stop_event.set()
|
self.stop_event.set()
|
||||||
|
|
||||||
def clear_queues(self):
|
def clear_queues(self):
|
||||||
"""清空所有任务队列"""
|
"""clear TTS task queues (except report_queue, which is handled by close method)"""
|
||||||
if self.tts:
|
if self.tts:
|
||||||
self.logger.bind(tag=TAG).debug(
|
self.logger.bind(tag=TAG).debug(
|
||||||
f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
|
f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 使用非阻塞方式清空队列
|
# use non-blocking way to clear TTS queues
|
||||||
for q in [
|
for q in [
|
||||||
self.tts.tts_text_queue,
|
self.tts.tts_text_queue,
|
||||||
self.tts.tts_audio_queue,
|
self.tts.tts_audio_queue,
|
||||||
self.report_queue,
|
|
||||||
]:
|
]:
|
||||||
if not q:
|
if not q:
|
||||||
continue
|
continue
|
||||||
|
|
|
||||||
|
|
@ -7,46 +7,15 @@ Report features:
|
||||||
See core/connection.py for implementation details.
|
See core/connection.py for implementation details.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import re
|
|
||||||
import time
|
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
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
|
from core.utils.textUtils import strip_emotion_tags
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
# Regex pattern to match emotion tags anywhere in text
|
|
||||||
# Format: (emotion) e.g., "(happy)", "(sincere)", "(curious)"
|
|
||||||
# Matches: optional whitespace + (word) + optional whitespace
|
|
||||||
EMOTION_TAG_PATTERN = re.compile(r'\s*\([a-zA-Z_]+\)\s*')
|
|
||||||
|
|
||||||
|
|
||||||
def strip_emotion_tags(text: str) -> str:
|
|
||||||
"""
|
|
||||||
Remove all emotion tags from TTS text.
|
|
||||||
|
|
||||||
Emotion tags are in format: (emotion) typically at the start of sentences.
|
|
||||||
Examples:
|
|
||||||
"(happy) Hello!" -> "Hello!"
|
|
||||||
"(sincere) That's great. (curious) What next?" -> "That's great. What next?"
|
|
||||||
"Hello (happy) world" -> "Hello world"
|
|
||||||
|
|
||||||
Args:
|
|
||||||
text: Text with potential emotion tags
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Text with all emotion tags removed
|
|
||||||
"""
|
|
||||||
if not text:
|
|
||||||
return text
|
|
||||||
|
|
||||||
# Remove all emotion tags from the text
|
|
||||||
result = EMOTION_TAG_PATTERN.sub(' ', text)
|
|
||||||
# Clean up multiple spaces and trim
|
|
||||||
result = re.sub(r'\s+', ' ', result)
|
|
||||||
return result.strip()
|
|
||||||
|
|
||||||
|
|
||||||
def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_time: int = 0, attachments: List[Dict[str, Any]] | None = None):
|
def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_time: int = 0, attachments: List[Dict[str, Any]] | None = None):
|
||||||
"""Execute chat message report to live-agent-api
|
"""Execute chat message report to live-agent-api
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,8 @@ from core.providers.tts.dto.dto import (
|
||||||
SentenceType,
|
SentenceType,
|
||||||
MessageTag,
|
MessageTag,
|
||||||
)
|
)
|
||||||
|
from core.utils.textUtils import strip_emotion_tags
|
||||||
|
from core.utils.opus import pack_opus_with_header
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -102,11 +103,7 @@ async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
|
||||||
async def _send_audio_with_header(conn, audios, message_tag=MessageTag.NORMAL):
|
async def _send_audio_with_header(conn, audios, message_tag=MessageTag.NORMAL):
|
||||||
if audios is None or len(audios) == 0:
|
if audios is None or len(audios) == 0:
|
||||||
return
|
return
|
||||||
header = bytearray(16)
|
complete_packet = pack_opus_with_header(audios, message_tag)
|
||||||
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)
|
await conn.websocket.send(complete_packet)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -243,7 +240,9 @@ async def send_tts_message(conn, state, text=None, message_tag=MessageTag.NORMAL
|
||||||
"message_tag": message_tag.value,
|
"message_tag": message_tag.value,
|
||||||
}
|
}
|
||||||
if text is not None:
|
if text is not None:
|
||||||
message["text"] = textUtils.check_emoji(text)
|
text = textUtils.check_emoji(text)
|
||||||
|
text = strip_emotion_tags(text)
|
||||||
|
message["text"] = text
|
||||||
|
|
||||||
# TTS播放结束
|
# TTS播放结束
|
||||||
if state == "stop":
|
if state == "stop":
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ from abc import ABC, abstractmethod
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.utils.tts import MarkdownCleaner
|
from core.utils.tts import MarkdownCleaner
|
||||||
from core.utils.output_counter import add_device_output
|
from core.utils.output_counter import add_device_output
|
||||||
|
from core.utils.opus import pack_opus_with_header
|
||||||
from core.handle.reportHandle import enqueue_tts_report
|
from core.handle.reportHandle import enqueue_tts_report
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage
|
from core.handle.sendAudioHandle import sendAudioMessage
|
||||||
from core.utils.util import audio_bytes_to_data_stream, audio_to_data_stream
|
from core.utils.util import audio_bytes_to_data_stream, audio_to_data_stream
|
||||||
|
|
@ -378,6 +379,7 @@ class TTSProviderBase(ABC):
|
||||||
|
|
||||||
# 收集上报音频数据
|
# 收集上报音频数据
|
||||||
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
|
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
|
||||||
|
audio_datas = pack_opus_with_header(audio_datas, message_tag)
|
||||||
enqueue_audio.append(audio_datas)
|
enqueue_audio.append(audio_datas)
|
||||||
|
|
||||||
# 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞
|
# 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞
|
||||||
|
|
@ -400,6 +402,14 @@ class TTSProviderBase(ABC):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"audio_play_priority_thread: {text} {e}")
|
logger.bind(tag=TAG).error(f"audio_play_priority_thread: {text} {e}")
|
||||||
|
|
||||||
|
# when connection session is closing, report the remaining TTS data(latest message)
|
||||||
|
if enqueue_text is not None and enqueue_audio is not None and len(enqueue_audio) > 0:
|
||||||
|
try:
|
||||||
|
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag)
|
||||||
|
logger.bind(tag=TAG).info(f"connection closing, report the remaining TTS data: {enqueue_text}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"connection closing, report the remaining TTS data failed: {e}")
|
||||||
|
|
||||||
async def start_session(self, session_id):
|
async def start_session(self, session_id):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
|
||||||
10
main/xiaozhi-server/core/utils/opus.py
Normal file
10
main/xiaozhi-server/core/utils/opus.py
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
|
|
||||||
|
def pack_opus_with_header(opus_data: bytes, message_tag: MessageTag = MessageTag.NORMAL) -> bytes:
|
||||||
|
header = bytearray(16)
|
||||||
|
header[0] = 1 # default value is 1 for audio message
|
||||||
|
header[1] = message_tag.value
|
||||||
|
header[2:6] = len(opus_data).to_bytes(4, "big")
|
||||||
|
# 3-15 bytes is reserved for future use, currently not used
|
||||||
|
complete_packet = bytes(header) + opus_data
|
||||||
|
return complete_packet
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
from urllib3 import Retry
|
from urllib3 import Retry
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
EMOJI_MAP = {
|
EMOJI_MAP = {
|
||||||
"😂": "laughing",
|
"😂": "laughing",
|
||||||
|
|
@ -115,3 +116,34 @@ def is_emoji(char):
|
||||||
def check_emoji(text):
|
def check_emoji(text):
|
||||||
"""去除文本中的所有emoji表情"""
|
"""去除文本中的所有emoji表情"""
|
||||||
return ''.join(char for char in text if not is_emoji(char) and char != "\n")
|
return ''.join(char for char in text if not is_emoji(char) and char != "\n")
|
||||||
|
|
||||||
|
# Regex pattern to match emotion tags anywhere in text
|
||||||
|
# Format: (emotion) e.g., "(happy)", "(sincere)", "(curious)"
|
||||||
|
# Matches: optional whitespace + (word) + optional whitespace
|
||||||
|
EMOTION_TAG_PATTERN = re.compile(r'\s*\([a-zA-Z_]+\)\s*')
|
||||||
|
|
||||||
|
|
||||||
|
def strip_emotion_tags(text: str) -> str:
|
||||||
|
"""
|
||||||
|
Remove all emotion tags from TTS text.
|
||||||
|
|
||||||
|
Emotion tags are in format: (emotion) typically at the start of sentences.
|
||||||
|
Examples:
|
||||||
|
"(happy) Hello!" -> "Hello!"
|
||||||
|
"(sincere) That's great. (curious) What next?" -> "That's great. What next?"
|
||||||
|
"Hello (happy) world" -> "Hello world"
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Text with potential emotion tags
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Text with all emotion tags removed
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return text
|
||||||
|
|
||||||
|
# Remove all emotion tags from the text
|
||||||
|
result = EMOTION_TAG_PATTERN.sub(' ', text)
|
||||||
|
# Clean up multiple spaces and trim
|
||||||
|
result = re.sub(r'\s+', ' ', result)
|
||||||
|
return result.strip()
|
||||||
Loading…
Reference in a new issue