From 63d597250f5cf76ab1c415766548f1b6b21274ba Mon Sep 17 00:00:00 2001 From: hrz <1710360675@qq.com> Date: Fri, 21 Feb 2025 10:19:50 +0800 Subject: [PATCH] =?UTF-8?q?update:=E5=8F=AA=E7=95=99=E4=B8=8B=E8=B1=86?= =?UTF-8?q?=E5=8C=85=E5=9C=A8=E7=BA=BF=20ASR=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 - Dockerfile-pip | 8 +- README_en.md | 2 +- ZhiKongTaiWeb/package.json | 2 +- config.yaml | 29 -- config/private_config.py | 8 +- core/connection.py | 34 +-- core/handle/audioHandle.py | 20 +- core/providers/asr/base.py | 26 -- core/providers/asr/doubao.py | 285 ------------------ core/providers/asr/fun_local.py | 110 ------- core/utils/asr.py | 138 ++++++++- core/utils/dialogue.py | 12 - core/utils/embedding.py | 49 ---- core/utils/llm_memory.py | 492 -------------------------------- core/utils/util.py | 4 +- core/websocket_server.py | 15 +- docker-compose.yml | 2 +- docs/Deployment-silm.md | 6 - docs/Embe.md | 13 - poetry.lock | 2 +- pyproject.toml | 2 +- requirements.txt | 3 +- 23 files changed, 149 insertions(+), 1115 deletions(-) delete mode 100644 core/providers/asr/base.py delete mode 100644 core/providers/asr/doubao.py delete mode 100644 core/providers/asr/fun_local.py delete mode 100644 core/utils/embedding.py delete mode 100644 core/utils/llm_memory.py delete mode 100644 docs/Embe.md diff --git a/.gitignore b/.gitignore index 161f209ee..8be615c08 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ # Byte-compiled / optimized / DLL files __pycache__/ -.idea/ *.py[cod] *$py.class @@ -146,4 +145,3 @@ tmp .private_config.yaml .env.development docker-compose.yml -models/jina-embeddings-v2-base-zh/onnx/model.onnx diff --git a/Dockerfile-pip b/Dockerfile-pip index 4eabb69f1..00ad57f04 100755 --- a/Dockerfile-pip +++ b/Dockerfile-pip @@ -24,13 +24,7 @@ WORKDIR /app COPY requirements.txt . # 优化apt安装 -RUN echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list && \ - echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \ - apt-get update && \ - apt-get install -y --no-install-recommends gcc libopus-dev ffmpeg && \ - rm -rf /var/lib/apt/lists/* && \ - # 直接使用系统Python - pip install --no-cache-dir -r requirements.txt \ +RUN pip install --no-cache-dir -r requirements.txt \ -i https://pypi.tuna.tsinghua.edu.cn/simple # 第三阶段:生产镜像 diff --git a/README_en.md b/README_en.md index 8b5c680ee..7f1e2ff68 100644 --- a/README_en.md +++ b/README_en.md @@ -12,7 +12,7 @@ the[Xiaozhi Communication Protocol](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO This project requires compatible esp32 hardware devices. If you have purchased esp32 hardware, successfully connected to Xiage's deployed backend, and wish to independently set up the `xiaozhi-esp32` backend service, this project is for -you。 +you. To see a demo, watch this video: diff --git a/ZhiKongTaiWeb/package.json b/ZhiKongTaiWeb/package.json index 9c3998ba6..7f488208f 100644 --- a/ZhiKongTaiWeb/package.json +++ b/ZhiKongTaiWeb/package.json @@ -21,4 +21,4 @@ "concurrently": "^9.1.2", "vite": "^5.4.8" } -} \ No newline at end of file +} diff --git a/config.yaml b/config.yaml index 6bdb74d94..a0ce2e1b4 100644 --- a/config.yaml +++ b/config.yaml @@ -38,20 +38,6 @@ xiaozhi: sample_rate: 16000 channels: 1 frame_duration: 60 - -# 长期记忆参数 -memory: - # 记忆摘要提示 - summary_prompt: "你还保留着一些长期的记忆,这有助于让你的对话更加丰富和连贯:" - # 记忆最大长度 - max_memory_length: 10000 - # 摘要最大长度 - max_summary_length: 2000 - # 单次摘要长度 - summary_length: 1000 - # 记忆文件夹 - memory_dir: "memory_data" - prompt: | 你是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。 请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。 @@ -79,19 +65,11 @@ selected_module: LLM: ChatGLMLLM # TTS将根据配置名称对应的type调用实际的TTS适配器 TTS: EdgeTTS - EMBD: SentenceTransformer ASR: FunASR: - type: fun_local model_dir: models/SenseVoiceSmall output_dir: tmp/ - DoubaoASR: - type: doubao - appid: 你的火山引擎语音合成服务appid - access_token: 你的火山引擎语音合成服务access_token - cluster: volcengine_input_common - output_dir: tmp/ VAD: SileroVAD: @@ -99,13 +77,6 @@ VAD: model_dir: models/snakers4_silero-vad min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些 -EMBD: - SentenceTransformer: - # 下载 https://huggingface.co/jinaai/jina-embeddings-v2-base-zh/blob/main/onnx/model.onnx 到 models/jina-embeddings-v2-base-zh/onnx/model.onnx - model_dir: models/jina-embeddings-v2-base-zh - # cpu cuda:0 推荐cpu节省显存 - device: "cpu" - LLM: # 当前支持的type为openai、dify、ollama,可自行适配 AliLLM: diff --git a/config/private_config.py b/config/private_config.py index 1fcad84a8..b1596b8f5 100644 --- a/config/private_config.py +++ b/config/private_config.py @@ -5,7 +5,7 @@ from config.logger import setup_logging from typing import Dict, Any, Optional from copy import deepcopy from core.utils.util import get_project_dir -from core.utils import asr, vad, llm, tts, embedding +from core.utils import asr, vad, llm, tts from manager.api.user_manager import UserManager from core.utils.lock_manager import FileLockManager @@ -192,10 +192,6 @@ class PrivateConfig: config["TTS"][selected_modules["TTS"]]["type"], config["TTS"][selected_modules["TTS"]], self.default_config.get("delete_audio", True) # Using default_config for global settings - ), - embedding.create_instance( - selected_modules["EMBD"], - config["EMBD"][selected_modules["EMBD"]] ) ) @@ -332,4 +328,4 @@ class PrivateConfig: def get_owner(self) -> Optional[str]: """获取设备当前所有者""" - return self.private_config.get('owner') + return self.private_config.get('owner') \ No newline at end of file diff --git a/core/connection.py b/core/connection.py index 5b8ea71c1..83251eebb 100644 --- a/core/connection.py +++ b/core/connection.py @@ -17,13 +17,12 @@ from concurrent.futures import ThreadPoolExecutor, TimeoutError from core.handle.audioHandle import handleAudioMessage, sendAudioMessage from config.private_config import PrivateConfig from core.auth import AuthMiddleware, AuthenticationError -from core.utils.llm_memory import MemoryManager from core.utils.auth_code_gen import AuthCodeGenerator # 添加导入 TAG = __name__ class ConnectionHandler: - def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _embd): + def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts): self.config = config self.logger = setup_logging() self.auth = AuthMiddleware(config) @@ -50,7 +49,6 @@ class ConnectionHandler: self.asr = _asr self.llm = _llm self.tts = _tts - self.embd = _embd self.dialogue = None # vad相关变量 @@ -85,17 +83,6 @@ class ConnectionHandler: self.is_device_verified = False # 添加设备验证状态标志 - self.llm_memory = MemoryManager( - llm=_llm, - embd=_embd, - summary_prompt=config.get("memory", {}).get("summary_prompt", "你还保留着一些长期的记忆,这有助于让你的对话更加丰富和连贯:"), - max_memory_length=config.get("memory", {}).get("max_memory_length", 10000), - max_summary_length=config.get("memory", {}).get("max_summary_length", 2000), - summary_length=config.get("memory", {}).get("summary_length", 1000), - memory_dir=config.get("memory", {}).get("memory_dir", "memory_data"), - ) - - async def handle_connection(self, ws): try: # 获取并验证headers @@ -106,13 +93,11 @@ class ConnectionHandler: await self.auth.authenticate(self.headers) device_id = self.headers.get("device-id", None) - self.device_id = device_id # Load private configuration if device_id is provided bUsePrivateConfig = self.config.get("use_private_config", False) self.logger.bind(tag=TAG).info(f"bUsePrivateConfig: {bUsePrivateConfig}, device_id: {device_id}") if bUsePrivateConfig and device_id: - try: self.private_config = PrivateConfig(device_id, self.config, self.auth_code_gen) await self.private_config.load_or_create() @@ -127,9 +112,7 @@ class ConnectionHandler: if all([llm, tts]): self.llm = llm self.tts = tts - self.embd = embd self.logger.bind(tag=TAG).info(f"Loaded private config and instances for device {device_id}") - else: self.logger.bind(tag=TAG).error(f"Failed to create instances for device {device_id}") self.private_config = None @@ -156,7 +139,6 @@ class ConnectionHandler: await self._route_message(message) except websockets.exceptions.ConnectionClosed: self.logger.bind(tag=TAG).info("客户端断开连接") - await self.llm_memory.add_chat_paragraph(device_id,self.dialogue.get_llm_dialogue()[1:]) await self.close() except AuthenticationError as e: @@ -165,8 +147,6 @@ class ConnectionHandler: return except Exception as e: self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}") - await self.llm_memory.add_chat_paragraph(device_id,self.dialogue.get_llm_dialogue()[1:]) - await ws.close() return @@ -200,7 +180,6 @@ class ConnectionHandler: return False return True - def isNeedAuth(self): bUsePrivateConfig = self.config.get("use_private_config", False) if not bUsePrivateConfig: @@ -219,20 +198,15 @@ class ConnectionHandler: loop.run_until_complete(self._check_and_broadcast_auth_code()) finally: loop.close() - return True - - query = self.llm_memory.handle_user_scene(self.device_id, query) + return True + self.dialogue.put(Message(role="user", content=query)) response_message = [] start = 0 # 提交 LLM 任务 try: start_time = time.time() # 记录开始时间 - memory_summary = self.llm_memory.get_memory_summary(self.device_id) - llm_responses = self.llm.response( - self.session_id, - self.dialogue.get_llm_dialogue_with_memory(memory_summary) - ) + llm_responses = self.llm.response(self.session_id, self.dialogue.get_llm_dialogue()) except Exception as e: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") return None diff --git a/core/handle/audioHandle.py b/core/handle/audioHandle.py index ac32fff04..394e7fe5d 100644 --- a/core/handle/audioHandle.py +++ b/core/handle/audioHandle.py @@ -28,19 +28,15 @@ async def handleAudioMessage(conn, audio): if conn.client_voice_stop: conn.client_abort = False conn.asr_server_receive = False - # 音频太短了,无法识别 - if len(conn.asr_audio) < 3: - conn.asr_server_receive = True + text, file_path = conn.asr.speech_to_text(conn.asr_audio, conn.session_id) + logger.bind(tag=TAG).info(f"识别文本: {text}") + text_len, text_without_punctuation = remove_punctuation_and_length(text) + if text_len <= conn.max_cmd_length and await handleCMDMessage(conn, text_without_punctuation): + return + if text_len > 0: + await startToChat(conn, text) else: - text, file_path = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id) - logger.bind(tag=TAG).info(f"识别文本: {text}") - text_len, text_without_punctuation = remove_punctuation_and_length(text) - if text_len <= conn.max_cmd_length and await handleCMDMessage(conn, text_without_punctuation): - return - if text_len > 0: - await startToChat(conn, text) - else: - conn.asr_server_receive = True + conn.asr_server_receive = True conn.asr_audio.clear() conn.reset_vad_states() diff --git a/core/providers/asr/base.py b/core/providers/asr/base.py deleted file mode 100644 index c18027ad5..000000000 --- a/core/providers/asr/base.py +++ /dev/null @@ -1,26 +0,0 @@ -import time -import wave -import os -from abc import ABC, abstractmethod -import logging -from typing import Optional, Tuple, List -import uuid - -import opuslib - -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - - -class ASRProviderBase(ABC): - @abstractmethod - def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str: - """解码Opus数据并保存为WAV文件""" - pass - - @abstractmethod - async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - pass diff --git a/core/providers/asr/doubao.py b/core/providers/asr/doubao.py deleted file mode 100644 index 491cdf0e3..000000000 --- a/core/providers/asr/doubao.py +++ /dev/null @@ -1,285 +0,0 @@ -import time -import io -import wave -import os -import logging -from typing import Optional, Tuple, List -import uuid -import websockets -import json -import gzip - -import opuslib -from core.providers.asr.base import ASRProviderBase - -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - -CLIENT_FULL_REQUEST = 0b0001 -CLIENT_AUDIO_ONLY_REQUEST = 0b0010 - -NO_SEQUENCE = 0b0000 -NEG_SEQUENCE = 0b0010 - -SERVER_FULL_RESPONSE = 0b1001 -SERVER_ACK = 0b1011 -SERVER_ERROR_RESPONSE = 0b1111 - -NO_SERIALIZATION = 0b0000 -JSON = 0b0001 -THRIFT = 0b0011 -CUSTOM_TYPE = 0b1111 -NO_COMPRESSION = 0b0000 -GZIP = 0b0001 -CUSTOM_COMPRESSION = 0b1111 - -def parse_response(res): - """ - protocol_version(4 bits), header_size(4 bits), - message_type(4 bits), message_type_specific_flags(4 bits) - serialization_method(4 bits) message_compression(4 bits) - reserved (8bits) 保留字段 - header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) - payload 类似与http 请求体 - """ - protocol_version = res[0] >> 4 - header_size = res[0] & 0x0f - message_type = res[1] >> 4 - message_type_specific_flags = res[1] & 0x0f - serialization_method = res[2] >> 4 - message_compression = res[2] & 0x0f - reserved = res[3] - header_extensions = res[4:header_size * 4] - payload = res[header_size * 4:] - result = {} - payload_msg = None - payload_size = 0 - if message_type == SERVER_FULL_RESPONSE: - payload_size = int.from_bytes(payload[:4], "big", signed=True) - payload_msg = payload[4:] - elif message_type == SERVER_ACK: - seq = int.from_bytes(payload[:4], "big", signed=True) - result['seq'] = seq - if len(payload) >= 8: - payload_size = int.from_bytes(payload[4:8], "big", signed=False) - payload_msg = payload[8:] - elif message_type == SERVER_ERROR_RESPONSE: - code = int.from_bytes(payload[:4], "big", signed=False) - result['code'] = code - payload_size = int.from_bytes(payload[4:8], "big", signed=False) - payload_msg = payload[8:] - if payload_msg is None: - return result - if message_compression == GZIP: - payload_msg = gzip.decompress(payload_msg) - if serialization_method == JSON: - payload_msg = json.loads(str(payload_msg, "utf-8")) - elif serialization_method != NO_SERIALIZATION: - payload_msg = str(payload_msg, "utf-8") - result['payload_msg'] = payload_msg - result['payload_size'] = payload_size - return result - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - self.appid = config.get("appid") - self.cluster = config.get("cluster") - self.access_token = config.get("access_token") - self.output_dir = config.get("output_dir") - - self.host = "openspeech.bytedance.com" - self.ws_url = f"wss://{self.host}/api/v2/asr" - self.success_code = 1000 - self.seg_duration = 15000 - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str: - """将Opus音频数据解码并保存为WAV文件""" - file_name = f"asr_{session_id}_{uuid.uuid4()}.wav" - file_path = os.path.join(self.output_dir, file_name) - - decoder = opuslib.Decoder(16000, 1) # 16kHz, 单声道 - pcm_data = [] - - for opus_packet in opus_data: - try: - pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms - pcm_data.append(pcm_frame) - except opuslib.OpusError as e: - logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) - - with wave.open(file_path, "wb") as wf: - wf.setnchannels(1) - wf.setsampwidth(2) # 2 bytes = 16-bit - wf.setframerate(16000) - wf.writeframes(b"".join(pcm_data)) - - return file_path - - @staticmethod - def _generate_header(message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE) -> bytearray: - """Generate protocol header.""" - header = bytearray() - header_size = 1 - header.append((0b0001 << 4) | header_size) # Protocol version - header.append((message_type << 4) | message_type_specific_flags) - header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression - header.append(0x00) # reserved - return header - - def _construct_request(self, reqid) -> dict: - """Construct the request payload.""" - return { - "app": { - "appid": self.appid, - "cluster": self.cluster, - "token": self.access_token, - }, - "user": { - "uid": str(uuid.uuid4()), - }, - "request": { - "reqid": reqid, - "show_utterances": False, - "sequence": 1 - }, - "audio": { - "format": "wav", - "rate": 16000, - "language": "zh-CN", - "bits": 16, - "channel": 1, - "codec": "raw", - }, - } - - async def _send_request(self, audio_data: List[bytes], segment_size: int) -> Optional[str]: - """Send request to Volcano ASR service.""" - try: - auth_header = {'Authorization': 'Bearer; {}'.format(self.access_token)} - async with websockets.connect(self.ws_url, additional_headers=auth_header) as websocket: - # Prepare request data - request_params = self._construct_request(str(uuid.uuid4())) - print(request_params) - payload_bytes = str.encode(json.dumps(request_params)) - payload_bytes = gzip.compress(payload_bytes) - full_client_request = self._generate_header() - full_client_request.extend((len(payload_bytes)).to_bytes(4, 'big')) # payload size(4 bytes) - full_client_request.extend(payload_bytes) # payload - - # Send header and metadata - # full_client_request - await websocket.send(full_client_request) - res = await websocket.recv() - result = parse_response(res) - if 'payload_msg' in result and result['payload_msg']['code'] != self.success_code: - logger.bind(tag=TAG).error(f"ASR error: {result}") - return None - - for seq, (chunk, last) in enumerate(self.slice_data(audio_data, segment_size), 1): - if last: - audio_only_request = self._generate_header( - message_type=CLIENT_AUDIO_ONLY_REQUEST, - message_type_specific_flags=NEG_SEQUENCE - ) - else: - audio_only_request = self._generate_header( - message_type=CLIENT_AUDIO_ONLY_REQUEST - ) - payload_bytes = gzip.compress(chunk) - audio_only_request.extend((len(payload_bytes)).to_bytes(4, 'big')) # payload size(4 bytes) - audio_only_request.extend(payload_bytes) # payload - # Send audio data - await websocket.send(audio_only_request) - - # Receive response - response = await websocket.recv() - result = parse_response(response) - - if 'payload_msg' in result and result['payload_msg']['code'] == self.success_code: - if len(result['payload_msg']['result']) > 0: - return result['payload_msg']['result'][0]["text"] - return None - else: - logger.bind(tag=TAG).error(f"ASR error: {result}") - return None - - except Exception as e: - logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True) - return None - - @staticmethod - def decode_opus(opus_data: List[bytes], session_id: str) -> List[bytes]: - - decoder = opuslib.Decoder(16000, 1) # 16kHz, 单声道 - pcm_data = [] - - for opus_packet in opus_data: - try: - pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms - pcm_data.append(pcm_frame) - except opuslib.OpusError as e: - logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) - - return pcm_data - - @staticmethod - def read_wav_info(data: io.BytesIO = None) -> (int, int, int, int, int): - with io.BytesIO(data) as _f: - wave_fp = wave.open(_f, 'rb') - nchannels, sampwidth, framerate, nframes = wave_fp.getparams()[:4] - wave_bytes = wave_fp.readframes(nframes) - return nchannels, sampwidth, framerate, nframes, len(wave_bytes) - - @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) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - try: - # 合并所有opus数据包 - pcm_data = self.decode_opus(opus_data, session_id) - combined_pcm_data = b''.join(pcm_data) - - wav_buffer = io.BytesIO() - - with wave.open(wav_buffer, "wb") as wav_file: - wav_file.setnchannels(1) # 设置声道数 - wav_file.setsampwidth(2) # 设置采样宽度 - wav_file.setframerate(16000) # 设置采样率 - wav_file.writeframes(combined_pcm_data) # 写入 PCM 数据 - - # 获取封装后的 WAV 数据 - wav_data = wav_buffer.getvalue() - nchannels, sampwidth, framerate, nframes, wav_len = self.read_wav_info(wav_data) - size_per_sec = nchannels * sampwidth * framerate - segment_size = int(size_per_sec * self.seg_duration / 1000) - - # 语音识别 - start_time = time.time() - text = await self._send_request(wav_data, segment_size) - if text: - logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}") - return text, None - return "", None - - except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", None diff --git a/core/providers/asr/fun_local.py b/core/providers/asr/fun_local.py deleted file mode 100644 index 299713f75..000000000 --- a/core/providers/asr/fun_local.py +++ /dev/null @@ -1,110 +0,0 @@ -import time -import wave -import os -import sys -import io -from abc import ABC, abstractmethod -from config.logger import setup_logging -from typing import Optional, Tuple, List -import uuid -import opuslib_next -from core.providers.asr.base import ASRProviderBase - -from funasr import AutoModel -from funasr.utils.postprocess_utils import rich_transcription_postprocess - -TAG = __name__ -logger = setup_logging() - -# 捕获标准输出 -class CaptureOutput: - def __enter__(self): - self._output = io.StringIO() - self._original_stdout = sys.stdout - sys.stdout = self._output - - def __exit__(self, exc_type, exc_value, traceback): - sys.stdout = self._original_stdout - self.output = self._output.getvalue() - self._output.close() - - # 将捕获到的内容通过 logger 输出 - if self.output: - logger.bind(tag=TAG).info(self.output.strip()) - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - self.model_dir = config.get("model_dir") - self.output_dir = config.get("output_dir") # 修正配置键名 - self.delete_audio_file = delete_audio_file - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - with CaptureOutput(): - self.model = AutoModel( - model=self.model_dir, - vad_kwargs={"max_single_segment_time": 30000}, - disable_update=True, - hub="hf" - # device="cuda:0", # 启用GPU加速 - ) - - def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str: - """将Opus音频数据解码并保存为WAV文件""" - file_name = f"asr_{session_id}_{uuid.uuid4()}.wav" - file_path = os.path.join(self.output_dir, file_name) - - decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 - pcm_data = [] - - for opus_packet in opus_data: - try: - pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms - pcm_data.append(pcm_frame) - except opuslib_next.OpusError as e: - logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) - - with wave.open(file_path, "wb") as wf: - wf.setnchannels(1) - wf.setsampwidth(2) # 2 bytes = 16-bit - wf.setframerate(16000) - wf.writeframes(b"".join(pcm_data)) - - return file_path - - async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]: - """语音转文本主处理逻辑""" - file_path = None - try: - # 保存音频文件 - start_time = time.time() - file_path = self.save_audio_to_file(opus_data, session_id) - logger.bind(tag=TAG).debug(f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}") - - # 语音识别 - start_time = time.time() - result = self.model.generate( - input=file_path, - cache={}, - language="auto", - use_itn=True, - batch_size_s=60, - ) - text = rich_transcription_postprocess(result[0]["text"]) - logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}") - - return text, file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", None - - finally: - # 文件清理逻辑 - if self.delete_audio_file and file_path and os.path.exists(file_path): - try: - os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") - except Exception as e: - logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") diff --git a/core/utils/asr.py b/core/utils/asr.py index 983114d32..ab1c35c4f 100644 --- a/core/utils/asr.py +++ b/core/utils/asr.py @@ -1,24 +1,132 @@ -import importlib -import logging -import os -import sys import time import wave -import uuid +import os +import sys +import io from abc import ABC, abstractmethod -from typing import Optional, Tuple, List -from core.providers.asr.base import ASRProviderBase from config.logger import setup_logging +from typing import Optional, Tuple, List +import uuid + +import opuslib_next +from funasr import AutoModel +from funasr.utils.postprocess_utils import rich_transcription_postprocess TAG = __name__ logger = setup_logging() -def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase: - """工厂方法创建ASR实例""" - if os.path.exists(os.path.join('core', 'providers', 'asr', f'{class_name}.py')): - lib_name = f'core.providers.asr.{class_name}' - if lib_name not in sys.modules: - sys.modules[lib_name] = importlib.import_module(f'{lib_name}') - return sys.modules[lib_name].ASRProvider(*args, **kwargs) +# 捕获标准输出 +class CaptureOutput: + def __enter__(self): + self._output = io.StringIO() + self._original_stdout = sys.stdout + sys.stdout = self._output - raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确") \ No newline at end of file + def __exit__(self, exc_type, exc_value, traceback): + sys.stdout = self._original_stdout + self.output = self._output.getvalue() + self._output.close() + + # 将捕获到的内容通过 logger 输出 + if self.output: + logger.bind(tag=TAG).info(self.output.strip()) + +class ASR(ABC): + @abstractmethod + def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str: + """解码Opus数据并保存为WAV文件""" + pass + + @abstractmethod + def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]: + """将语音数据转换为文本""" + pass + + +class FunASR(ASR): + def __init__(self, config: dict, delete_audio_file: bool): + self.model_dir = config.get("model_dir") + self.output_dir = config.get("output_dir") # 修正配置键名 + self.delete_audio_file = delete_audio_file + + # 确保输出目录存在 + os.makedirs(self.output_dir, exist_ok=True) + with CaptureOutput(): + self.model = AutoModel( + model=self.model_dir, + vad_kwargs={"max_single_segment_time": 30000}, + disable_update=True, + hub="hf" + # device="cuda:0", # 启用GPU加速 + ) + + def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str: + """将Opus音频数据解码并保存为WAV文件""" + file_name = f"asr_{session_id}_{uuid.uuid4()}.wav" + file_path = os.path.join(self.output_dir, file_name) + + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + pcm_data = [] + + for opus_packet in opus_data: + try: + pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms + pcm_data.append(pcm_frame) + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) + + with wave.open(file_path, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) # 2 bytes = 16-bit + wf.setframerate(16000) + wf.writeframes(b"".join(pcm_data)) + + return file_path + + def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]: + """语音转文本主处理逻辑""" + file_path = None + try: + # 保存音频文件 + start_time = time.time() + file_path = self.save_audio_to_file(opus_data, session_id) + logger.bind(tag=TAG).debug(f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}") + + # 语音识别 + start_time = time.time() + result = self.model.generate( + input=file_path, + cache={}, + language="auto", + use_itn=True, + batch_size_s=60, + ) + text = rich_transcription_postprocess(result[0]["text"]) + logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}") + + return text, file_path + + except Exception as e: + logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) + return None, None + + finally: + # 文件清理逻辑 + if self.delete_audio_file and file_path and os.path.exists(file_path): + try: + os.remove(file_path) + logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") + except Exception as e: + logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") + + +def create_instance(class_name: str, *args, **kwargs) -> ASR: + """工厂方法创建ASR实例""" + cls_map = { + "FunASR": FunASR, + # 可扩展其他ASR实现 + } + + if cls := cls_map.get(class_name): + return cls(*args, **kwargs) + raise ValueError(f"不支持的ASR类型: {class_name}") diff --git a/core/utils/dialogue.py b/core/utils/dialogue.py index ddc306d86..703f12c00 100644 --- a/core/utils/dialogue.py +++ b/core/utils/dialogue.py @@ -19,18 +19,6 @@ class Dialogue: def put(self, message: Message): self.dialogue.append(message) - def get_llm_dialogue_with_memory(self, memory_data:str) -> List[Dict[str, str]]: - dialogue = [] - - for m in self.dialogue: - if m.role == "system" and len(memory_data.strip()) > 0: - content = f"{m.content}\n\n你还保留着一些长期的记忆,这有助于让你的对话更加丰富和连贯:\n{memory_data}" - else: - content = m.content - dialogue.append({"role": m.role, "content": content}) - - return dialogue - def get_llm_dialogue(self) -> List[Dict[str, str]]: dialogue = [] for m in self.dialogue: diff --git a/core/utils/embedding.py b/core/utils/embedding.py deleted file mode 100644 index 4701cbf67..000000000 --- a/core/utils/embedding.py +++ /dev/null @@ -1,49 +0,0 @@ -from abc import ABC, abstractmethod -import os -from config.logger import setup_logging -TAG = __name__ -logger = setup_logging() - - -class EMBD(ABC): - @abstractmethod - def encode(self, conn, data): - pass - -class SentenceEMBD(EMBD): - def __init__(self, config: dict,): - from sentence_transformers import SentenceTransformer,export_optimized_onnx_model - self.model_dir = config.get("model_dir") - self.device = config.get("device","cpu") - # model_dir = "jinaai/jina-embeddings-v2-base-zh" - if not os.path.exists(os.path.join(self.model_dir,"onnx","model_O3.onnx")): - self.model = SentenceTransformer( - self.model_dir, - backend="onnx", - device=self.device, - model_kwargs={"file_name": "model.onnx"} - ) - export_optimized_onnx_model(self.model, "O3", self.model_dir) - logger.bind(tag=TAG).info(f"优化模型成功: {self.model_dir}") - - self.model = SentenceTransformer( - self.model_dir, - backend="onnx", - model_kwargs={"file_name": "onnx/model_O3.onnx"}, - device=self.device, - ) - logger.bind(tag=TAG).info(f"加载模型成功: {self.model_dir}") - - def encode(self, data): - return self.model.encode(data) - -def create_instance(class_name: str, *args, **kwargs) -> EMBD: - """工厂方法创建embedding实例""" - - model_map = { - "SentenceTransformer": SentenceEMBD, - } - - if cls := model_map.get(class_name): - return cls(*args, **kwargs) - raise ValueError(f"不支持的embedding类型: {class_name}") \ No newline at end of file diff --git a/core/utils/llm_memory.py b/core/utils/llm_memory.py deleted file mode 100644 index ac5aa6255..000000000 --- a/core/utils/llm_memory.py +++ /dev/null @@ -1,492 +0,0 @@ -import hashlib -import threading -import json -import os -from collections import deque -import uuid - -from numpy.linalg import norm -import asyncio -from concurrent.futures import ThreadPoolExecutor -import numpy as np -from datetime import datetime -from config.logger import setup_logging -TAG = __name__ -logger = setup_logging() -# Cosine similarity function -cos_sim = lambda a, b: (a @ b.T) / (norm(a) * norm(b)) - - -import numpy as np - -class IntentRecognizer: - intent_embeddings_cache = {} - cache_lock = threading.Lock() - def __init__(self, embedding_model): - self.embedding_model = embedding_model - # 存储注册的意图和相似度阈值以及对应的回调函数 - self.intent_callbacks = [] - - def register_intent(self, intent_phrases, callback_function, similarity_threshold=0.7): - """ - 注册一个意图 - :param intent_phrases: 意图相关的短语列表 - :param callback_function: 对应的回调函数 - :param similarity_threshold: 意图与查询的相似度阈值,默认为0.7 - """ - with self.cache_lock: - for phrase in intent_phrases: - # 如果该短语的嵌入已经缓存,则直接使用缓存 - if phrase not in IntentRecognizer.intent_embeddings_cache: - # 计算嵌入并缓存 - intent_embedding = self.embedding_model.encode([phrase])[0] - IntentRecognizer.intent_embeddings_cache[phrase] = intent_embedding - else: - # 使用缓存的嵌入 - intent_embedding = IntentRecognizer.intent_embeddings_cache[phrase] - - # 存储每个意图短语及其对应的回调函数和相似度阈值 - self.intent_callbacks.append({ - "phrase": phrase, - "embedding": intent_embedding, - "callback": callback_function, - "threshold": similarity_threshold - }) - - def handle_query(self, query: str, *args, **kwargs): - """ - 处理用户查询并进行意图识别,调用匹配的回调函数 - :param query: 用户查询 - :param args: 任意位置参数传递给回调函数 - :param kwargs: 任意关键字参数传递给回调函数 - :return: 回调函数的返回值 - """ - query = query.strip() - # 计算用户查询的嵌入表示 - query_embedding = self.embedding_model.encode([query])[0] - - best_match = None - highest_similarity = -1 - matched_callback = None - - # 比较查询与注册的意图短语的相似度 - for intent in self.intent_callbacks: - similarity = np.dot(query_embedding, intent["embedding"]) / (np.linalg.norm(query_embedding) * np.linalg.norm(intent["embedding"])) - if similarity > highest_similarity and similarity >= intent["threshold"]: - highest_similarity = similarity - best_match = intent["phrase"] - matched_callback = intent["callback"] - - if best_match and matched_callback: - # 调用与匹配意图对应的回调函数,传递位置参数和关键字参数 - logger.info(f"{query}\t意图识别结果:{best_match}\tfunc:{matched_callback}\t (相似度: {highest_similarity:.2f})") - return matched_callback(query,*args, **kwargs) - logger.info(f"{query}\t未识别到意图") - return None - - - - - - -class MemoryManager: - _instance = None - _lock = threading.Lock() - - def __new__(cls, *args, **kwargs): - with cls._lock: - if cls._instance is None: - cls._instance = super(MemoryManager, cls).__new__(cls) - return cls._instance - - def __init__( - self, - llm, - embd, - summary_prompt: str = "请总结下面的聊天内容,必须在{content_len}字数以内,必须包含聊天的完整细节:\n\n{content}", - max_memory_length: int = 1000, - summary_length: int = 1000, - max_summary_length: int = 2000, - - memory_dir='memory_data' - ): - """ - 初始化记忆管理类 - :param embedding_model: 用于生成文本嵌入的模型 - :param max_memory_length: 最大记忆总字符长度 - :param summary_length: 每次生成的总结的长度 - :param memory_file: 保存记忆数据的文件路径 - """ - logger.info(f"初始化记忆管理器 max_memory_length:{max_memory_length} summary_length:{summary_length} max_summary_length:{max_summary_length}") - self.max_memory_length = max_memory_length - self.summary_length = summary_length - self.max_summary_length = max_summary_length - - self.memory_data = {} # 用字典管理每个用户的记忆 - self.lock = threading.Lock() # 锁对象,用于线程同步 - self.summary_prompt = summary_prompt - self.llm = llm - self.embedding_model = embd # 用于生成文本的嵌入 - - self.memory_dir = memory_dir - if not os.path.exists(self.memory_dir): - os.makedirs(self.memory_dir,exist_ok=True) # 创建目录 - - # 确保目录具有读写权限 - if not os.access(self.memory_dir, os.W_OK): - try: - os.chmod(self.memory_dir, 0o700) # 设置读写权限 - logger.info(f"已为目录 {self.memory_dir} 设置读写权限") - except Exception as e: - logger.warning(f"无法修改 {self.memory_dir} 的权限: {e}") - raise PermissionError(f"没有足够权限访问目录: {self.memory_dir}") - # 加载已有记忆或初始化新的记忆 - self.load_memory() - - # ThreadPoolExecutor for async tasks - self.executor = ThreadPoolExecutor() - - - self.intent_recognizer = IntentRecognizer(self.embedding_model) - self.intent_recognizer.register_intent( - ["回忆对话", "回忆上次讲的", "请回忆","有什么记忆","刚才讲了什么","上次讲了什么"], - self._recall_last_conversation, - similarity_threshold=0.7 - ) - self.intent_recognizer.register_intent( - ["删除我的记忆","删除所有记忆"], - self._del_all, - similarity_threshold=0.9 - ) - - def _recall_last_conversation(self,query: str, token_name: str)->str: - """ - 回忆上次的对话 - :param token_name: 用户唯一标识符 - :param query: 用户查询 - :return: 上次的对话内容 - """ - user_memory = self.search_memory(token_name, query, top_k=5) - - - if len(user_memory) == 0: - - user_memory = self.memory_data.get(token_name, {'memory':[]}) - - user_memory = list(user_memory['memory']) - user_memory = user_memory[-10:] - - - - output = "\n".join([msg['content'] for msg in user_memory]) - - - return f"{query}\n\n我们上次聊到了:\n\n{output}" - - def _generate_summary(self, chat_paragraph: list): - """ - 生成聊天内容的总结(可以根据具体要求定制总结逻辑) - :param chat_content: 聊天内容 - :return: 总结的字符串 - """ - if self.llm is None: - return "".join([msg['content'] for msg in chat_paragraph])[:self.summary_length] - - response_message = [] - try: - llm_responses = self.llm.response( - str(uuid.uuid4()), - [ - { - "role": "user", - "content": self.summary_prompt.format(content=json.dumps(chat_paragraph),content_len=self.summary_length) - } - ] - ) - except Exception as e: - logger.warning(f"LLM 处理出错 {query}: {e}") - return None - - for content in llm_responses: - response_message.append(content) - return "".join(response_message) - - def _forget_old_memory(self, token_name: str): - """ - 超过最大记忆总长度时,删除不重要的记忆 - :param token_name: 用户唯一标识符 - """ - user_memory = self.memory_data.get(token_name, {'memory': deque(), 'total_length': 0}) - - while user_memory['total_length'] > self.max_memory_length and user_memory['memory']: - # 删除最旧的聊天内容和对应的嵌入 - oldest_message = user_memory['memory'].popleft() - oldest_embedding = user_memory['embeddings'].popleft() # Remove corresponding embedding - user_memory['total_length'] -= len(oldest_message['content']) - - - - def _update_summary(self, token_name: str, chat_paragraph: list[dict]): - """ - 更新记忆总结,合并每个聊天段落的内容并生成摘要 - :param token_name: 用户唯一标识符 - """ - - if len(chat_paragraph) == 0: - return - - summary = self._generate_summary(chat_paragraph) - - if summary is None or len(summary.strip()) == 0: - return - - self.memory_data[token_name].setdefault('memory_summary', []).append(summary) - - # 生成并保存摘要的嵌入 - summary_embedding = self.embedding_model.encode([summary])[0] - self.memory_data[token_name].setdefault('summary_embeddings', []).append(summary_embedding) - - def _combine_summary(self, token_name: str): - """ - 将所有的记忆总结合并为一个 - :param token_name: 用户唯一标识符 - """ - - user_memory = self.memory_data.get(token_name, {'memory_summary': []}) - - # 如果没有超过最大总结长度,直接返回 - old_summary = "".join(user_memory['memory_summary']) - if len(user_memory) == 0 or len(old_summary) < self.max_memory_length: - logger.debug("不需要合并,总结长度:", len(old_summary)) - return - logger.debug("合并前的总结长度:", len(old_summary)) - summary = self._generate_summary(user_memory['memory_summary']) - logger.debug("合并后的总结长度:", len(summary)) - self.memory_data[token_name]['memory_summary'] = [summary] - - # 生成并保存摘要的嵌入 - summary_embedding = self.embedding_model.encode([summary])[0] - self.memory_data[token_name]['summary_embeddings'] = [summary_embedding] - - def _del_all(self, query:str, token_name: str)->str: - """ - 删除所有记忆 - :param token_name: 用户唯一标识符 - """ - self.memory_data[token_name] = {'memory': deque(), 'total_length': 0, 'memory_summary': [], 'summary_embeddings': [], 'embeddings': deque()} - self.save_memory() - return f"你必须{query}\n\n你必须回答同意删除所有记忆" - - async def add_chat_paragraph(self, token_name: str, chat_paragraph: list[dict]): - """ - 添加一段聊天内容到记忆中 - :param token_name: 用户唯一标识符 - :param chat_paragraph: 聊天段落,包含多条聊天记录 - """ - loop = asyncio.get_event_loop() - await loop.run_in_executor(self.executor, self._add_chat_paragraph, token_name, chat_paragraph) - - def _add_chat_paragraph(self, token_name: str, chat_paragraph: list[dict]): - with self.lock: # 使用锁保证线程安全 - if token_name not in self.memory_data: - self.memory_data[token_name] = {'memory': deque(), 'total_length': 0, 'memory_summary': [], 'summary_embeddings': [], 'embeddings': deque()} - - user_memory = self.memory_data[token_name] - new_embeddings = [] - - for message in chat_paragraph: - role = message['role'] - content = message['content'] - - chat_hash = hashlib.md5(content.encode()).hexdigest() - - user_memory['memory'].append({"role": role, "content": content, "hash": chat_hash, "datatime": "{:%Y-%m-%d %H:%M:%S}".format(datetime.now())}) - user_memory['total_length'] += len(content) - - # 生成嵌入 - embedding = self.embedding_model.encode([content])[0] # 使用嵌入模型生成嵌入 - user_memory['embeddings'].append(embedding) - - # 更新记忆总结 - self._update_summary(token_name, chat_paragraph) - - # 如果记忆超出了限制,删除不重要的内容 - self._forget_old_memory(token_name) - - # 合并压缩记忆总结 - self._combine_summary(token_name) - - # 保存记忆到文件 - self.save_memory() - - def handle_user_scene(self,token_name:str, query: str) -> str: - """ - 解析用户查询 - :param query: 用户查询 - :return: 解析后的查询 - """ - query = query.strip() - if len(query) == 0: - return query - - result = self.intent_recognizer.handle_query(query, token_name) - if result is None: - return query - - return result - - - def get_memory_summary(self, token_name: str) -> str: - """ - 获取当前用户的记忆总结 - :param token_name: 用户唯一标识符 - :return: 当前的总结 - """ - user_memory = self.memory_data.get(token_name, {'memory_summary': []}) - return "\n\n".join(user_memory['memory_summary']) - - def get_full_memory(self, token_name: str) -> list[str]: - """ - 获取当前用户的完整记忆内容 - :param token_name: 用户唯一标识符 - :return: 当前的所有记忆内容 - """ - user_memory = self.memory_data.get(token_name, {'memory': []}) - return [msg['content'] for msg in user_memory['memory']] - - def search_memory(self, token_name: str, query: str, top_k: int = 5, threshold: float = 0.5): - """ - 使用嵌入进行记忆查询 - :param token_name: 用户唯一标识符 - :param query: 查询内容 - :param top_k: 返回最相似的记忆条数 - :param threshold: 相似度阈值,低于此阈值的结果将被忽略 - :return: 最相似的记忆条目 - """ - user_memory = self.memory_data.get(token_name, {'embeddings': []}) - if not user_memory['embeddings']: - return [] - - # 生成查询的嵌入 - query_embedding = self.embedding_model.encode([query])[0] - - # 计算查询与记忆中每条消息的相似度 - similarities = [cos_sim(query_embedding, embedding) for embedding in user_memory['embeddings']] - - # 获取最相似的记忆条目,过滤相似度低于阈值的结果 - filtered_indices = [i for i, sim in enumerate(similarities) if sim >= threshold] - top_indices = sorted(filtered_indices, key=lambda i: similarities[i], reverse=True)[:top_k] - similar_memory = [user_memory['memory'][i] for i in top_indices] - - return similar_memory - - def search_memory_summary(self, token_name: str, query: str, top_k: int = 5, threshold: float = 0.5): - """ - 使用嵌入进行记忆总结查询 - :param token_name: 用户唯一标识符 - :param query: 查询内容 - :param top_k: 返回最相似的记忆条数 - :param threshold: 相似度阈值,低于此阈值的结果将被忽略 - :return: 最相似的记忆总结条目 - """ - user_memory = self.memory_data.get(token_name, {'memory_summary': [], 'summary_embeddings': []}) - if not user_memory['summary_embeddings']: - return [] - - # 生成查询的嵌入 - query_embedding = self.embedding_model.encode([query])[0] - - # 计算查询与记忆总结的相似度 - similarities = [cos_sim(query_embedding, embedding) for embedding in user_memory['summary_embeddings']] - - # 获取最相似的记忆总结条目,过滤相似度低于阈值的结果 - filtered_indices = [i for i, sim in enumerate(similarities) if sim >= threshold] - top_indices = sorted(filtered_indices, key=lambda i: similarities[i], reverse=True)[:top_k] - similar_summary = [user_memory['memory_summary'][i] for i in top_indices] - - return similar_summary - def save_memory(self): - """ - 将记忆保存到本地文件,每个文件以token_name作为文件名 - """ - try: - for token_name, user_data in self.memory_data.items(): - memory_data_serializable = { - 'memory': list(user_data['memory']), - 'total_length': user_data['total_length'], - 'memory_summary': user_data['memory_summary'], - 'summary_embeddings': [embedding.tolist() for embedding in user_data['summary_embeddings']], - 'embeddings': [embedding.tolist() for embedding in user_data['embeddings']] - } - - file_path = os.path.join(self.memory_dir, f"{token_name}.json") - with open(file_path, 'w', encoding='utf-8') as file: - json.dump(memory_data_serializable, file, ensure_ascii=False, indent=4) - logger.info(f"记忆已保存至 {file_path}") - - except Exception as e: - logger.warning(f"保存记忆时出错: {e}") - - def load_memory(self): - """ - 从本地文件加载记忆数据 - """ - try: - self.memory_data = {} - - for file_name in os.listdir(self.memory_dir): - if file_name.endswith('.json'): - token_name = file_name[:-5] # 去掉 .json 后缀 - file_path = os.path.join(self.memory_dir, file_name) - - with open(file_path, 'r', encoding='utf-8') as file: - try: - memory_data = json.load(file) - except Exception as e: - logger.warning(f"加载记忆{file_path}时出错: {e}") - continue - - self.memory_data[token_name] = { - 'memory': deque(memory_data['memory']), - 'total_length': memory_data['total_length'], - 'memory_summary': memory_data['memory_summary'], - 'summary_embeddings': [np.array(embedding) for embedding in memory_data['summary_embeddings']], - 'embeddings': deque([np.array(embedding) for embedding in memory_data['embeddings']]) - } - logger.info(f"记忆已从 {file_path} 加载") - - except Exception as e: - logger.warning(f"加载记忆时出错: {e}") - - -if __name__ == '__main__': - from sentence_transformers import SentenceTransformer - # 示例使用 - embedding_model = SentenceTransformer('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True, device="cpu") - memory_manager = MemoryManager(llm=None, embd=embedding_model, max_memory_length=100) - - # 模拟两段对话 - chat_paragraph1 = [ - {"role": "user", "content": "吹到了你的发。😔"}, - {"role": "assistant", "content": "发丝轻拂,独怜此际,梦断谁家?😔"} - ] - - chat_paragraph2 = [ - {"role": "user", "content": "今天天气。😔"}, - {"role": "assistant", "content": "晴天?😔"} - ] - - # 添加第一段聊天 - asyncio.run(memory_manager.add_chat_paragraph("user1", chat_paragraph1)) - - # 添加第二段聊天 - asyncio.run(memory_manager.add_chat_paragraph("user1", chat_paragraph2)) - - # 使用嵌入进行记忆查询 - query = "今天天气?" - similar_memory = memory_manager.search_memory("user1", query, threshold=0.5) - print("最相似的记忆内容:", [msg['content'] for msg in similar_memory]) - - # 使用嵌入进行记忆总结查询 - similar_summary = memory_manager.search_memory_summary("user1", query, threshold=0.5) - print("最相似的记忆总结:", similar_summary) diff --git a/core/utils/util.py b/core/utils/util.py index e06994829..0c1b5b6ee 100644 --- a/core/utils/util.py +++ b/core/utils/util.py @@ -35,9 +35,7 @@ def write_json_file(file_path, data): def is_segment(tokens): - if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":") and len(tokens) > 5: - return True - elif tokens[-1] in ( ".", "?", "。", "?", "!", "!", ";", ";", ): + if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":"): return True else: return False diff --git a/core/websocket_server.py b/core/websocket_server.py index 829801ba2..d8dce04d8 100644 --- a/core/websocket_server.py +++ b/core/websocket_server.py @@ -3,7 +3,7 @@ import websockets from config.logger import setup_logging from core.connection import ConnectionHandler from core.utils.util import get_local_ip -from core.utils import asr, vad, llm, tts, embedding +from core.utils import asr, vad, llm, tts TAG = __name__ @@ -11,7 +11,7 @@ class WebSocketServer: def __init__(self, config: dict): self.config = config self.logger = setup_logging() - self._vad, self._asr, self._llm, self._tts, self._embd = self._create_processing_instances() + self._vad, self._asr, self._llm, self._tts = self._create_processing_instances() def _create_processing_instances(self): """创建处理模块实例""" @@ -21,10 +21,7 @@ class WebSocketServer: self.config["VAD"][self.config["selected_module"]["VAD"]] ), asr.create_instance( - self.config["selected_module"]["ASR"] - if not 'type' in self.config["ASR"][self.config["selected_module"]["ASR"]] - else - self.config["ASR"][self.config["selected_module"]["ASR"]]["type"], + self.config["selected_module"]["ASR"], self.config["ASR"][self.config["selected_module"]["ASR"]], self.config["delete_audio"] ), @@ -42,10 +39,6 @@ class WebSocketServer: self.config["TTS"][self.config["selected_module"]["TTS"]]["type"], self.config["TTS"][self.config["selected_module"]["TTS"]], self.config["delete_audio"] - ), - embedding.create_instance( - self.config["selected_module"]["EMBD"], - self.config["EMBD"][self.config["selected_module"]["EMBD"]] ) ) @@ -65,5 +58,5 @@ class WebSocketServer: async def _handle_connection(self, websocket): """处理新连接,每次创建独立的ConnectionHandler""" - handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._embd) + handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts) await handler.handle_connection(websocket) diff --git a/docker-compose.yml b/docker-compose.yml index ba75c9bc7..49e26d81b 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,4 +10,4 @@ services: - "8002:8002" volumes: - ./data:/app/data - - ./models/SenseVoiceSmall/model.pt:/app/models/SenseVoiceSmall/model.pt + - ./models/SenseVoiceSmall/model.pt:/app/models/SenseVoiceSmall/model.pt \ No newline at end of file diff --git a/docs/Deployment-silm.md b/docs/Deployment-silm.md index e4ac648d6..404106efa 100644 --- a/docs/Deployment-silm.md +++ b/docs/Deployment-silm.md @@ -110,12 +110,6 @@ docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconf 然后就和正常开发一样了 -进入`bash` - -```sh -docker exec -it xiaozhi-env /bin/bash -``` - ## 3.安装依赖 在刚刚的打开的终端运行 diff --git a/docs/Embe.md b/docs/Embe.md deleted file mode 100644 index 8845d216d..000000000 --- a/docs/Embe.md +++ /dev/null @@ -1,13 +0,0 @@ -# mac - -docker需要开8g才能运行成功 - -后续设备对话又爆内存 - -```sh -brew install git-lfs -cd models -GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/jinaai/jina-embeddings-v2-base-zh -cd jina-embeddings-v2-base-zh -git lfs pull -``` \ No newline at end of file diff --git a/poetry.lock b/poetry.lock index 315554087..8e2114bae 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3732,4 +3732,4 @@ propcache = ">=0.2.0" [metadata] lock-version = "2.1" python-versions = "^3.10.16" -content-hash = "9d724dd1cc50a7a6a42f0b5d8a81ad788332939ffc6a3ba12537106567f4ebe7" \ No newline at end of file +content-hash = "9d724dd1cc50a7a6a42f0b5d8a81ad788332939ffc6a3ba12537106567f4ebe7" diff --git a/pyproject.toml b/pyproject.toml index cb32e4a43..2ee2fc148 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,4 +30,4 @@ opuslib-next = "^1.1.2" [build-system] requires = ["poetry-core"] -build-backend = "poetry.core.masonry.api" \ No newline at end of file +build-backend = "poetry.core.masonry.api" diff --git a/requirements.txt b/requirements.txt index e5918196d..bfa9ed803 100755 --- a/requirements.txt +++ b/requirements.txt @@ -16,5 +16,4 @@ aiohttp_cors==0.7.0 ormsgpack==1.7.0 ruamel.yaml==0.18.10 loguru==0.7.3 -requests>=2.0.0 -#sentence-transformers[onnx]==3.4.1 +requests>=2.0.0 \ No newline at end of file