mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
添加豆包在线 ASR (#82)
* 添加 长期记忆功能 * fix bugs * add memory parm for config.yaml * fix is_segment for tts * 推送主分支测试 * 🎈 perf: 美化log * 🐞 fix: bug 改用opus_next,增加文档 * 合并main到develop (#75) * fix: 多种docker build 编译方式 * fix:push * 优化打包速度 (#65) * 🐳 chore: 优化打包速度 使用国内镜像 * 🎈 perf: 优化打包速度 注释日志的时间信息 * 合并多个更新 (#68) * 🐳 chore: 优化打包速度 使用国内镜像 * 🎈 perf: 优化打包速度 注释日志的时间信息 * 🐳 chore: 改用docker hub * 🐎 ci(ci): 自动打包docker * 🐳 chore: 更新文档 * 🎈 perf: 改用opuslib_next * 🌈 style: 统一log * minimax语音tts和阿里云智能语音tts适配 * 本地模型不重复创建,共用一个 (#51) * 本地模型不重复创建,共用一个 * 更新web端页面发布版本 * 🎈 perf: 优化开发体验 (#70) 添加内置模型下载,yarn --------- Co-authored-by: TOM88812 <ttangxs0808@163.com> Co-authored-by: HonestQiao <honestqiao@163.com> Co-authored-by: 玄凤科技 <128943504+Eric0308@users.noreply.github.com> Co-authored-by: 欣南科技 <huangrongzhuang@xin-nan.com> Co-authored-by: Huang <32005838+openrz@users.noreply.github.com> * feat: support doubao online ASR * feat: support doubao online ASR --------- Co-authored-by: fofo <zhongpei@vip.qq.com> Co-authored-by: hrz <1710360675@qq.com> Co-authored-by: 玄凤科技 <128943504+Eric0308@users.noreply.github.com> Co-authored-by: kalicyh <34980061+kalicyh@users.noreply.github.com> Co-authored-by: TOM88812 <ttangxs0808@163.com> Co-authored-by: HonestQiao <honestqiao@163.com> Co-authored-by: 欣南科技 <huangrongzhuang@xin-nan.com> Co-authored-by: Huang <32005838+openrz@users.noreply.github.com> Co-authored-by: 胡垚 <qsct9501@163.com>
This commit is contained in:
parent
afa469c08c
commit
14b8adf964
23 changed files with 1115 additions and 149 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -1,5 +1,6 @@
|
|||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
.idea/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
|
|
@ -145,3 +146,4 @@ tmp
|
|||
.private_config.yaml
|
||||
.env.development
|
||||
docker-compose.yml
|
||||
models/jina-embeddings-v2-base-zh/onnx/model.onnx
|
||||
|
|
|
|||
|
|
@ -24,7 +24,13 @@ WORKDIR /app
|
|||
COPY requirements.txt .
|
||||
|
||||
# 优化apt安装
|
||||
RUN pip install --no-cache-dir -r requirements.txt \
|
||||
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 \
|
||||
-i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
|
||||
# 第三阶段:生产镜像
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
||||
|
|
|
|||
29
config.yaml
29
config.yaml
|
|
@ -38,6 +38,20 @@ 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标签。
|
||||
|
|
@ -65,11 +79,19 @@ 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:
|
||||
|
|
@ -77,6 +99,13 @@ 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:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
from core.utils import asr, vad, llm, tts, embedding
|
||||
from manager.api.user_manager import UserManager
|
||||
from core.utils.lock_manager import FileLockManager
|
||||
|
||||
|
|
@ -192,6 +192,10 @@ 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"]]
|
||||
)
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -17,12 +17,13 @@ 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):
|
||||
def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _embd):
|
||||
self.config = config
|
||||
self.logger = setup_logging()
|
||||
self.auth = AuthMiddleware(config)
|
||||
|
|
@ -49,6 +50,7 @@ class ConnectionHandler:
|
|||
self.asr = _asr
|
||||
self.llm = _llm
|
||||
self.tts = _tts
|
||||
self.embd = _embd
|
||||
self.dialogue = None
|
||||
|
||||
# vad相关变量
|
||||
|
|
@ -83,6 +85,17 @@ 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
|
||||
|
|
@ -93,11 +106,13 @@ 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()
|
||||
|
|
@ -112,7 +127,9 @@ 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
|
||||
|
|
@ -139,6 +156,7 @@ 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:
|
||||
|
|
@ -147,6 +165,8 @@ 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
|
||||
|
||||
|
|
@ -180,6 +200,7 @@ class ConnectionHandler:
|
|||
return False
|
||||
return True
|
||||
|
||||
|
||||
def isNeedAuth(self):
|
||||
bUsePrivateConfig = self.config.get("use_private_config", False)
|
||||
if not bUsePrivateConfig:
|
||||
|
|
@ -200,13 +221,18 @@ class ConnectionHandler:
|
|||
loop.close()
|
||||
return True
|
||||
|
||||
query = self.llm_memory.handle_user_scene(self.device_id, query)
|
||||
self.dialogue.put(Message(role="user", content=query))
|
||||
response_message = []
|
||||
start = 0
|
||||
# 提交 LLM 任务
|
||||
try:
|
||||
start_time = time.time() # 记录开始时间
|
||||
llm_responses = self.llm.response(self.session_id, self.dialogue.get_llm_dialogue())
|
||||
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)
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
|
||||
return None
|
||||
|
|
|
|||
|
|
@ -28,15 +28,19 @@ async def handleAudioMessage(conn, audio):
|
|||
if conn.client_voice_stop:
|
||||
conn.client_abort = False
|
||||
conn.asr_server_receive = False
|
||||
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:
|
||||
# 音频太短了,无法识别
|
||||
if len(conn.asr_audio) < 3:
|
||||
conn.asr_server_receive = True
|
||||
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_audio.clear()
|
||||
conn.reset_vad_states()
|
||||
|
||||
|
|
|
|||
26
core/providers/asr/base.py
Normal file
26
core/providers/asr/base.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
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
|
||||
285
core/providers/asr/doubao.py
Normal file
285
core/providers/asr/doubao.py
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
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
|
||||
110
core/providers/asr/fun_local.py
Normal file
110
core/providers/asr/fun_local.py
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
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}")
|
||||
|
|
@ -1,132 +1,24 @@
|
|||
import time
|
||||
import wave
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
from abc import ABC, abstractmethod
|
||||
from config.logger import setup_logging
|
||||
from typing import Optional, Tuple, List
|
||||
import time
|
||||
import wave
|
||||
import uuid
|
||||
|
||||
import opuslib_next
|
||||
from funasr import AutoModel
|
||||
from funasr.utils.postprocess_utils import rich_transcription_postprocess
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple, List
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
from config.logger import setup_logging
|
||||
|
||||
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 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:
|
||||
def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase:
|
||||
"""工厂方法创建ASR实例"""
|
||||
cls_map = {
|
||||
"FunASR": FunASR,
|
||||
# 可扩展其他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)
|
||||
|
||||
if cls := cls_map.get(class_name):
|
||||
return cls(*args, **kwargs)
|
||||
raise ValueError(f"不支持的ASR类型: {class_name}")
|
||||
raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确")
|
||||
|
|
@ -19,6 +19,18 @@ 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<start>{memory_data}</end>"
|
||||
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:
|
||||
|
|
|
|||
49
core/utils/embedding.py
Normal file
49
core/utils/embedding.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
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}")
|
||||
492
core/utils/llm_memory.py
Normal file
492
core/utils/llm_memory.py
Normal file
|
|
@ -0,0 +1,492 @@
|
|||
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)
|
||||
|
|
@ -35,7 +35,9 @@ def write_json_file(file_path, data):
|
|||
|
||||
|
||||
def is_segment(tokens):
|
||||
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":"):
|
||||
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":") and len(tokens) > 5:
|
||||
return True
|
||||
elif tokens[-1] in ( ".", "?", "。", "?", "!", "!", ";", ";", ):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -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
|
||||
from core.utils import asr, vad, llm, tts, embedding
|
||||
|
||||
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._create_processing_instances()
|
||||
self._vad, self._asr, self._llm, self._tts, self._embd = self._create_processing_instances()
|
||||
|
||||
def _create_processing_instances(self):
|
||||
"""创建处理模块实例"""
|
||||
|
|
@ -21,7 +21,10 @@ class WebSocketServer:
|
|||
self.config["VAD"][self.config["selected_module"]["VAD"]]
|
||||
),
|
||||
asr.create_instance(
|
||||
self.config["selected_module"]["ASR"],
|
||||
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["ASR"][self.config["selected_module"]["ASR"]],
|
||||
self.config["delete_audio"]
|
||||
),
|
||||
|
|
@ -39,6 +42,10 @@ 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"]]
|
||||
)
|
||||
)
|
||||
|
||||
|
|
@ -58,5 +65,5 @@ class WebSocketServer:
|
|||
|
||||
async def _handle_connection(self, websocket):
|
||||
"""处理新连接,每次创建独立的ConnectionHandler"""
|
||||
handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts)
|
||||
handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._embd)
|
||||
await handler.handle_connection(websocket)
|
||||
|
|
|
|||
|
|
@ -110,6 +110,12 @@ docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconf
|
|||
|
||||
然后就和正常开发一样了
|
||||
|
||||
进入`bash`
|
||||
|
||||
```sh
|
||||
docker exec -it xiaozhi-env /bin/bash
|
||||
```
|
||||
|
||||
## 3.安装依赖
|
||||
|
||||
在刚刚的打开的终端运行
|
||||
|
|
|
|||
13
docs/Embe.md
Normal file
13
docs/Embe.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# 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
|
||||
```
|
||||
|
|
@ -17,3 +17,4 @@ ormsgpack==1.7.0
|
|||
ruamel.yaml==0.18.10
|
||||
loguru==0.7.3
|
||||
requests>=2.0.0
|
||||
#sentence-transformers[onnx]==3.4.1
|
||||
|
|
|
|||
Loading…
Reference in a new issue