Jelajahi Sumber

增加编译生成配置虚拟环境的bat
优化日志目录结构

longjoedyy 1 bulan lalu
induk
melakukan
ccd2649437
3 mengubah file dengan 149 tambahan dan 25 penghapusan
  1. 2 1
      core/chat_service.py
  2. 121 19
      cythonize.py
  3. 26 5
      utils/logger.py

+ 2 - 1
core/chat_service.py

@@ -39,7 +39,8 @@ class ChatService:
             token = request_data["token"]
 
             # 生成用户标识符
-            user_id = self.agent_manager._get_user_identifier(username, token)
+            # user_id = self.agent_manager._get_user_identifier(username, token)
+            user_id = username
 
             chat_logger.info(
                 f"收到请求 - 用户={user_id} , 线程ID={thread_id}, 消息={message[:100]}"

+ 121 - 19
cythonize.py

@@ -218,7 +218,7 @@ def create_get_device_id_script(deploy_dir):
     pause
     """
 
-    bat_file = deploy_dir / "get_device_id.bat"
+    bat_file = deploy_dir / "2_get_device_id.bat"
     bat_file.write_text(bat_content, encoding="utf-8")
 
 
@@ -288,6 +288,94 @@ def create_windows_service_scripts(deploy_dir):
     shutil.copy2(nssm_exe, nssm_dst)
     print("  ✅ 复制 nssm.exe")
 
+    # 配置虚拟环境脚本
+    venv_bat = """
+@echo off
+chcp 65001 >nul
+echo ========================================
+echo   Python Virtual Environment Setup Script
+echo ========================================
+echo.
+
+REM 动态获取脚本所在目录
+set "PROJECT_DIR=%~dp0"
+set "PROJECT_DIR=%PROJECT_DIR:~0,-1%"
+echo 项目目录: %PROJECT_DIR%
+REM 1. Check if in project root
+if not exist "%PROJECT_DIR%\\requirements.txt" (
+    echo [ERROR] Please run in project root directory!
+    echo        requirements.txt not found
+    pause
+    exit /b 1
+)
+
+REM 2. Check Python
+python --version >nul 2>&1
+if errorlevel 1 (
+    echo [ERROR] Python not found. Please install Python or add to PATH
+    pause
+    exit /b 1
+)
+
+REM 3. Check existing venv
+if exist "venv\\" (
+    echo [WARN] Virtual environment 'venv' already exists
+    set /p choice=Delete and recreate? [Y/N]: 
+    if /i "%choice%"=="Y" (
+        echo Removing old virtual environment...
+        rmdir /s /q venv
+    ) else (
+        echo Skip creation, install dependencies directly...
+        goto :install_deps
+    )
+    echo.
+)
+
+REM 4. Create virtual environment
+echo Step 1: Creating virtual environment...
+python -m venv venv
+if errorlevel 1 (
+    echo [ERROR] Failed to create virtual environment
+    pause
+    exit /b 1
+)
+echo [OK] Virtual environment created
+echo.
+
+REM 5. Install dependencies
+:install_deps
+echo Step 2: Installing dependencies...
+call venv\\Scripts\\activate
+if errorlevel 1 (
+    echo [ERROR] Failed to activate virtual environment
+    pause
+    exit /b 1
+)
+
+echo Installing packages from requirements.txt...
+pip install -r "%PROJECT_DIR%\\requirements.txt" -i https://mirrors.aliyun.com/pypi/simple/
+if errorlevel 1 (
+    echo [ERROR] Failed to install dependencies
+    pause
+    exit /b 1
+)
+echo [OK] Dependencies installed
+echo.
+
+REM 6. Verification
+echo Step 3: Verification...
+echo Installed packages:
+venv\\Scripts\\python.exe -m pip list
+if errorlevel 1 (
+    echo [WARN] Failed to list packages
+)
+
+echo.
+echo ========================================
+echo [SUCCESS] Virtual environment setup complete!
+pause
+"""
+
     # 服务安装脚本
     install_bat = """@echo off
 chcp 65001 >nul
@@ -299,8 +387,7 @@ echo.
 REM 检查是否以管理员权限运行
 net session >nul 2>&1
 if %errorlevel% neq 0 (
-    echo Error: 请以管理员权限运行此脚本!
-    echo 请右键点击此脚本 -> "以管理员身份运行"
+    echo Error: 请以管理员身份运行此脚本!
     pause
     exit /b 1
 )
@@ -324,22 +411,23 @@ if not exist "%PROJECT_DIR%\\app.py" (
     exit /b 1
 )
 
-REM 动态查找Python安装路径
-echo 搜索Python安装...
-for /f "delims=" %%i in ('where python') do (
-    set "PYTHON_PATH=%%i"
-    goto :found_python
-)
+REM 设置虚拟环境Python路径
+set "VENV_PYTHON_PATH=%PROJECT_DIR%\\venv\\Scripts\\python.exe"
 
-:found_python
-if not defined PYTHON_PATH (
-    echo 错误: 未找到Python!
-    echo 请安装 Python 3.7+ 并确保其在 PATH 中
+REM 检查虚拟环境Python是否存在
+echo 检查虚拟环境...
+if not exist "%VENV_PYTHON_PATH%" (
+    echo 错误: 虚拟环境中未找到Python!
+    echo 预期路径: %VENV_PYTHON_PATH%
+    echo.
+    echo 请确保:
+    echo 1. 已创建虚拟环境: python -m venv venv
+    echo 2. 已安装依赖: venv\\Scripts\\pip install -r requirements.txt
     pause
     exit /b 1
 )
 
-echo 找到Python: %PYTHON_PATH%
+echo 找到虚拟环境Python: %VENV_PYTHON_PATH%
 
 REM 停止并移除现有服务
 echo Unstall Service
@@ -349,14 +437,16 @@ timeout /t 2 /nobreak >nul
 
 REM 关键修正:使用正确的引号格式(模仿您的成功命令)
 echo 安装 LongjoeAI 服务...
-"%PROJECT_DIR%\\nssm.exe" install LongjoeAI "cmd" "/c cd /d "%PROJECT_DIR%" && "%PYTHON_PATH%" app.py"
+"%PROJECT_DIR%\\nssm.exe" install LongjoeAI "cmd" "/c cd /d "%PROJECT_DIR%" && "%VENV_PYTHON_PATH%" app.py"
 
 if errorlevel 1 (
     echo 错误: 服务安装失败!
     echo.
     echo 调试信息:
     echo 项目目录: %PROJECT_DIR%
-    echo Python 路径: %PYTHON_PATH%
+    echo Python 路径: %VENV_PYTHON_PATH%
+    pause
+    exit /b 1
 )
 
 REM 配置服务参数
@@ -397,8 +487,7 @@ echo.
 REM 检查是否以管理员权限运行
 net session >nul 2>&1
 if %errorlevel% neq 0 (
-    echo 错误: 请以管理员权限运行此脚本!
-    echo 请右键点击此脚本 -> "以管理员身份运行"
+    echo 错误: 请以管理员身份运行运行此脚本!
     pause
     exit /b 1
 )
@@ -427,6 +516,17 @@ pause
     # 服务管理脚本
     manage_bat = """@echo off
 chcp 65001 >nul
+
+REM 检查是否以管理员权限运行
+net session >nul 2>&1
+if %errorlevel% neq 0 (
+    echo 错误: 请以管理员身份运行运行此脚本!
+    pause
+    exit /b 1
+)
+
+:menu
+cls
 echo ========================================
 echo      LongjoeAI Service Management
 echo ========================================
@@ -464,10 +564,12 @@ if "%choice%"=="1" (
 
 echo.
 pause
+goto menu
 """
 
     # 写入脚本文件
-    (deploy_dir / "service_install.bat").write_text(install_bat, encoding="utf-8")
+    (deploy_dir / "1_venv_install.bat").write_text(venv_bat, encoding="utf-8")
+    (deploy_dir / "3_service_install.bat").write_text(install_bat, encoding="utf-8")
     (deploy_dir / "service_uninstall.bat").write_text(uninstall_bat, encoding="utf-8")
     (deploy_dir / "service_manage.bat").write_text(manage_bat, encoding="utf-8")
     print(

+ 26 - 5
utils/logger.py

@@ -9,6 +9,10 @@ from pathlib import Path
 LOG_DIR = Path("chat_logs")
 LOG_DIR.mkdir(exist_ok=True)
 
+# 详细日志目录结构
+DETAILED_LOG_DIR = LOG_DIR / "detailed"
+DETAILED_LOG_DIR.mkdir(exist_ok=True)
+
 
 # 配置日志
 def setup_logging():
@@ -46,11 +50,31 @@ def setup_logging():
 chat_logger = setup_logging()
 
 
+def get_detailed_log_path(user_id: str, timestamp: datetime = None) -> Path:
+    """
+    获取详细日志文件的路径
+    格式: chat_logs/detailed/YYYYMMDD/user_id_YYYYMMDD_HHMMSS.json
+    """
+    if timestamp is None:
+        timestamp = datetime.now()
+
+    # 按日期创建目录
+    date_str = timestamp.strftime("%Y%m%d")
+    date_dir = DETAILED_LOG_DIR / date_str
+    date_dir.mkdir(exist_ok=True)
+
+    # 生成文件名
+    filename = f"{user_id}_{timestamp.strftime('%Y%m%d_%H%M%S')}.json"
+
+    return date_dir / filename
+
+
 def log_chat_entry(user_id: str, user_message: str, agent_response: Dict[str, Any]):
     """记录完整的对话日志"""
     try:
+        timestamp = datetime.now()
         log_entry = {
-            "timestamp": datetime.now().isoformat(),
+            "timestamp": timestamp.isoformat(),
             "user_id": user_id,
             "user_message": user_message,
             "agent_response": {
@@ -79,10 +103,7 @@ def log_chat_entry(user_id: str, user_message: str, agent_response: Dict[str, An
         )
 
         # 保存详细日志到单独文件
-        detailed_log_file = (
-            LOG_DIR
-            / f"detailed_{user_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
-        )
+        detailed_log_file = get_detailed_log_path(user_id, timestamp)
         with open(detailed_log_file, "w", encoding="utf-8") as f:
             json.dump(log_entry, f, ensure_ascii=False, indent=2)