diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 71098a200..15e57f347 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -82,13 +82,13 @@ class ASRProviderBase(ABC): ) # 确保ASR模块返回原始文本 conn.logger.bind(tag=TAG).info(f"识别文本: {raw_text}") text_len, _ = remove_punctuation_and_length(raw_text) - self.stop_ws_connection() + await self.stop_ws_connection() if text_len > 0: # 使用自定义模块进行上报 await startToChat(conn, raw_text) enqueue_asr_report(conn, raw_text, asr_audio_task) - def stop_ws_connection(self): + async def stop_ws_connection(self): pass def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str: diff --git a/main/xiaozhi-server/core/providers/asr/doubao_stream.py b/main/xiaozhi-server/core/providers/asr/doubao_stream.py index 31704b969..518eaed8c 100644 --- a/main/xiaozhi-server/core/providers/asr/doubao_stream.py +++ b/main/xiaozhi-server/core/providers/asr/doubao_stream.py @@ -209,9 +209,9 @@ class ASRProvider(ASRProviderBase): self.asr_ws = None self.is_processing = False - def stop_ws_connection(self): + async def stop_ws_connection(self): if self.asr_ws: - asyncio.create_task(self.asr_ws.close()) + await self.asr_ws.close() self.asr_ws = None self.is_processing = False diff --git a/main/xiaozhi-server/core/providers/asr/volcengine.py b/main/xiaozhi-server/core/providers/asr/volcengine.py index e76586089..9702176b8 100644 --- a/main/xiaozhi-server/core/providers/asr/volcengine.py +++ b/main/xiaozhi-server/core/providers/asr/volcengine.py @@ -9,6 +9,9 @@ import base64 from core.providers.asr.dto.dto import InterfaceType from core.providers.asr.base import ASRProviderBase +from core.handle.receiveAudioHandle import startToChat +from core.handle.reportHandle import enqueue_asr_report +from core.utils.util import remove_punctuation_and_length from config.logger import setup_logging @@ -39,7 +42,7 @@ class ASRProvider(ASRProviderBase): os.makedirs(self.output_dir, exist_ok=True) # 新增流式处理所需的状态变量 - self.asr_ws: Optional[websockets.WebSocketClientProtocol] = None + self.ws: Optional[websockets.WebSocketClientProtocol] = None self.forward_task: Optional[asyncio.Task] = None self.is_processing: bool = False self.text: str = "" # 用于存储当前识别的文本 @@ -50,11 +53,12 @@ class ASRProvider(ASRProviderBase): async def open_audio_channels(self, conn): await super().open_audio_channels(conn) self.current_session_id = conn.session_id # 保存当前会话 ID + self.conn = conn async def receive_audio(self, conn, audio: bytes, audio_have_voice: bool): if not self.current_session_id: self.current_session_id = conn.session_id - + logger.bind(tag=TAG).info(f"自动生成新的会话ID: {self.current_session_id}") if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime": have_voice = audio_have_voice else: @@ -65,51 +69,38 @@ class ASRProvider(ASRProviderBase): conn.asr_audio = conn.asr_audio[-10:] return - if have_voice and self.asr_ws is None and not self.is_processing: + if have_voice and not self.is_processing: try: self.is_processing = True - logger.bind(tag=TAG).info(f"Connecting to ASR service: {self.ws_url}") - auth_header = {"Authorization": f"Bearer {self.api_key}"} - self.asr_ws = await websockets.connect( - self.ws_url, - additional_headers=auth_header, - close_timeout=10 - ) - - # 启动任务来接收和处理 ASR 结果 - self.forward_task = asyncio.create_task(self._forward_asr_results(conn)) - - # 发送初始化/会话开始请求 - init_request = self._create_stream_start_msg() # 需要实现此方法 - await self.asr_ws.send(json.dumps(init_request)) - logger.bind(tag=TAG).info(f"Sent init request: {init_request}") - - # 发送缓存的音频数据 - if conn.asr_audio and len(conn.asr_audio) > 0: - pcm_frame = self.decode_opus(conn.asr_audio) - await self._send_audio_chunk(b''.join(pcm_frame), False if have_voice else True) - conn.asr_audio.clear() - + logger.bind(tag=TAG).info( f"session: {self.current_session_id} 开启会话") + await self.start_session(self.current_session_id) + pcm_frame = self.decode_opus(conn.asr_audio) + await self._send_audio_chunk(b''.join(pcm_frame)) + conn.asr_audio.clear() except Exception as e: logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {e}", exc_info=True) - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None + if self.ws: + await self.ws.close() + self.ws = None self.is_processing = False return # 发送当前音频数据 - if self.asr_ws and self.is_processing: + if self.ws and self.is_processing: try: - logger.bind(tag=TAG).debug(f"Append audio data") + logger.bind(tag=TAG).debug( f"session: {self.current_session_id} 发送语音数size: {len(audio)}") pcm_frame = self.decode_opus(conn.asr_audio) - await self._send_audio_chunk(b''.join(pcm_frame),False if have_voice else True) + await self._send_audio_chunk(b''.join(pcm_frame)) conn.asr_audio.clear() except Exception as e: logger.bind(tag=TAG).error(f"Error sending audio data: {e}", exc_info=True) + + if not have_voice and self.ws and self.is_processing: + logger.bind(tag=TAG).info( f"session: {self.current_session_id} 结束会话") + await self.finish_session(self.current_session_id) - async def _send_audio_chunk(self, pcm_data: bytes, completed = False): - if not self.asr_ws or not self.is_processing: + async def _send_audio_chunk(self, pcm_data: bytes): + if not self.ws or not self.is_processing: return # 火山引擎流式 ASR 可能需要将 PCM 数据进行 Base64 编码或直接发送二进制 @@ -118,39 +109,20 @@ class ASRProvider(ASRProviderBase): base64_audio = base64.b64encode(pcm_data).decode("utf-8") audio_event = { "audio": base64_audio, + "type": "input_audio_buffer.append" } - audio_event["type"] = "input_audio_buffer.commit" if completed else "input_audio_buffer.append" - await self.asr_ws.send(json.dumps(audio_event)) - logger.bind(tag=TAG).debug(f"Sent audio chunk, size: {len(pcm_data)} , completed: {completed}") + await self.ws.send(json.dumps(audio_event)) + logger.bind(tag=TAG).debug(f"Sent audio chunk, size: {len(pcm_data)} ") - def _create_stream_start_msg(self) -> dict: - """创建流式识别开始的请求消息,具体格式需参考火山引擎文档""" - # 参考之前的 _create_session_msg,但可能需要不同的参数和类型 - config = { - "input_audio_format": "pcm", - "input_audio_codec": "raw", - "input_audio_sample_rate": 16000, - "input_audio_bits": 16, - "input_audio_channel": 1, - "input_audio_transcription": { - "model": self.model_name, - # "stream": True # 标识为流式 - }, - "session_id": self.current_session_id or str(uuid.uuid4()), # 确保有 session_id - } - event = { - "type": "transcription_session.update", # 假设的开始消息类型 - "session": config - } - return event - async def _forward_asr_results(self, conn): + async def _forward_asr_results(self): try: - while self.asr_ws and not conn.stop_event.is_set() and self.is_processing: + logger.bind(tag=TAG).debug(f"session: {self.current_session_id} ASR forward start.") + while self.ws and not self.conn.stop_event.is_set() and self.is_processing: try: - message = await self.asr_ws.recv() + message = await self.ws.recv() event = json.loads(message) - logger.bind(tag=TAG).debug(f"Received ASR result: {event}") + logger.bind(tag=TAG).info(f"session: {self.current_session_id} Received ASR result: {event}") # 解析火山引擎流式 ASR 的响应格式 # 以下为示例,具体字段需要参考文档 @@ -161,16 +133,16 @@ class ASRProvider(ASRProviderBase): self.text += transcript_segment # 累加中间结果 if is_final: logger.bind(tag=TAG).info(f"Final ASR result: {self.text}") - conn.reset_vad_states() # 假设有 VAD 状态重置 - await self.handle_voice_stop(conn, None) # 触发语音结束处理 + self.conn.reset_vad_states() # 假设有 VAD 状态重置 + await self.handle_voice_stop(self.conn, None) # 触发语音结束处理 # self.text = "" # 清空,等待下一次识别 # 注意:这里可能需要更复杂的逻辑来处理会话结束和文本清空 elif message_type == 'conversation.item.input_audio_transcription.completed': # 假设的最终完成类型 final_transcript = event.get("transcript", self.text) logger.bind(tag=TAG).info(f"ASR transcription completed: {final_transcript}") self.text = final_transcript # 确保使用最终结果 - conn.reset_vad_states() - await self.handle_voice_stop(conn, None) + self.conn.reset_vad_states() + await self.handle_voice_stop(self.conn, None) self.text = "" # 清空 # await self.stop_ws_connection() # 收到完成后可以考虑关闭连接 break # 结束接收任务 @@ -180,7 +152,8 @@ class ASRProvider(ASRProviderBase): break except websockets.ConnectionClosed: - logger.bind(tag=TAG).info("ASR WebSocket connection closed.") + await self.stop_ws_connection() + logger.bind(tag=TAG).error("ASR WebSocket connection closed.") break except json.JSONDecodeError: logger.bind(tag=TAG).error(f"Failed to decode JSON from ASR: {message}") @@ -188,42 +161,9 @@ class ASRProvider(ASRProviderBase): logger.bind(tag=TAG).error(f"Error processing ASR result: {e}", exc_info=True) break finally: - logger.bind(tag=TAG).info("ASR forward task finished.") - # 确保在任务结束时,如果连接还存在,则关闭 - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None + logger.bind(tag=TAG).debug(f"session: {self.current_session_id} ASR forward task finished.") self.is_processing = False - # self.text = "" # 确保文本清空 - - def stop_ws_connection(self): - logger.bind(tag=TAG).info("Stopping ASR WebSocket connection...") - if self.asr_ws: - try: - asyncio.create_task(self.asr_ws.close()) - logger.bind(tag=TAG).info("ASR WebSocket connection closed successfully.") - except Exception as e: - logger.bind(tag=TAG).error(f"Error closing ASR WebSocket: {e}") - finally: - self.asr_ws = None - self.audio_buffer.clear() - # self.text = "" # 确保文本清空 - - @staticmethod - def slice_data(data: bytes, chunk_size: int) -> (list, bool): - """ - slice data - :param data: wav data - :param chunk_size: the segment size in one request - :return: segment data, last flag - """ - data_len = len(data) - offset = 0 - while offset + chunk_size < data_len: - yield data[offset : offset + chunk_size], False - offset += chunk_size - else: - yield data[offset:data_len], True + async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" @@ -245,9 +185,8 @@ class ASRProvider(ASRProviderBase): async def close(self): """资源清理方法""" - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None + logger.bind(tag=TAG).info(f"不知道哪里调用的close {session_id}") + await self.stop_ws_connection() if self.forward_task: self.forward_task.cancel() try: @@ -255,4 +194,110 @@ class ASRProvider(ASRProviderBase): except asyncio.CancelledError: pass self.forward_task = None - self.is_processing = False \ No newline at end of file + self.is_processing = False + + async def start_session(self, session_id): + logger.bind(tag=TAG).debug(f"开始会话 {session_id}") + try: + # 建立新连接 + await self._ensure_connection() + # 发送会话启动请求 + """创建流式识别开始的请求消息,具体格式需参考火山引擎文档""" + config = { + "input_audio_format": "pcm", + "input_audio_codec": "raw", + "input_audio_sample_rate": 16000, + "input_audio_bits": 16, + "input_audio_channel": 1, + "input_audio_transcription": { + "model": self.model_name, + }, + "session_id": session_id, # 确保有 session_id + } + event = { + "type": "transcription_session.update", # 假设的开始消息类型 + "session": config + } + await self.ws.send(json.dumps(event)) + logger.bind(tag=TAG).debug(f"会话启动请求已发送, Send Event: {event}") + # 启动监听任务 + if self.forward_task is None: + self.forward_task = asyncio.create_task(self._forward_asr_results()) + except Exception as e: + logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") + # 确保清理资源 + if hasattr(self, "forward_task"): + try: + self.forward_task.cancel() + await self.forward_task + except: + pass + self.forward_task = None + await self.stop_ws_connection() + raise + + async def finish_session(self, session_id): + try: + self.audio_buffer.clear() + #self.is_processing = False + if self.ws: + done_payload = { + "type": "input_audio_buffer.commit" + } + await self.ws.send(json.dumps(done_payload)) + logger.bind(tag=TAG).debug(f"会话结束请求已发送,Send Event: {done_payload}") + + except Exception as e: + await self.stop_ws_connection() + logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}") + + # 等待监听任务完成 + if hasattr(self, "forward_task"): + try: + await self.forward_task + logger.bind(tag=TAG).debug(f"退出monitor task") + except Exception as e: + logger.bind(tag=TAG).error( + f"等待监听任务完成时发生错误: {str(e)}" + ) + finally: + self.forward_task = None + self.current_session_id = None + + # 处理语音停止 + async def handle_voice_stop(self, conn, asr_audio_task): + raw_text, _ = await self.speech_to_text( + asr_audio_task, conn.session_id, conn.audio_format + ) # 确保ASR模块返回原始文本 + conn.logger.bind(tag=TAG).info(f"识别文本: {raw_text}") + text_len, _ = remove_punctuation_and_length(raw_text) + #await self.finish_session(self.current_session_id) + if text_len > 0: + # 使用自定义模块进行上报 + await startToChat(conn, raw_text) + enqueue_asr_report(conn, raw_text, asr_audio_task) + + async def _ensure_connection(self): + # TODO: 建立健康检查机制,实现连接复用 + #await self.stop_ws_connection() + if self.ws is None: + try: + logger.bind(tag=TAG).info(f"Connecting to ASR service:{self.ws_url}") + headers = {"Authorization": f"Bearer {self.api_key}"} + self.ws = await websockets.connect(self.ws_url, additional_headers=headers) + logger.bind(tag=TAG).info("WebSocket connection established.") + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}") + self.ws = None + raise + + async def stop_ws_connection(self): + logger.bind(tag=TAG).info("Stopping ASR WebSocket connection...") + if self.ws: + try: + await self.ws.close() + logger.bind(tag=TAG).info("ASR WebSocket connection closed successfully.") + except Exception as e: + logger.bind(tag=TAG).error(f"Error closing ASR WebSocket: {e}") + finally: + self.ws = None \ No newline at end of file