feat: 代码注释

This commit is contained in:
martsforever
2025-11-03 11:24:06 +08:00
parent fae4f7f24e
commit 97c31cc135
@@ -20,24 +20,31 @@ def add_websocket_voice_recognise_route(app: FastAPI):
# 接收连接 # 接收连接
await receive_socket.accept() await receive_socket.accept()
# 公共函数,用于向前端发送语音识别结果
async def send_text(data: dict): async def send_text(data: dict):
await receive_socket.send_text(json.dumps(data, ensure_ascii=False)) await receive_socket.send_text(json.dumps(data, ensure_ascii=False))
# 百炼识别返回的开始说话事件
async def on_speech_started(item_id: str): async def on_speech_started(item_id: str):
await send_text({"type": "speech_started", "item_id": item_id}) await send_text({"type": "speech_started", "item_id": item_id})
# 百炼识别返回的正在说话事件
async def on_speech_content(item_id: str, content: str): async def on_speech_content(item_id: str, content: str):
await send_text({"type": "speech_content", "item_id": item_id, "content": content}) await send_text({"type": "speech_content", "item_id": item_id, "content": content})
# 百炼识别返回的说话结束事件
async def on_speech_stopped(item_id: str): async def on_speech_stopped(item_id: str):
await send_text({"type": "speech_stopped", "item_id": item_id}) await send_text({"type": "speech_stopped", "item_id": item_id})
# 百炼识别返回的识别完成事件
async def on_speech_completed(item_id: str, content: str): async def on_speech_completed(item_id: str, content: str):
await send_text({"type": "speech_completed", "item_id": item_id, "content": content}) await send_text({"type": "speech_completed", "item_id": item_id, "content": content})
# 百炼识别连接错误
async def on_connect_error(error: Exception): async def on_connect_error(error: Exception):
await clear_socket() await clear_socket()
# 创建一个百炼语音识别对象
bvrs = BaiLianVoiceRecogniseSocket( bvrs = BaiLianVoiceRecogniseSocket(
on_speech_started=on_speech_started, on_speech_started=on_speech_started,
on_speech_content=on_speech_content, on_speech_content=on_speech_content,
@@ -46,6 +53,7 @@ def add_websocket_voice_recognise_route(app: FastAPI):
on_connect_error=on_connect_error, on_connect_error=on_connect_error,
) )
# 连接百炼websocket
await bvrs.connect() await bvrs.connect()
async def clear_socket(): async def clear_socket():
@@ -89,7 +97,9 @@ def add_websocket_voice_recognise_route(app: FastAPI):
# 并发运行两个任务 # 并发运行两个任务
await asyncio.gather( await asyncio.gather(
# 等待前端的websocket消息,将前端传递的音频数据转发给百炼识别
waiting_msg_from_front(), waiting_msg_from_front(),
# 等待百炼的websocket消息,将识别结果转发给前端
bvrs.waiting_message_from_socket(), bvrs.waiting_message_from_socket(),
return_exceptions=True return_exceptions=True
) )