Files
xiaozhi-esp32-server/main/xiaozhi-server/core/handle/textHandle.py
T

65 lines
2.8 KiB
Python
Raw Normal View History

2025-02-18 00:07:19 +08:00
from config.logger import setup_logging
2025-02-04 13:57:05 +08:00
import json
from core.handle.abortHandle import handleAbortMessage
from core.handle.helloHandle import handleHelloMessage
2025-03-23 17:47:39 +08:00
from core.utils.util import remove_punctuation_and_length
2025-03-18 13:25:34 +08:00
from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
2025-03-09 01:02:37 +08:00
from core.handle.iotHandle import handleIotDescriptors, handleIotStatus
2025-02-02 23:01:14 +08:00
2025-02-18 00:07:19 +08:00
TAG = __name__
logger = setup_logging()
2025-02-02 23:01:14 +08:00
async def handleTextMessage(conn, message):
2025-02-04 13:57:05 +08:00
"""处理文本消息"""
2025-02-18 00:07:19 +08:00
logger.bind(tag=TAG).info(f"收到文本消息:{message}")
2025-02-04 13:57:05 +08:00
try:
msg_json = json.loads(message)
2025-02-09 16:44:57 +08:00
if isinstance(msg_json, int):
await conn.websocket.send(message)
return
2025-02-04 13:57:05 +08:00
if msg_json["type"] == "hello":
2025-02-06 12:30:26 +08:00
await handleHelloMessage(conn)
2025-02-04 13:57:05 +08:00
elif msg_json["type"] == "abort":
await handleAbortMessage(conn)
elif msg_json["type"] == "listen":
if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"]
2025-03-18 18:42:17 +08:00
logger.bind(tag=TAG).debug(f"客户端拾音模式:{conn.client_listen_mode}")
2025-02-04 13:57:05 +08:00
if msg_json["state"] == "start":
conn.client_have_voice = True
conn.client_voice_stop = False
elif msg_json["state"] == "stop":
conn.client_have_voice = True
conn.client_voice_stop = True
2025-03-18 13:25:34 +08:00
if len(conn.asr_audio) > 0:
await handleAudioMessage(conn, b'')
2025-02-04 13:57:05 +08:00
elif msg_json["state"] == "detect":
conn.asr_server_receive = False
conn.client_have_voice = False
conn.asr_audio.clear()
if "text" in msg_json:
2025-03-23 17:47:39 +08:00
text = msg_json["text"]
_, text = remove_punctuation_and_length(text)
# 识别是否是唤醒词
is_wakeup_words = text in conn.config.get("wakeup_words")
# 是否开启唤醒词回复
enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting:
# 如果是唤醒词,且关闭了唤醒词回复,就不用回答
await send_stt_message(conn, text)
await send_tts_message(conn, "stop", None)
2025-03-23 17:47:39 +08:00
else:
# 否则需要LLM对文字内容进行答复
await startToChat(conn, text)
2025-02-24 18:06:13 +08:00
elif msg_json["type"] == "iot":
if "descriptors" in msg_json:
2025-02-26 01:33:05 +08:00
await handleIotDescriptors(conn, msg_json["descriptors"])
2025-03-09 01:02:37 +08:00
if "states" in msg_json:
2025-03-18 18:42:17 +08:00
await handleIotStatus(conn, msg_json["states"])
2025-02-04 13:57:05 +08:00
except json.JSONDecodeError:
2025-02-09 16:44:57 +08:00
await conn.websocket.send(message)