diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index a80b55a29..4cc20a933 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1204,14 +1204,10 @@ class ConnectionHandler: try: # 从队列获取数据,设置超时以便定期检查停止事件 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 try: - # 检查线程池状态 - if self.executor is None: - continue - # 提交任务到线程池 - # self.executor.submit(self._process_report, *item) self._process_report(*item) except Exception as e: self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}") @@ -1220,6 +1216,21 @@ class ConnectionHandler: except Exception as 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("聊天记录上报线程已退出") def _process_report(self, role, text, audio_data, report_time, attachments=None): @@ -1266,9 +1277,21 @@ class ConnectionHandler: if self.stop_event: self.stop_event.set() - # 清空任务队列 + # clear TTS text queue and audio queue, except report_queue 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连接 try: if ws: @@ -1327,17 +1350,16 @@ class ConnectionHandler: self.stop_event.set() def clear_queues(self): - """清空所有任务队列""" + """clear TTS task queues (except report_queue, which is handled by close method)""" if self.tts: self.logger.bind(tag=TAG).debug( 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 [ self.tts.tts_text_queue, self.tts.tts_audio_queue, - self.report_queue, ]: if not q: continue diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py index 10f894b5c..e41aeab5a 100644 --- a/main/xiaozhi-server/core/handle/reportHandle.py +++ b/main/xiaozhi-server/core/handle/reportHandle.py @@ -7,46 +7,15 @@ Report features: See core/connection.py for implementation details. """ -import re import time import base64 from typing import List, Dict, Any from config.live_agent_api_client import report_chat_message from core.providers.tts.dto.dto import MessageTag +from core.utils.textUtils import strip_emotion_tags 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): """Execute chat message report to live-agent-api diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index 39883e5e2..f46fdc294 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -7,7 +7,8 @@ from core.providers.tts.dto.dto import ( SentenceType, MessageTag, ) - +from core.utils.textUtils import strip_emotion_tags +from core.utils.opus import pack_opus_with_header 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): 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 + complete_packet = pack_opus_with_header(audios, message_tag) 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, } 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播放结束 if state == "stop": diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index c4bc750d6..443c861e9 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -16,6 +16,7 @@ from abc import ABC, abstractmethod from config.logger import setup_logging from core.utils.tts import MarkdownCleaner 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.sendAudioHandle import sendAudioMessage 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: + audio_datas = pack_opus_with_header(audio_datas, message_tag) enqueue_audio.append(audio_datas) # 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞 @@ -400,6 +402,14 @@ class TTSProviderBase(ABC): except Exception as 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): pass diff --git a/main/xiaozhi-server/core/utils/opus.py b/main/xiaozhi-server/core/utils/opus.py new file mode 100644 index 000000000..090f3e4dd --- /dev/null +++ b/main/xiaozhi-server/core/utils/opus.py @@ -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 \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/textUtils.py b/main/xiaozhi-server/core/utils/textUtils.py index d3689d346..812ef6bf3 100644 --- a/main/xiaozhi-server/core/utils/textUtils.py +++ b/main/xiaozhi-server/core/utils/textUtils.py @@ -1,7 +1,8 @@ import json - +import re from urllib3 import Retry + TAG = __name__ EMOJI_MAP = { "😂": "laughing", @@ -115,3 +116,34 @@ def is_emoji(char): def check_emoji(text): """去除文本中的所有emoji表情""" 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() \ No newline at end of file