diff --git a/douyin/core/path_config.py b/douyin/core/path_config.py index 0e80cb6..b8b3fd6 100644 --- a/douyin/core/path_config.py +++ b/douyin/core/path_config.py @@ -2,15 +2,21 @@ 路径配置模块:统一管理所有文件路径,便于整理文件夹结构而不影响代码 """ import os +import sys from typing import Optional import json +def _detect_project_root() -> str: + """返回运行根目录;源码运行是仓库根,PyInstaller 运行是 exe 所在目录。""" + if getattr(sys, "frozen", False): + return os.path.dirname(os.path.abspath(sys.executable)) + # __file__ 位于 /douyin/core/path_config.py, + # 所以项目根是当前文件向上两级目录。 + return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + # 项目根目录(所有路径的基准) -# __file__ 位于 /douyin/core/path_config.py, -# 所以项目根是当前文件向上两级目录。 -PROJECT_ROOT = os.path.dirname( - os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -) +PROJECT_ROOT = _detect_project_root() # 运行时路径与设备侧默认路径(支持环境变量覆盖,便于迁移) DEFAULT_ANDROID_SCREENSHOT_PATH = "/sdcard/DCIM/screenshot.png" @@ -250,6 +256,15 @@ def get_run_cli_path() -> str: return os.path.abspath(os.path.join(PROJECT_ROOT, "bin", "run_cli.py")) +def get_run_cli_command() -> list[str]: + """返回启动 run_cli 的命令;源码模式用 Python 脚本,打包模式用同目录 exe。""" + if getattr(sys, "frozen", False): + exe_name = "run_cli.exe" if sys.platform.startswith("win") else "run_cli" + exe_path = os.path.join(PROJECT_ROOT, exe_name) + return [exe_path] + return [sys.executable, get_run_cli_path()] + + def ensure_dir(path: str) -> None: """确保目录存在,不存在则创建""" dir_path = os.path.dirname(path) if os.path.isfile(path) else path diff --git a/gui/gui_core.py b/gui/gui_core.py index 95c4e17..9df46e4 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -192,16 +192,16 @@ class Runner: # 如果 wait_minutes=0,表示无限循环模式 wait_minutes_arg = str(params.wait_minutes) if params.wait_minutes > 0 else "0" - run_cli_path = path_config.get_run_cli_path() + run_cli_cmd = path_config.get_run_cli_command() + run_cli_path = run_cli_cmd[-1] if run_cli_cmd else path_config.get_run_cli_path() if not os.path.exists(run_cli_path): raise FileNotFoundError( - f"未找到 run_cli.py 文件。\n" + f"未找到 run_cli 启动文件。\n" f"预期路径: {run_cli_path}\n" - f"请确保 run_cli.py 位于项目根目录。" + f"请确保 run_cli.py 位于源码项目,或 run_cli.exe 位于安装目录。" ) cmd = [ - sys.executable, - run_cli_path, + *run_cli_cmd, "--y-pianyi", str(params.y_pianyi), "--wait-minutes", @@ -369,9 +369,8 @@ class Runner: ) except FileNotFoundError as e: raise RuntimeError( - f"无法启动进程:找不到 Python 解释器或 run_cli.py 文件\n" - f"Python路径: {sys.executable}\n" - f"run_cli.py路径: {run_cli_path}\n" + f"无法启动进程:找不到 run_cli 启动文件\n" + f"run_cli路径: {run_cli_path}\n" f"原始错误: {e}" ) from e except Exception as e: diff --git a/gui/web_gui.py b/gui/web_gui.py index f4c3c62..e22ac89 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -527,16 +527,16 @@ class ProcRunner: str(_pick("fansclub_fail_action", "") or "").strip().lower() ) - run_cli_path = path_config.get_run_cli_path() + run_cli_cmd = path_config.get_run_cli_command() + run_cli_path = run_cli_cmd[-1] if run_cli_cmd else path_config.get_run_cli_path() if not os.path.exists(run_cli_path): raise FileNotFoundError( - f"run_cli.py not found.\n" + f"run_cli launcher not found.\n" f"Expected path: {run_cli_path}\n" - f"Please ensure run_cli.py is in the project root directory." + f"Please ensure run_cli.py is in the source tree or run_cli.exe is in the install directory." ) cmd = [ - sys.executable, - run_cli_path, + *run_cli_cmd, "--y-pianyi", str(y_pianyi), "--wait-minutes", diff --git a/gui/web_gui_pkg/proc_runner_ops.py b/gui/web_gui_pkg/proc_runner_ops.py index 2bd31d7..1834af4 100644 --- a/gui/web_gui_pkg/proc_runner_ops.py +++ b/gui/web_gui_pkg/proc_runner_ops.py @@ -122,12 +122,13 @@ def start_test_yanghao(self: Any, device_id: str, seconds: int) -> None: seconds = int(seconds or 0) if seconds <= 0: seconds = 60 - run_cli_path = path_config.get_run_cli_path() + run_cli_cmd = path_config.get_run_cli_command() + run_cli_path = run_cli_cmd[-1] if run_cli_cmd else path_config.get_run_cli_path() if not os.path.exists(run_cli_path): raise FileNotFoundError( - f"run_cli.py not found.\nExpected path: {run_cli_path}\nPlease ensure run_cli.py is in the project root directory." + f"run_cli launcher not found.\nExpected path: {run_cli_path}\nPlease ensure run_cli.py is in the source tree or run_cli.exe is in the install directory." ) - cmd = [sys.executable, run_cli_path, "--test-yanghao-flow", "--test-yanghao-flow-seconds", str(seconds)] + cmd = [*run_cli_cmd, "--test-yanghao-flow", "--test-yanghao-flow-seconds", str(seconds)] device_id = resolve_adb_device(find_adb_executable(), device_id) cmd += ["--device-id", device_id] self._start_process(cmd) @@ -137,12 +138,13 @@ def start_test_comment(self: Any, device_id: str, text: str) -> None: if self.is_running(): raise RuntimeError("already running") text = str(text or "").strip() - run_cli_path = path_config.get_run_cli_path() + run_cli_cmd = path_config.get_run_cli_command() + run_cli_path = run_cli_cmd[-1] if run_cli_cmd else path_config.get_run_cli_path() if not os.path.exists(run_cli_path): raise FileNotFoundError( - f"run_cli.py not found.\nExpected path: {run_cli_path}\nPlease ensure run_cli.py is in the project root directory." + f"run_cli launcher not found.\nExpected path: {run_cli_path}\nPlease ensure run_cli.py is in the source tree or run_cli.exe is in the install directory." ) - cmd = [sys.executable, run_cli_path, "--test-comment"] + cmd = [*run_cli_cmd, "--test-comment"] if text: cmd += ["--test-comment-text", text] device_id = resolve_adb_device(find_adb_executable(), device_id) diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 0000000..c95ce6f --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,54 @@ +# Windows 打包说明 + +本目录提供两级交付方式: + +1. PyInstaller 便携目录:生成 `dist/DouyinGuaji-/`,可直接复制给别人运行。 +2. Inno Setup 安装包:基于便携目录生成 `DouyinGuaji--Setup.exe`。 + +## 生成便携目录 + +在项目根目录运行: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 +``` + +如果依赖已经装好,可以跳过安装依赖: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall +``` + +输出目录: + +```text +dist\DouyinGuaji-\ +``` + +主要文件: + +- `DouyinGuajiGUI.exe`:桌面 GUI 主入口 +- `web_gui.exe`:Web GUI 服务入口 +- `run_cli.exe`:后台运行入口,桌面 GUI / Web GUI 会调用它 +- `assets/`、`webui/`、`config/`:运行所需资源 +- `logs/`、`pic/`、`state/`:运行时输出目录 + +## 生成安装包 + +先安装 Inno Setup 6,并确保 `iscc.exe` 在 PATH 中,然后运行: + +```powershell +iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=3.3.3 +``` + +输出目录: + +```text +dist\installer\DouyinGuaji-3.3.3-Setup.exe +``` + +## 发给别人前检查 + +- 目标电脑需要能使用 ADB,或者把 Android platform-tools 加入 PATH。 +- 首次启动 PaddleOCR 相关组件可能较慢,杀毒软件也可能扫描 exe。 +- `config/config.json` 是本地运行配置,默认不随安装包带个人配置;让使用者首次打开后在 GUI 中保存配置。 diff --git a/packaging/inno/douyin_guaji.iss b/packaging/inno/douyin_guaji.iss new file mode 100644 index 0000000..1c06f91 --- /dev/null +++ b/packaging/inno/douyin_guaji.iss @@ -0,0 +1,40 @@ +#define MyAppName "DouyinGuaji" +#ifndef MyAppVersion +#define MyAppVersion "3.3.3" +#endif +#define MyAppPublisher "DouyinGuaji" +#define MyAppExeName "DouyinGuajiGUI.exe" +#define SourceDir "..\..\dist\DouyinGuaji-" + MyAppVersion + +[Setup] +AppId={{8F96B3C6-8C53-4A41-96E2-926A3E9BC0F4} +AppName={#MyAppName} +AppVersion={#MyAppVersion} +AppPublisher={#MyAppPublisher} +DefaultDirName={autopf}\{#MyAppName} +DefaultGroupName={#MyAppName} +DisableProgramGroupPage=yes +OutputDir=..\..\dist\installer +OutputBaseFilename=DouyinGuaji-{#MyAppVersion}-Setup +Compression=lzma +SolidCompression=yes +WizardStyle=modern +ArchitecturesAllowed=x64 +ArchitecturesInstallIn64BitMode=x64 + +[Languages] +Name: "chinesesimp"; MessagesFile: "compiler:Languages\ChineseSimplified.isl" + +[Tasks] +Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加图标:"; Flags: unchecked + +[Files] +Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs + +[Icons] +Name: "{group}\DouyinGuaji 桌面版"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}" +Name: "{group}\DouyinGuaji Web 服务"; Filename: "{app}\web_gui.exe"; WorkingDir: "{app}" +Name: "{autodesktop}\DouyinGuaji"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}"; Tasks: desktopicon + +[Run] +Filename: "{app}\{#MyAppExeName}"; Description: "启动 DouyinGuaji"; Flags: nowait postinstall skipifsilent diff --git a/packaging/pyinstaller/build_windows.ps1 b/packaging/pyinstaller/build_windows.ps1 new file mode 100644 index 0000000..00dede3 --- /dev/null +++ b/packaging/pyinstaller/build_windows.ps1 @@ -0,0 +1,65 @@ +param( + [string]$Version = "", + [switch]$SkipInstall +) + +$ErrorActionPreference = "Stop" +$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..") +Set-Location $Root + +if (-not $Version) { + $Version = (python -c "from douyin.core.version import APP_VERSION; print(str(APP_VERSION).lstrip('Vv'))").Trim() +} + +if (-not $SkipInstall) { + python -m pip install --upgrade pip + python -m pip install -r requirements.txt + python -m pip install pyinstaller +} + +$DistRoot = Join-Path $Root "dist\DouyinGuaji-$Version" +if (Test-Path $DistRoot) { + Remove-Item -LiteralPath $DistRoot -Recurse -Force +} +New-Item -ItemType Directory -Force $DistRoot | Out-Null + +$CommonArgs = @( + "--clean", + "--noconfirm", + "--distpath", $DistRoot, + "--workpath", (Join-Path $Root "build\pyinstaller"), + "--paths", $Root, + "--add-data", "assets;assets", + "--add-data", "webui;webui", + "--add-data", "config\README.md;config", + "--hidden-import", "PIL._tkinter_finder", + "--hidden-import", "ttkbootstrap" +) + +python -m PyInstaller @CommonArgs --name DouyinGuajiGUI --windowed "gui\gui_app.py" +python -m PyInstaller @CommonArgs --name web_gui --console "gui\web_gui.py" +python -m PyInstaller @CommonArgs --name run_cli --console "bin\run_cli.py" + +foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) { + $srcDir = Join-Path $DistRoot $name + Copy-Item -LiteralPath (Join-Path $srcDir "$name.exe") -Destination (Join-Path $DistRoot "$name.exe") -Force +} + +foreach ($dir in @("assets", "webui")) { + $target = Join-Path $DistRoot $dir + if (Test-Path $target) { + Remove-Item -LiteralPath $target -Recurse -Force + } + Copy-Item -LiteralPath (Join-Path $Root $dir) -Destination $target -Recurse -Force +} + +New-Item -ItemType Directory -Force (Join-Path $DistRoot "config") | Out-Null +Copy-Item -LiteralPath (Join-Path $Root "config\README.md") -Destination (Join-Path $DistRoot "config\README.md") -Force +foreach ($dir in @("logs", "pic", "state")) { + New-Item -ItemType Directory -Force (Join-Path $DistRoot $dir) | Out-Null +} + +Copy-Item -LiteralPath (Join-Path $Root "README.md") -Destination (Join-Path $DistRoot "README.md") -Force + +Write-Host "[OK] Portable package: $DistRoot" +Write-Host "[NEXT] If Inno Setup is installed: iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=$Version" diff --git a/tests/test_path_config.py b/tests/test_path_config.py index 72afc74..b2a8066 100644 --- a/tests/test_path_config.py +++ b/tests/test_path_config.py @@ -6,6 +6,7 @@ from __future__ import annotations import os +import sys import pytest @@ -102,6 +103,22 @@ class TestSpecificPaths: monkeypatch.setenv("HOST", "0.0.0.0") assert path_config.get_web_gui_host() == path_config.DEFAULT_WEB_GUI_HOST + def test_run_cli_command_source_mode_uses_python_script(self): + cmd = path_config.get_run_cli_command() + assert cmd[0] == sys.executable + assert cmd[-1].endswith(os.path.join("bin", "run_cli.py")) + + def test_run_cli_command_frozen_mode_uses_sibling_exe(self, monkeypatch): + monkeypatch.setattr(path_config.sys, "frozen", True, raising=False) + monkeypatch.setattr( + path_config.sys, + "executable", + os.path.join(PROJECT_ROOT, "DouyinGuajiGUI.exe"), + ) + assert path_config.get_run_cli_command() == [ + os.path.join(PROJECT_ROOT, "run_cli.exe") + ] + # ============================================================ # 路径间不应互相重复