From 2e03398908f130fadbda3bb6b0b6233a7f410a6c Mon Sep 17 00:00:00 2001 From: seven Date: Tue, 25 Mar 2025 17:32:27 +0800 Subject: [PATCH] add --- main/xiaozhi-server/core/connection.py | 91 +++++++++++++++++++ .../core/handle/sendAudioHandle.py | 61 +++++++++---- .../core/providers/tts/linkerai.py | 63 +++++++++++++ 3 files changed, 196 insertions(+), 19 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/tts/linkerai.py diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index c9a52b120..a3af6df8c 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -309,6 +309,85 @@ class ConnectionHandler: self.dialogue.put(Message(role="assistant", content="".join(response_message))) self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)) return True + + + def chat_stream(self, query): + if self.isNeedAuth(): + self.llm_finish_task = True + future = asyncio.run_coroutine_threadsafe(self._check_and_broadcast_auth_code(), self.loop) + future.result() + return True + + self.dialogue.put(Message(role="user", content=query)) + + response_message = [] + processed_chars = 0 # 跟踪已处理的字符位置 + try: + start_time = time.time() + # 使用带记忆的对话 + future = asyncio.run_coroutine_threadsafe(self.memory.query_memory(query), self.loop) + memory_str = future.result() + + self.logger.bind(tag=TAG).debug(f"记忆内容: {memory_str}") + llm_responses = self.llm.response( + self.session_id, + self.dialogue.get_llm_dialogue_with_memory(memory_str) + ) + except Exception as e: + self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") + return None + + self.llm_finish_task = False + text_index = 0 + for content in llm_responses: + response_message.append(content) + if self.client_abort: + break + + end_time = time.time() + self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}") + + # 合并当前全部文本并处理未分割部分 + full_text = "".join(response_message) + current_text = full_text[processed_chars:] # 从未处理的位置开始 + + # 查找最后一个有效标点 + punctuations = ("。", "?", "!", ";", ":") + last_punct_pos = -1 + for punct in punctuations: + pos = current_text.rfind(punct) + if pos > last_punct_pos: + last_punct_pos = pos + + # 找到分割点则处理 + if last_punct_pos != -1: + segment_text_raw = current_text[:last_punct_pos + 1] + segment_text = get_string_no_punctuation_or_emoji(segment_text_raw) + if segment_text: + # 强制设置空字符,测试TTS出错返回语音的健壮性 + # if text_index % 2 == 0: + # segment_text = " " + text_index += 1 + self.recode_first_last_text(segment_text, text_index) + future = self.executor.submit(self.speak_and_play, segment_text, text_index) + self.tts_queue.put(future) + processed_chars += len(segment_text_raw) # 更新已处理字符位置 + + # 处理最后剩余的文本 + full_text = "".join(response_message) + remaining_text = full_text[processed_chars:] + if remaining_text: + segment_text = get_string_no_punctuation_or_emoji(remaining_text) + if segment_text: + text_index += 1 + self.recode_first_last_text(segment_text, text_index) + future = self.executor.submit(self.speak_and_play, segment_text, text_index) + self.tts_queue.put(future) + + self.llm_finish_task = True + self.dialogue.put(Message(role="assistant", content="".join(response_message))) + self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)) + return True def chat_with_function_calling(self, query, tool_call=False): self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}") @@ -597,3 +676,15 @@ class ConnectionHandler: self.close_after_chat = True except Exception as e: self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") + + + def chat_and_close_stream(self, text): + """Chat with the user and then close the connection""" + try: + # Use the existing chat method + self.chat_stream(text) + + # After chat is complete, close the connection + self.close_after_chat = True + except Exception as e: + self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index c0a664eb6..d667ce4eb 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -3,6 +3,7 @@ import json import asyncio import time from core.utils.util import remove_punctuation_and_length, get_string_no_punctuation_or_emoji +import types TAG = __name__ logger = setup_logging() @@ -31,29 +32,51 @@ async def sendAudio(conn, audios): frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码 start_time = time.perf_counter() play_position = 0 + + if isinstance(audios,types.GeneratorType): + count = 0 + for opus_packet in audios: + if count < 3: + await conn.websocket.send(opus_packet) + conn.logger.bind(tag=TAG).debug(f"预缓冲帧 {i}, 时间: {(time.perf_counter() - start_time) * 1000:.2f}ms") + else: + if conn.client_abort: + return + expected_time = start_time + (play_position / 1000) + current_time = time.perf_counter() + delay = expected_time - current_time + if delay > 0: + await asyncio.sleep(delay) + await conn.websocket.send(opus_packet) + conn.logger.bind(tag=TAG).debug(f"发送帧,位置: {play_position}ms, 实际间隔: {(time.perf_counter() - current_time) * 1000:.2f}ms") + play_position += frame_duration - # 预缓冲:发送前 3 帧 - pre_buffer = min(3, len(audios)) - for i in range(pre_buffer): - await conn.websocket.send(audios[i]) - conn.logger.bind(tag=TAG).debug(f"预缓冲帧 {i}, 时间: {(time.perf_counter() - start_time) * 1000:.2f}ms") + count += 1 - # 正常播放剩余帧 - for opus_packet in audios[pre_buffer:]: - if conn.client_abort: - return - - # 计算预期发送时间 - expected_time = start_time + (play_position / 1000) - current_time = time.perf_counter() - delay = expected_time - current_time - if delay > 0: - await asyncio.sleep(delay) + else: - await conn.websocket.send(opus_packet) - conn.logger.bind(tag=TAG).debug(f"发送帧,位置: {play_position}ms, 实际间隔: {(time.perf_counter() - current_time) * 1000:.2f}ms") + # 预缓冲:发送前 3 帧 + pre_buffer = min(3, len(audios)) + for i in range(pre_buffer): + await conn.websocket.send(audios[i]) + conn.logger.bind(tag=TAG).debug(f"预缓冲帧 {i}, 时间: {(time.perf_counter() - start_time) * 1000:.2f}ms") - play_position += frame_duration + # 正常播放剩余帧 + for opus_packet in audios[pre_buffer:]: + if conn.client_abort: + return + + # 计算预期发送时间 + expected_time = start_time + (play_position / 1000) + current_time = time.perf_counter() + delay = expected_time - current_time + if delay > 0: + await asyncio.sleep(delay) + + await conn.websocket.send(opus_packet) + conn.logger.bind(tag=TAG).debug(f"发送帧,位置: {play_position}ms, 实际间隔: {(time.perf_counter() - current_time) * 1000:.2f}ms") + + play_position += frame_duration diff --git a/main/xiaozhi-server/core/providers/tts/linkerai.py b/main/xiaozhi-server/core/providers/tts/linkerai.py new file mode 100644 index 000000000..be2e502f9 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/linkerai.py @@ -0,0 +1,63 @@ +import os +import uuid +import requests +from datetime import datetime +from core.providers.tts.base import TTSProviderBase +import json + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.model = config.get("model") + self.access_token = config.get("access_token") + self.voice = config.get("voice") + self.response_format = config.get("response_format") + self.sample_rate = config.get("sample_rate") + self.speed = config.get("speed") + self.gain = config.get("gain") + + self.host = "tts.linkerai.top" + self.api_url = f"https://{self.host}/tts" + + def generate_filename(self, extension=".wav"): + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") + + async def text_to_speak(self, text, output_file): + params = { + "tts_text": text, + "spk_id": self.voice, + "frame_durition": 60, + "stream": True, + "target_sr": self.sample_rate, + "audio_format":"opus", + "instruct_text":"" + } + headers = { + "Authorization": f"Bearer {self.access_token}", + "Content-Type": "application/json" + } + with open(output_file,'w') as f: + f.write('%s\n'%(json.dumps(params))) + f.write('%s'%(json.dumps(headers))) + + def yield_data(self,params,headers): + response = requests.get(self.api_url, headers=headers, params=params, stream=True) + if response.status_code == 200: + + for chunk in response.iter_content(chunk_size=None): + if chunk: + yield chunk + else: + print(f"请求失败,状态码: {response.status_code}") + print(f"错误信息: {response.text}") + + def audio_to_opus_data(self, audio_file_path): + duration = 100 + code = [] + with open(audio_file_path,encoding='utf-8') as f: + for line in f.readlines(): + code.append(json.dumps(line)) + params = code[0] + headers = code[1] + + return self.yield_data(params=params,headers=headers),duration