diff --git a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/Util/__init__.py b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/Util/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/app.py b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/app.py index 1ac0f982..87bb1c69 100644 --- a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/app.py +++ b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/app.py @@ -4,6 +4,7 @@ import signal from config.settings import load_config, check_config_file from core.websocket_server import WebSocketServer from core.utils.util import check_ffmpeg_installed +from core.utils.mysql_util import init_mysql_pool, close_mysql_pool TAG = __name__ @@ -34,6 +35,9 @@ async def main(): # 加载配置 config = load_config() + # 初始化 MySQL 连接池 + await init_mysql_pool() + # 启动 WebSocket 服务器 ws_server = WebSocketServer(config) ws_task = asyncio.create_task(ws_server.start()) @@ -48,6 +52,8 @@ async def main(): await ws_task except asyncio.CancelledError: pass + # 关闭 MySQL 连接池 + await close_mysql_pool() print("服务器已关闭,程序退出。") @@ -55,4 +61,4 @@ if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: - print("手动中断,程序终止。") + print("手动中断,程序终止。") \ No newline at end of file diff --git a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/providers/asr/fun_local.py b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/providers/asr/fun_local.py index 2902017b..06883324 100644 --- a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/providers/asr/fun_local.py +++ b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/providers/asr/fun_local.py @@ -11,7 +11,7 @@ from core.providers.asr.base import ASRProviderBase from funasr import AutoModel from funasr.utils.postprocess_utils import rich_transcription_postprocess - +from core.utils.mysql_util import save_chat_history, get_chat_history TAG = __name__ logger = setup_logging() @@ -95,7 +95,14 @@ class ASRProvider(ASRProviderBase): logger.bind(tag=TAG).info(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}") #【黄海注释】准备在这里进行嵌入代码,把文字+声音的关系记录下来,让用户选择是哪个人进行声纹匹配 - + # 保存聊天记录 + await save_chat_history( + chat_text=text, + chat_wav=file_path, + ai_text='',# 暂时没有记录AI的影响 + person_id="FDE43080-122E-4F5D-B860-4E53DEC54BFB", + person_name='黄海' + ) return text, file_path except Exception as e: diff --git a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/Util/MySQLUtil.py b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/utils/mysql_util.py similarity index 51% rename from XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/Util/MySQLUtil.py rename to XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/utils/mysql_util.py index 55a56de2..c2bb37a4 100644 --- a/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/Util/MySQLUtil.py +++ b/XiaoZhi/xiaozhi-esp32-server/main/xiaozhi-server/core/utils/mysql_util.py @@ -1,27 +1,20 @@ import logging -import asyncio -import uuid from aiomysql import create_pool -from datetime import datetime - -# MYSQL配置信息 -MYSQL_HOST = "10.10.14.203" -MYSQL_PORT = 3306 -MYSQL_USER = "root" -MYSQL_PASSWORD = "Password123@mysql" -MYSQL_DB_NAME = "xiaozhi_esp32_server" # 配置日志 logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") logger = logging.getLogger(__name__) +# 全局 MySQL 连接池 +mysql_pool = None + # MySQL 配置 MYSQL_CONFIG = { - "host": MYSQL_HOST, - "port": MYSQL_PORT, - "user": MYSQL_USER, - "password": MYSQL_PASSWORD, - "db": MYSQL_DB_NAME, + "host": "10.10.14.203", + "port": 3306, + "user": "root", + "password": "Password123@mysql", + "db": "xiaozhi_esp32_server", "minsize": 1, "maxsize": 20, "autocommit": True, @@ -31,32 +24,28 @@ MYSQL_CONFIG = { async def init_mysql_pool(): """初始化 MySQL 连接池""" + global mysql_pool try: - pool = await create_pool(**MYSQL_CONFIG) + mysql_pool = await create_pool(**MYSQL_CONFIG) logger.info("MySQL连接池创建成功") - return pool except Exception as e: logger.error(f"创建MySQL连接池失败: {str(e)}") raise -async def truncate_chat_log(pool): - """清空聊天历史表""" - try: - async with pool.acquire() as conn: - await conn.ping() - async with conn.cursor() as cur: - await cur.execute("TRUNCATE TABLE t_chat_history") - logger.info("表 t_chat_history 已清空") - except Exception as e: - logger.error(f"清空表失败: {str(e)}") - raise +async def close_mysql_pool(): + """关闭 MySQL 连接池""" + global mysql_pool + if mysql_pool: + mysql_pool.close() + await mysql_pool.wait_closed() + logger.info("MySQL连接池已关闭") -async def insert_chat_log(pool, chat_text, chat_wav, ai_text, person_id, person_name): - """插入聊天记录""" +async def save_chat_history(chat_text, chat_wav, ai_text, person_id, person_name): + """保存聊天记录""" try: - async with pool.acquire() as conn: + async with mysql_pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: sql = """ @@ -65,20 +54,19 @@ async def insert_chat_log(pool, chat_text, chat_wav, ai_text, person_id, person_ VALUES (%s, %s, %s, %s, %s) """ await cur.execute(sql, (chat_text, chat_wav, ai_text, person_id, person_name)) - logger.info(f"成功插入聊天记录: {person_name}") + logger.info(f"成功保存聊天记录: {person_name}") return cur.lastrowid except Exception as e: - logger.error(f"插入聊天记录失败: {str(e)}") + logger.error(f"保存聊天记录失败: {str(e)}") raise -async def update_chat_log(pool, chat_id, chat_text=None, chat_wav=None, ai_text=None, person_name=None): +async def update_chat_history(chat_id, chat_text=None, chat_wav=None, ai_text=None, person_name=None): """更新聊天记录""" try: - async with pool.acquire() as conn: + async with mysql_pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: - # 构建更新语句 updates = [] params = [] if chat_text is not None: @@ -107,10 +95,10 @@ async def update_chat_log(pool, chat_id, chat_text=None, chat_wav=None, ai_text= raise -async def delete_chat_log(pool, chat_id): +async def delete_chat_history(chat_id): """删除聊天记录""" try: - async with pool.acquire() as conn: + async with mysql_pool.acquire() as conn: await conn.ping() async with conn.cursor() as cur: sql = "DELETE FROM t_chat_history WHERE id = %s" @@ -121,47 +109,21 @@ async def delete_chat_log(pool, chat_id): raise -async def main(): - """主函数""" - pool = None +async def get_chat_history(person_id=None, limit=10): + """获取聊天记录""" try: - # 初始化连接池 - pool = await init_mysql_pool() - - # 清空表 - await truncate_chat_log(pool) - - # 测试插入 - person_id = str(uuid.uuid4()) - chat_id = await insert_chat_log( - pool=pool, - chat_text="你好,小智", - chat_wav="test.wav", - ai_text="你好,有什么我可以帮你的吗?", - person_id=person_id, - person_name="测试用户" - ) - logger.info(f"插入的聊天记录ID: {chat_id}") - - # 测试更新 - await update_chat_log( - pool=pool, - chat_id=chat_id, - ai_text="你好,很高兴为你服务!", - person_name="更新后的用户" - ) - - # 测试删除 - await delete_chat_log(pool, chat_id) - + async with mysql_pool.acquire() as conn: + await conn.ping() + async with conn.cursor() as cur: + if person_id: + sql = "SELECT * FROM t_chat_history WHERE person_id = %s ORDER BY id DESC LIMIT %s" + await cur.execute(sql, (person_id, limit)) + else: + sql = "SELECT * FROM t_chat_history ORDER BY id DESC LIMIT %s" + await cur.execute(sql, (limit,)) + + result = await cur.fetchall() + return result except Exception as e: - logger.error(f"程序执行出错: {str(e)}") - finally: - if pool: - pool.close() - await pool.wait_closed() - logger.info("MySQL连接池已关闭") - - -if __name__ == '__main__': - asyncio.run(main()) \ No newline at end of file + logger.error(f"获取聊天记录失败: {str(e)}") + raise \ No newline at end of file