diff --git a/.gitignore b/.gitignore index faa3940..67fcad0 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,9 @@ time_analysis_result.txt # Test/diagnostic outputs output/ +artifacts/ocr_check/ +artifacts/webui_checks/**/*.png +artifacts/webui_checks/**/*.txt # Local runtime state and generated caches state/ @@ -106,6 +109,7 @@ tools/samples/ tools/*.zip tools/*.tar.gz tools/*.bundle +tools/tmp_pw_check.py # Project-specific generated state douyin/core/state/reservations.json @@ -122,6 +126,9 @@ state/high_value_rooms.json *.7z *.bundle +# Local migration scratch notes +docs/json_migration_note.txt + # Node / frontend caches node_modules/ npm-debug.log* diff --git a/bin/gui_app.py b/bin/gui_app.py index a4ace2e..f559571 100644 --- a/bin/gui_app.py +++ b/bin/gui_app.py @@ -8,10 +8,11 @@ import runpy import sys from pathlib import Path +from douyin.core import path_config ROOT_DIR = Path(__file__).resolve().parent.parent TARGET = ROOT_DIR / "gui" / "gui_app.py" -VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe" +VENV_PYTHON = Path(path_config.get_venv_python_path()) def _reexec_with_venv() -> None: diff --git a/bin/webgui_launcher.py b/bin/webgui_launcher.py index e33d641..2365980 100644 --- a/bin/webgui_launcher.py +++ b/bin/webgui_launcher.py @@ -8,10 +8,11 @@ import runpy import sys from pathlib import Path +from douyin.core import path_config ROOT_DIR = Path(__file__).resolve().parent.parent TARGET = ROOT_DIR / "gui" / "webgui_launcher.py" -VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe" +VENV_PYTHON = Path(path_config.get_venv_python_path()) def _reexec_with_venv() -> None: diff --git a/config/config.json b/config/config.json index 2feb0df..94433b3 100644 --- a/config/config.json +++ b/config/config.json @@ -234,8 +234,8 @@ "log_unified_enabled": true, "log_unified_path": "logs/unified.log", "last_wifi_target": { - "target": "192.168.5.2:5555", + "target": "192.168.10.107:39051", "model": "PEPM00", - "saved_at": 1779501066 + "saved_at": 1780284199 } } diff --git a/docs/superpowers/plans/2026-06-01-split-large-files-next.md b/docs/superpowers/plans/2026-06-01-split-large-files-next.md new file mode 100644 index 0000000..b72e76f --- /dev/null +++ b/docs/superpowers/plans/2026-06-01-split-large-files-next.md @@ -0,0 +1,89 @@ +# 2026-06-01 大文件继续拆分计划(续) + +## 当前状态(更新于本轮) + +- 已完成: + - `gui/web_gui.py` 路由壳化,主体路由下沉到 `gui/web_gui_pkg/routes.py` + - `douyin/core/fudai_modules/run_once_basic_helpers.py` 中预约检查与状态写盘逻辑下沉到 `run_once_basic_reservation.py` + - `douyin/core/douyin_fudai.py` 中 `_handle_in_fudai_detail` / `_handle_live_room_has_or_not_fudai` 下沉到 `fudai_modules/live_room_handlers.py` + - `douyin/core/underlying_operations.py` 中 `get_screenshot` 下沉到 `underlying_operations_pkg/screenshot_pipeline.py` + - `douyin/fudai/douyin_fudai_core_legacy.py` 壳化完成,核心实现转移到 `douyin/fudai/douyin_fudai_contain_impl.py` + - `douyin/fudai/douyin_fudai_contain_impl.py` 内部 helper 下沉到 `douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py`(轻重 OCR 分流判定、参与人数提取等) + - `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的按钮状态判定与回写逻辑下沉到 `douyin/fudai/douyin_fudai_core_pkg/button_state.py` + - `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的并行任务提交与结果收集骨架下沉到 `douyin/fudai/douyin_fudai_core_pkg/parallel_exec.py` + - `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的任务列表观看任务检测分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/watch_task.py` + - `douyin/fudai/douyin_fudai_contain_impl.py` 原始内容/清理后内容观看任务检测分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/watch_task.py` + - `douyin/fudai/douyin_fudai_contain_impl.py` 倒计时数字提取与校验分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/countdown_parse.py` + - `douyin/core/douyin_fudai.py` 的 `_capture_roi_screenshot` 与 `_match_icon_template` 下沉到 `douyin/handlers/douyin_screenshot_handler.py` + - `douyin/core/douyin_fudai.py` 的 `fudai_choujiang` 运行循环(定时/无限模式 + 结束日志)下沉到 `douyin/core/fudai_modules/fudai_run_loop.py` + - `douyin/core/douyin_fudai.py` 的 `run_once_basic` 前置段(启动日志/养号触发/标题记录)下沉到 `run_once_basic_helpers.run_once_basic_prelude` + - `douyin/core/douyin_fudai.py` 的 `run_once_basic` 预约后阶段处理段下沉到 `run_once_basic_helpers.run_once_basic_post_reservation` + - `douyin/core/underlying_operations.py` 的输入法/文本输入链路下沉到 `douyin/core/underlying_operations_pkg/text_input.py`(`input_text` / `paste_text_at` / ADBKeyboard 广播与 IME 切换等),主类保留薄转发 + - `douyin/core/fudai_modules/run_once_basic_helpers.py` 的阶段链路下沉到 `douyin/core/fudai_modules/run_once_basic_stage.py`(`screenshot_and_diagnose` / `handle_desktop_recovery` / `handle_high_value_room_revisit`),主 helper 保留薄转发 + - `douyin/core/fudai_modules/run_once_basic_helpers.py` 的粉丝团处理段下沉到 `douyin/core/fudai_modules/run_once_basic_fansclub.py`(`_handle_fansclub_join`),主 helper 保留薄转发 + - `douyin/core/fudai_modules/handle_detail_helpers.py` 的筛选与高价值预约段下沉到 `douyin/core/fudai_modules/handle_detail_filter.py`(`_check_skip_and_handle` / `_try_high_value_reservation` / `_handle_skip_filter` / `_fallback_swipe_up`),主 helper 保留薄转发 + - `douyin/core/fudai_modules/handle_detail_helpers.py` 的首开详情分支下沉到 `douyin/core/fudai_modules/handle_detail_first_open.py`(`handle_first_open_branch` / `_validate_first_open_detail`),主 helper 保留薄转发 + - `douyin/core/fudai_modules/handle_detail_helpers.py` 的二次打开与预约完成收尾下沉到 `douyin/core/fudai_modules/handle_detail_second_open.py`(`handle_second_open_branch` / `_handle_reservation_completion`),主 helper 保留薄转发 + - `douyin/stage/douyin_stage.py` 的步骤0并行像素检测下沉到 `douyin/stage/douyin_stage_handler_pkg/pixel_parallel.py`(`run_parallel_pixel_detection`),主诊断流程保留汇总与分支调度 + - `douyin/stage/douyin_stage.py` 的弹窗OCR兜底与最终阶段收尾下沉到 `douyin/stage/douyin_stage_handler_pkg/finalize_stage.py`(`finalize_stage_after_pixel`),主诊断流程保留前序分支与统一调用 + - `douyin/stage/douyin_stage.py` 的“邀你抢红包”OCR检测段下沉到 `douyin/stage/douyin_stage_handler_pkg/ocr_redpacket.py`(`detect_invite_redpacket_via_ocr`),主诊断流程保留统一调用与返回分发 + - `douyin/core/underlying_operations.py` 的 UIAutomator 交互段下沉到 `douyin/core/underlying_operations_pkg/ui_automator.py`(`_uiautomator_dump` / `tap_by_text` / `tap_close_icon`),主类保留薄转发 + - `douyin/core/underlying_operations.py` 的前台包检测与应用拉起链路下沉到 `douyin/core/underlying_operations_pkg/foreground.py`(`get_top_package` / `launch_package` / `is_douyin_foreground`),主类保留薄转发 + - `gui/web_gui.py` 的 ProcRunner 状态读取与测试入口段下沉到 `gui/web_gui_pkg/proc_runner_ops.py`(`get_reservations` / `get_high_value_rooms` / `send_back_key` / `start_test_yanghao` / `start_test_comment`),主类保留薄转发 + - `gui/web_gui.py` 的 ProcRunner 统计聚合段下沉到 `gui/web_gui_pkg/proc_runner_stats.py`(`get_stats`),主类保留薄转发 + - `webui/css/components.css` 的 Overlay/Toast 样式拆分到 `webui/css/components_overlays.css` 与 `webui/css/components_toast.css`,并在 `webui/index.html` 追加模块化样式引用,主 `components.css` 保留其余组件样式 + - `webui/index.html` 的监控/预约/日志面板与页脚区块下沉到 `webui/js/panel_templates.js`,页面改为挂载点注入(保留原 DOM id/class),主 `index.html` 继续瘦身 + - `webui/index.html` 的头部命令条与状态概览区块下沉到 `webui/js/top_templates.js`,页面改为挂载点注入(保留原 DOM id/class),主 `index.html` 继续瘦身 + - `douyin/reservation/reservation_logic/attend_window.py` 的“已参与过滤/无效时间过滤/动态提前量计算/目标快照日志”下沉到 `douyin/reservation/reservation_logic/attend_window_helpers.py`,主流程保留编排与分支顺序 + - `webui/js/runtime_actions.js` 的设备动作与测试动作下沉到 `webui/js/runtime_device_actions.js`(`selectedDeviceId` / `postDeviceAction` / `wifi*` / `forceStopRun` / `testYanghao` / `testComment`),`index.html` 已补充脚本加载顺序 + - `douyin/stage/douyin_stage_handler_pkg/check_live.py` 的分数选择策略与结果日志汇总下沉到 `douyin/stage/douyin_stage_handler_pkg/check_live_score.py`,主流程保留模板匹配编排 + - `gui/components/config_io.py` 的文本域读写与 debug/logging 配置映射下沉到 `gui/components/config_io_helpers.py`,主流程保留编排与配置字段回写顺序 + - `douyin/handlers/screenshot_manager/save_image.py` 的调试保存开关读取、保存重试机制、标注绘制逻辑下沉到 `douyin/handlers/screenshot_manager/save_image_helpers.py`(`is_debug_captures_enabled` / `save_image_with_retry` / `annotate_debug_image`),主入口保留编排与异常处理 + - `tools/coords/region_selector.py` 的菜单构建、快捷键绑定、画布事件绑定与拖放注册下沉到 `tools/coords/region_selector_ui.py`(`setup_menu` / `bind_canvas_events` / `setup_dnd`),主类保留业务状态与事件处理 + - `douyin/fudai/douyin_fudai_contain_impl.py` 的后处理聚合逻辑下沉到 `douyin/fudai/douyin_fudai_core_pkg/contain_postprocess.py`(进房耗时日志、价值OCR校验、标题写回、房间映射落盘),主流程保留编排与返回值 + - `gui/gui_core_pkg/stats_log_parser.py` 的重复正则提取与数值转换下沉到 `gui/gui_core_pkg/stats_log_parser_helpers.py`(`search_group` / `search_group_any` / `parse_int_value` / `parse_float_value` / `set_meta_*_if_match`),主解析流程保留业务事件判定 + - `douyin/reservation/reservation_logic/attend_window.py` 的尾段日志逻辑下沉到 `attend_window_helpers.py`(`log_back_failed_keep_queue` / `log_attend_window_result`),主流程保留回退决策与状态编排 + - `webui/index.html` 的 `keywords + debug` 配置面板下沉到 `webui/js/config_panel_templates.js`,页面改为 `configPanelTemplatesMount` 挂载点注入并补充脚本加载顺序(保留原 id/data-key,行为兼容) + - `tools/coords/simple_region_selector.py` 的菜单/快捷键/画布绑定下沉到 `tools/coords/simple_region_selector_ui.py`(`setup_menu_and_shortcuts` / `bind_canvas_events`),主类保留图像处理与多边形分析流程 +- 当前 Top 大文件(源码): + 1. `webui/index.html` 53.7KB(本轮从 71.0KB 降到 53.7KB,已低于 65KB 目标) + 2. `douyin/other/douyin_yanghao.py` 29.8KB + 3. `webui/css/components.css` 29.7KB + 4. `douyin/fudai/douyin_fudai_finder_pkg/detector.py` 29.4KB + 5. `douyin/core/douyin_fudai.py` 29.0KB + 6. `douyin/reservation/reservation_logic/attend_window.py` 28.8KB(已从 35.5KB 降到 28.8KB) + 7. `gui/web_gui_pkg/stats_log_parser.py` 28.7KB + 8. `douyin/stage/douyin_stage_handler_pkg/check_live.py` 28.6KB + 9. `gui/gui_core_pkg/stats_log_parser.py` 28.4KB(已从 30.3KB 降到 28.4KB) + 10. `webui/js/ui_init.js` 27.8KB + 11. `webui/js/runtime_actions.js` 27.1KB + +## 下一轮拆分顺序(建议) + +1. `douyin/fudai/douyin_fudai_finder_pkg/detector.py` + - 抽离模板匹配与阈值/回退逻辑,降低单函数复杂度。 +2. `gui/web_gui_pkg/stats_log_parser.py` + - 参照 gui_core 侧 helper 化,统一正则提取与类型转换入口。 +3. `douyin/reservation/reservation_logic/attend_window.py` + - 继续抽离中段“锁定期判断 + 同预约分支”中的日志与状态更新子流程。 +4. `douyin/other/douyin_yanghao.py` + - 抽离坐标/概率配置读取与动作执行分发,降低主流程长度与分支复杂度。 +5. `webui/js/ui_init.js` + - 分离面板切换、搜索过滤与快捷键初始化,进一步降低单文件复杂度。 + +## 验证口径 + +- 每次拆分后必须执行: + - `python -m py_compile <改动的py文件>` + - 如本机 `pytest` 可用,再跑相关最小测试集 +- 由于当前 shell 环境缺少 pytest,测试日志需保留: + - `logs/pytest_*.log` + +## 硬编码治理并行策略 + +- 优先治理“环境迁移敏感”的硬编码: + - host/port(已收敛到 `net_config`,继续排查其它入口) + - 本地路径、固定命令、默认端口 +- 处理方式: + - 新增集中配置读取函数 + - 原调用点只保留薄封装,避免每处单独拼环境变量 diff --git a/docs/迁移部署指南.md b/docs/迁移部署指南.md index 85dc04a..91f1765 100644 --- a/docs/迁移部署指南.md +++ b/docs/迁移部署指南.md @@ -1,201 +1,97 @@ -# 迁移部署指南(新电脑 + 手机端) +# 迁移部署指南(简版) -本文用于把项目迁移到另一台 Windows 电脑,并完成手机端可运行配置。 +## 1. 电脑端(最少步骤) -## 1. 适用范围 - -- 项目根目录:`douyin_guaji-main` -- 目标系统:Windows 10/11 -- Python:3.10 ~ 3.12(推荐 3.10) -- 手机:Android 5.0+(无需 Root) - -## 2. 迁移总览 - -1. 新电脑安装 Python、ADB 并拉取项目代码 -2. 创建虚拟环境并安装依赖 -3. (可选)从旧电脑迁移运行配置与状态文件 -4. 手机上开启开发者选项/USB 调试并完成 ADB 授权 -5. 首次启动 GUI 或 CLI 做连通性验证 - ---- - -## 3. 新电脑部署步骤 - -### 3.1 安装基础软件 - -1. 安装 Python(勾选 `Add Python to PATH`) -2. 安装 ADB(Android platform-tools),确保命令行可执行: +1. 安装 `Python 3.10+` +2. 安装 `ADB`(platform-tools)并加入 PATH +3. 拉代码: ```powershell -python --version -adb version -``` - -### 3.2 获取项目 - -```powershell -git clone <你的仓库地址> +git clone https://git.simgreek.com/simgreek/douyi_guaji_main.git cd douyin_guaji-main ``` -### 3.3 创建虚拟环境并安装依赖 +4. 一键部署依赖: ```powershell -python -m venv .venv -.venv\Scripts\Activate.ps1 -pip install -r requirements.txt +bootstrap_deps.bat ``` -若网络较慢: +可选: ```powershell -pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple -``` - -### 3.4 依赖自检 - -```powershell -python tools/diagnostics/check_dependencies.py +bootstrap_deps.bat --minimal +bootstrap_deps.bat --index-url https://pypi.tuna.tsinghua.edu.cn/simple ``` --- -## 4. 从旧电脑迁移配置(推荐) +## 2. 手机端必须操作 -> 这一步用于保留你原来的筛选参数、高价值房间记录、预约状态。 +### 2.1 开启开发者选项 -请从旧电脑复制以下文件到新电脑同路径: +1. `设置 -> 关于手机` +2. 连续点击“版本号”7次 -1. `config/config.json`(主配置,最重要) -2. `state/high_value_rooms.json`(高价值房间回访记录,可选) -3. `douyin/core/state/reservations.json`(预约队列,可选) +### 2.2 开启 USB 调试 -可选迁移(用于调试可视化): - -1. `douyin/core/state/room_pos_map.json` - -说明: - -- 这些文件多数被 `.gitignore` 忽略,不会随 `git clone` 自动带过来。 -- 如不迁移,项目会按默认配置运行。 - ---- - -## 5. 手机端必须操作 - -### 5.1 开启开发者模式与 USB 调试 - -1. 手机 `设置 -> 关于手机`,连续点击“版本号”7次 -2. 进入 `开发者选项`,打开: +1. `设置 -> 开发者选项` +2. 开启: - `USB 调试` - - (部分机型)`USB 安装` / `USB 调试(安全设置)` + - (部分机型)`USB 调试(安全设置)` / `USB 安装` -### 5.2 首次 USB 连接授权 +### 2.3 首次授权 -1. USB 连接电脑,USB 模式选“文件传输/MTP” -2. 手机弹出“允许 USB 调试”时,点“允许” +1. 手机 USB 连接电脑,模式选“文件传输/MTP” +2. 手机弹出“允许 USB 调试”时点击“允许” 3. 电脑执行: ```powershell adb devices ``` -期望看到: - -```text - device -``` - -若是 `unauthorized`,说明手机还未确认授权。 - -### 5.3 安装/确认抖音 APP - -- 手机上安装并登录要运行的抖音账号 -- 手动打开一次抖音到首页,确保账号状态正常 - -### 5.4(可选)安装 ADBKeyboard(提升文本输入兼容性) - -项目内置 APK:`tools/adb/ADBKeyboard.apk` - -```powershell -adb -s install -r tools/adb/ADBKeyboard.apk -adb -s shell ime list -s -``` - -若列表里存在 `com.android.adbkeyboard/.AdbIME`,可切换: - -```powershell -adb -s shell ime enable com.android.adbkeyboard/.AdbIME -adb -s shell ime set com.android.adbkeyboard/.AdbIME -``` +看到 ` device` 即成功。 +如果是 `unauthorized`,重新插线并重新允许授权。 --- -## 6. 首次运行验收(新电脑) +## 3. 手机底部导航栏怎么调出(详细) -### 6.1 GUI 启动(推荐) +目标:显示底部“返回/主页/多任务”按钮。 -```powershell -python bin/gui_app.py -``` +### 方法 A(通用) -检查点: +1. 打开设置 +2. 搜索:`System navigation` 或 `Navigation mode` +3. 选择:`3-button navigation`(三键导航) -1. 设备下拉里能看到手机 -2. 点击截图可成功生成实时截图 -3. 点击开始运行后日志持续刷新,无异常退出 +常见路径: -### 6.2 Web GUI 启动(可选) +- `Settings -> System -> Gestures -> System navigation` +- 或 `Settings -> System -> Navigation mode` -```powershell -python bin/webgui_launcher.py -``` +### 方法 B(品牌常见路径) -浏览器访问:`http://127.0.0.1:8000/` +- Samsung:`设置 -> 显示 -> 导航条 -> 按钮` +- Xiaomi/Redmi/POCO:`设置 -> 桌面 -> 系统导航方式 -> 经典导航键` +- OPPO/OnePlus:`设置 -> 系统设置 -> 系统导航方式 -> 虚拟按键` +- vivo/iQOO:`设置 -> 系统导航 -> 导航键` +- Huawei/Honor:`设置 -> 系统和更新 -> 系统导航方式 -> 屏幕内三键导航` -### 6.3 CLI 冒烟(可选) +### 还是没显示时 -```powershell -python bin/run_cli.py --device-id --wait-minutes 1 --needswitch -``` +1. 关闭“全面屏手势/全屏手势” +2. 退出当前全屏 App 后再切换 +3. 切换后重启手机一次 + +临时调出:从屏幕最底部向上轻划一次(很多机型会临时显示系统导航控件)。 --- -## 7. WiFi ADB(可选) +## 4. 可选迁移配置 -首次切换 WiFi ADB 需先 USB 连接。可用两种方式: - -1. 桌面 GUI 里的 `WiFi ADB` 按钮(推荐) -2. 命令行脚本: - -```powershell -python tools/adb/auto_connect_wifi_adb.py --device -``` - -若连接异常,先重启 ADB: - -```powershell -adb kill-server -adb start-server -adb devices -``` - ---- - -## 8. 常见问题速查 - -1. `adb devices` 空列表:检查数据线、USB模式、USB调试是否开启 -2. 设备状态 `unauthorized`:看手机弹窗并重新授权 -3. 设备状态 `offline`:重插 USB + `adb kill-server && adb start-server` -4. 依赖安装失败(尤其 paddle):优先用清华源重试 -5. 启动后无日志/秒退:先跑 `python tools/diagnostics/check_dependencies.py` - ---- - -## 9. 交付给他人的最小清单 - -1. 项目代码目录 `douyin_guaji-main` -2. 迁移说明文档(本文) -3. (可选)你的 `config/config.json` -4. 对方手机按第 5 节完成设置后即可跑通 +如果要保留你原来的策略和状态,再复制这些文件: +1. `config/config.json` +2. `state/high_value_rooms.json` +3. `douyin/core/state/reservations.json` diff --git a/douyin/core/douyin_flow_control_pkg/find_open.py b/douyin/core/douyin_flow_control_pkg/find_open.py index 47b3968..c45f496 100644 --- a/douyin/core/douyin_flow_control_pkg/find_open.py +++ b/douyin/core/douyin_flow_control_pkg/find_open.py @@ -14,6 +14,19 @@ from douyin.core import path_config from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot +def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None: + try: + payload = { + "flag": str(flag or ""), + "status": str(status or ""), + "run_id": str(getattr(analyser, "_run_id", "") or ""), + } + payload.update(extra or {}) + analyser._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload) + except Exception: + pass + + def find_and_open_fudai_detail( analyser: Any, stage: Any = "", @@ -21,6 +34,15 @@ def find_and_open_fudai_detail( func_start_time: float | None = None, ): """主实现:检测福袋图标并点击打开详情页。""" + _emit_flow_flag( + analyser, + "fudai_find_open", + "start", + room_pos=int(getattr(analyser, "room_pos", 0) or 0), + max_wait_seconds=float( + getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0 + ), + ) if func_start_time is None: func_start_time = time.time() @@ -247,6 +269,13 @@ def find_and_open_fudai_detail( except Exception: # 容错:如果处理计数或配置读取出错,忽略并继续返回 False pass + _emit_flow_flag( + analyser, + "fudai_find_open", + "not_found", + max_wait_seconds=max_wait_seconds, + elapsed_seconds=round(time.time() - start_time, 2), + ) return False # 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度) @@ -440,6 +469,13 @@ def find_and_open_fudai_detail( ) except Exception: pass + _emit_flow_flag( + analyser, + "fudai_find_open", + "open_success", + stage=stage, + reason=str(reason or ""), + ) return True else: try: @@ -494,6 +530,13 @@ def find_and_open_fudai_detail( ) except Exception: pass + _emit_flow_flag( + analyser, + "fudai_find_open", + "open_misclick", + stage=stage, + reason=str(reason or ""), + ) return False except Exception as e: try: @@ -510,6 +553,12 @@ def find_and_open_fudai_detail( "find_and_open_fudai_detail完成(阶段检测异常)", elapsed_seconds=round(elapsed, 2), ) + _emit_flow_flag( + analyser, + "fudai_find_open", + "open_stage_exception", + error=str(e), + ) return False except Exception: try: @@ -532,6 +581,7 @@ def find_and_open_fudai_detail( "find_and_open_fudai_detail完成(兜底失败)", elapsed_seconds=round(elapsed, 2), ) + _emit_flow_flag(analyser, "fudai_find_open", "fallback_failed") return False return False diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 1f14bc4..b6fb101 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -24,9 +24,7 @@ from douyin.core.underlying_operations import underlying_operations from douyin.stage import douyin_stage from douyin.detection import douyin_detection -from douyin.fudai import douyin_fudai_detail from douyin.fudai import douyin_fudai_core -from douyin.core import douyin_flow_control # pylint: disable=redefined-outer-name from douyin.other import douyin_live_room from douyin.reservation import ( douyin_reservation_logic, @@ -461,122 +459,11 @@ class fudai_analyse: # 基础循环:在限定时间内反复执行单轮逻辑 # 如果 wait_minutes <= 0,则无限循环运行 + from douyin.core.fudai_modules import fudai_run_loop as _run_loop if wait_minutes and wait_minutes > 0: - end_ts = time.time() + int(wait_minutes) * 60 - while time.time() < end_ts: - try: - self.run_once_basic() - except Exception as exc: - # 捕获异常,记录日志,但继续循环 - try: - self._log_kv( - "循环", - "run_once_basic 异常", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - # 异常后稍作延迟再继续 - try: - self.operation.delay(2.0) - except Exception: - time.sleep(2.0) - continue - - # 为避免过于频繁截图,增加少量间隔 - try: - self.operation.delay(1.0) - except Exception: - time.sleep(1.0) - - # 记录运行结束(定时模式) - try: - end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - - try: - from douyin.core import path_config as _pc - actions_log_path = _pc.get_actions_log_path() - except Exception: - actions_log_path = os.path.normpath( - os.path.join( - os.path.dirname(__file__), "..", "..", "logs", "actions.log" - ) - ) - log_dir = os.path.dirname(actions_log_path) - if log_dir: - os.makedirs(log_dir, exist_ok=True) - with open( - actions_log_path, "a", encoding="utf-8-sig", errors="replace" - ) as f: - f.write("=" * 80 + "\n") - f.write(f"{end_time} - [GUI] - [运行] 程序运行结束(时间到)\n") - f.flush() - except Exception: - pass - + _run_loop.run_timed_loop(self, int(wait_minutes)) else: - # 无限循环模式(wait_minutes <= 0) - self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)") - while True: - try: - self.run_once_basic() - except KeyboardInterrupt: - # 允许 Ctrl+C 退出 - self._log_kv("循环", "收到中断信号,退出循环") - # 记录运行结束 - try: - end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - - try: - from douyin.core import path_config as _pc - actions_log_path = _pc.get_actions_log_path() - except Exception: - actions_log_path = os.path.normpath( - os.path.join( - os.path.dirname(__file__), "..", "..", "logs", "actions.log" - ) - ) - log_dir = os.path.dirname(actions_log_path) - if log_dir: - os.makedirs(log_dir, exist_ok=True) - with open( - actions_log_path, - "a", - encoding="utf-8-sig", - errors="replace", - ) as f: - f.write("=" * 80 + "\n") - f.write( - f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n" - ) - f.flush() - except Exception: - pass - raise - except Exception as exc: - # 捕获异常,记录日志,但继续循环 - try: - self._log_kv( - "循环", - "run_once_basic 异常", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - # 异常后稍作延迟再继续 - try: - self.operation.delay(2.0) - except Exception: - time.sleep(2.0) - continue - - # 为避免过于频繁截图,增加少量间隔 - try: - self.operation.delay(1.0) - except Exception: - time.sleep(1.0) + _run_loop.run_infinite_loop(self) # ========== 阶段诊断 ========== def _diagnose_stage_from_current_screen( @@ -639,285 +526,18 @@ class fudai_analyse: def _capture_roi_screenshot( self, label: str, sx: int, sy: int, size: int, screenshot_path: str = None ) -> str: - """捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。 - - 返回 ROI 图片路径(绝对路径),失败返回空字符串。 - """ - try: - from douyin.core import path_config - - # use module-level `Image` - - # 确保有最新全图 - if screenshot_path is None: - try: - self.operation.get_screenshot(self.device_id, use_service=False) - except Exception: - pass - pic_path = path_config.get_screenshot_path() - else: - pic_path = screenshot_path - if not os.path.exists(pic_path): - return "" - - # 计算裁剪框(保证正方形,size 基于像素) - half = int(size // 2) - left = int(max(0, sx - half)) - top = int(max(0, sy - half)) - right = int(sx + half) - bottom = int(sy + half) - - # 以原子方式读取文件内容再由 PIL 解析,避免因文件替换/锁定导致的半写入问题 - import io - from PIL import UnidentifiedImageError # type: ignore[import] - - data = None - # 增强读取:多次尝试并在每次读到字节后用 PIL 验证,避免半写入/损坏 PNG 导致解析异常 - for attempt in range(6): - try: - try: - # 主动请求最新截图以尽量获得完整文件 - self.operation.get_screenshot(self.device_id, use_service=False) - except Exception: - pass - - if not os.path.exists(pic_path): - time.sleep(0.08) - continue - sz = os.path.getsize(pic_path) - if sz < 1024: - time.sleep(0.08) - continue - with open(pic_path, "rb") as f: - data = f.read() - if not data or not data.startswith(b"\x89PNG"): - data = None - time.sleep(0.08) - continue - # quick tail check - if b"IEND" not in data[-512:]: - data = None - time.sleep(0.08) - continue - - # 尝试由 PIL 快速验证(不加载像素,仅检查文件完整性) - try: - img_test = Image.open(io.BytesIO(data)) - img_test.verify() - except Exception: - data = None - time.sleep(0.08) - continue - - # 通过基本校验,退出重试循环 - break - except Exception: - data = None - time.sleep(0.08) - - if not data: - return "" - - try: - img = Image.open(io.BytesIO(data)) - img.load() - except UnidentifiedImageError: - return "" - except Exception: - # 如果首次解析仍然失败,尝试再获取一次截图并重试一次 - try: - try: - self.operation.get_screenshot(self.device_id, use_service=False) - except Exception: - pass - with open(pic_path, "rb") as f: - data2 = f.read() - if ( - data2 - and data2.startswith(b"\x89PNG") - and b"IEND" in data2[-512:] - ): - try: - img = Image.open(io.BytesIO(data2)) - img.load() - except Exception: - return "" - else: - return "" - except Exception: - return "" - w, h = img.size - # 修正边界 - left = max(0, min(left, w - 1)) - top = max(0, min(top, h - 1)) - right = max(1, min(right, w)) - bottom = max(1, min(bottom, h)) - - roi = img.crop((left, top, right, bottom)) - img.close() - # 保存到 pic 目录,使用 label 区分 - out_dir = path_config.get_pic_dir() - os.makedirs(out_dir, exist_ok=True) - fname = ( - f"roi_{label}_{getattr(self, '_run_id', 'run')}_{int(time.time())}.png" - ) - out_path = os.path.join(out_dir, fname) - roi.save(out_path) - return out_path - except Exception: - try: - self._log_kv( - "截图", - "_capture_roi_screenshot 失败", - label=label, - sx=sx, - sy=sy, - size=size, - ) - except Exception: - pass - return "" + """捕获以 (sx,sy) 为中心的 ROI 截图。""" + return douyin_screenshot_handler.ScreenshotHandler.capture_roi_screenshot( + self, label, sx, sy, size, screenshot_path + ) def _match_icon_template( self, roi_path: str, template_path: str, threshold: float | None = None ) -> Tuple[bool, float]: - """对比 ROI 与模板,返回 (detected: bool, score: float)。 - - 使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。 - 如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。 - 返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。 - """ - try: - if not roi_path or not os.path.exists(roi_path): - return False, 0.0 - if not template_path or not os.path.exists(template_path): - return False, 0.0 - - # use module-level `Image` and `np` imports - - _roi_raw = Image.open(roi_path) - _tpl_raw = Image.open(template_path) - try: - roi_img = _roi_raw.convert("RGB") - tpl_img = _tpl_raw.convert("RGB") - finally: - _roi_raw.close() - _tpl_raw.close() - - rw, rh = roi_img.size - tw, th = tpl_img.size - # 若模板比 ROI 大,等比缩小模板 - if tw > rw or th > rh: - scale = min(rw / tw, rh / th, 1.0) - new_w = max(1, int(tw * scale)) - new_h = max(1, int(th * scale)) - tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS) - tw, th = tpl_img.size - - # 转为灰度数组 - roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32) - tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32) - - # 若模板尺寸等于 ROI,则直接计算相关系数 - if ( - roi_gray.shape[0] == tpl_gray.shape[0] - and roi_gray.shape[1] == tpl_gray.shape[1] - ): - A = roi_gray.flatten() - B = tpl_gray.flatten() - else: - # 若模板小于 ROI,则优先取 ROI 中心区域与模板尺寸一致的裁剪进行比对(更稳健), - # 如果中心裁剪分数很低再退回到滑动搜索(成本较高) - ih, iw = roi_gray.shape - th, tw = tpl_gray.shape - # 计算中心裁剪窗口 - if ih >= th and iw >= tw: - cy = ih // 2 - th // 2 - cx = iw // 2 - tw // 2 - cy = max(0, min(cy, ih - th)) - cx = max(0, min(cx, iw - tw)) - window = roi_gray[cy : cy + th, cx : cx + tw] - a = window.flatten() - b = tpl_gray.flatten() - a = a - a.mean() - b = b - b.mean() - denom = np.linalg.norm(a) * np.linalg.norm(b) - if denom > 1e-6: - score = float(np.dot(a, b) / denom) - else: - score = -1.0 - # 若中心裁剪得分足够好则直接返回 - if score >= 0.55: - used_thr = ( - float(threshold) - if threshold is not None - else float( - getattr(self, "yanghao_icon_match_threshold", 0.70) - or 0.70 - ) - ) - detected = score >= used_thr - return bool(detected), float(score) - - # 退回到滑动搜索(简易版),保留原有步长策略 - ih, iw = roi_gray.shape - th, tw = tpl_gray.shape - best = -1.0 - step_y = max(1, th // 6) - step_x = max(1, tw // 6) - for y in range(0, ih - th + 1, step_y): - for x in range(0, iw - tw + 1, step_x): - window = roi_gray[y : y + th, x : x + tw] - a = window.flatten() - b = tpl_gray.flatten() - a = a - a.mean() - b = b - b.mean() - denom = np.linalg.norm(a) * np.linalg.norm(b) - if denom <= 1e-6: - continue - score = float(np.dot(a, b) / denom) - if score > best: - best = score - if best < -0.5: - return False, 0.0 - score = float(best) - used_thr = ( - float(threshold) - if threshold is not None - else float( - getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70 - ) - ) - detected = score >= used_thr - return bool(detected), float(score) - - # 同尺寸直接计算相关系数 - A = roi_gray.flatten() - B = tpl_gray.flatten() - A = A - A.mean() - B = B - B.mean() - denom = np.linalg.norm(A) * np.linalg.norm(B) - if denom <= 1e-6: - return False, 0.0 - score = float(np.dot(A, B) / denom) - used_thr = ( - float(threshold) - if threshold is not None - else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70) - ) - detected = score >= used_thr - return bool(detected), float(score) - except Exception: - try: - self._log_kv( - "检测", - "_match_icon_template 异常", - roi_path=roi_path, - template_path=template_path, - ) - except Exception: - pass - return False, 0.0 + """对比 ROI 与模板,返回 (detected, score)。""" + return douyin_screenshot_handler.ScreenshotHandler.match_icon_template( + self, roi_path, template_path, threshold + ) def _check_in_live_room_by_icon( self, @@ -971,31 +591,10 @@ class fudai_analyse: # use module-level `douyin_reservation_logic` imported at top start_time = time.time() - self._log_kv("流程", "run_once_basic开始", start_timestamp=start_time) - # 在主循环开始时检查是否需要定时触发推荐页养号 - try: - self._maybe_run_yanghao_during_run() - except Exception: - pass - - # 尝试记录当前直播间的标题与位置,确保所有直播间(不限福袋)都被采集到运行时映射表 - # 但如果刚刚切换直播间,避免重复记录(切换前已记录) - try: - just_switched = getattr(self, "_just_switched_room", False) - if not just_switched: - self._record_room_title_and_pos() - else: - self._log_kv( - "预约", - "[预约] 刚刚切换直播间,跳过重复记录标题", - reason="avoid_duplicate_after_switch", - ) - except Exception: - pass - # 直接参与标志已移除,相关旧逻辑已清理,继续按正常流程执行 # 0. 如果正在等待开奖:不在此期间检查并抢占其他预约,避免放弃当前正在参加的直播间 from douyin.core.fudai_modules import run_once_basic_helpers as _ronce_helpers + _ronce_helpers.run_once_basic_prelude(self, start_time) if _ronce_helpers.handle_waiting_for_lottery_result(self, start_time): return @@ -1004,40 +603,9 @@ class fudai_analyse: return # 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间" - reservation_check_start = time.time() - if _ronce_helpers.handle_reservation_check(self, start_time): + if _ronce_helpers.handle_reservation_pipeline(self, start_time): return - - # 检查是否刚刚记录了预约,如果是,强制切换直播间,避免在同一直播间循环 - if _ronce_helpers.handle_just_recorded_reservation(self, start_time): - return - - # 预约检查耗时记录 - reservation_elapsed = time.time() - reservation_check_start - self._log_kv("预约", f"预约检查完成,耗时: {reservation_elapsed:.3f}s") - - # 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后) - if _ronce_helpers.handle_skip_stage_diagnosis(self, start_time): - return - - # 1. 截图 + 阶段诊断 - diag = _ronce_helpers.screenshot_and_diagnose(self, start_time) - if diag is None: - return - stage, seen = diag - - # 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复 - if _ronce_helpers.handle_desktop_recovery(self): - return - - # 2. 诊断后分支(弹窗检测已合并到阶段诊断中) - - # 2.0. 高价值房间重访检查(在处理其他状态之前) - if _ronce_helpers.handle_high_value_room_revisit(self, start_time): - return - - # 处理弹窗 / 详情 / 直播间 / 推荐页 / 开奖结果 / 直播结束 阶段分发 - _ronce_helpers.dispatch_stage_branch(self, stage, seen, start_time) + _ronce_helpers.run_once_basic_post_reservation(self, start_time) def _check_lottery_result_by_ocr(self) -> Optional[str]: """通过OCR识别开奖结果按钮区域,返回识别到的文本类型。""" @@ -1117,235 +685,10 @@ class fudai_analyse: # pylint: disable=too-many-nested-blocks def _handle_in_fudai_detail(self) -> None: """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。""" - from douyin.core.fudai_modules import handle_detail_helpers as _hd_helpers - start_time = time.time() - _hd_helpers.log_entry_flags(self) - # 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋 - - # 检查连续参与失败次数,避免卡死 - if _hd_helpers.handle_consecutive_failures_check(self): - return - - # 步骤1:检查是否是第二次打开福袋详情 - step1_start = time.time() - is_second_open = getattr(self, "_fudai_detail_first_read", False) - if is_second_open: - # 第二次打开分支已抽到 handle_second_open_branch - if _hd_helpers.handle_second_open_branch(self, start_time, step1_start): - return - # 异常或兜底重读时 fall through 到正常流程 - else: - # 步骤2 + 步骤3:第一次打开分支已抽到 handle_first_open_branch - if _hd_helpers.handle_first_open_branch(self, start_time): - return - - # 检查是否是优惠券弹窗、观看任务或识别错误:如果检测到,应该直接跳过,不继续处理 - if _hd_helpers.check_last_status_branch(self, start_time): - return - - # 重新取 detail(first-open / second-open 可能已 cache 到 self._last_fudai_detail_tuple) - detail = getattr(self, "_last_fudai_detail_tuple", None) - - # 如果成功读取,重置失败计数 - try: - self._fudai_detail_consecutive_failures = 0 - except Exception: - pass - - # 额外验证:使用验证函数检查数据合理性 - try: - if detail is None: - try: - self._log_kv("福袋详情", "详情数据为 None,跳过验证") - except Exception: - pass - else: - is_valid, reason = douyin_fudai_detail.validate_fudai_detail( - detail, self - ) - if not is_valid: - # 按钮状态为可操作时,即使验证失败也继续走参与流程 - _ACTIONABLE = { - "可以参与", "需要加入粉丝团", "需要评论", - "需要观看", "已参与", - } - _btn_st = getattr(self, "_fudai_button_status", None) - if _btn_st in _ACTIONABLE: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:验证失败但按钮可操作,继续参与", - validation_reason=reason, - button_status=_btn_st, - ) - except Exception: - pass - else: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:福袋详情数据验证失败,识别出错", - validation_reason=reason, - ) - except Exception: - pass - douyin_fudai_detail.close_fudai_detail(self) - - # 清除任务数量标志 - _hd_helpers._clear_task_count_flag(self) - - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_in_fudai_detail完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - - # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 - if _hd_helpers.check_invalid_detail_fallback(self, detail, start_time): - return - - # 步骤3 末尾准备:记录参与前状态、提取 future_ts、重置 _detail_closed_by_attend - attend_before_ts = _hd_helpers.prepare_for_attend(self, detail) - - # 步骤4:参与决策(已抽到 handle_detail_helpers.step4_make_join_decision) - # skip / skip_reason 已在 first-open 分支处理;fall-through 到此处时认为是"立即参与" - _hd_helpers.step4_make_join_decision( - self, detail, False, "", attend_before_ts, start_time - ) + from douyin.core.fudai_modules.live_room_handlers import handle_in_fudai_detail as _impl + return _impl(self) def _handle_live_room_has_or_not_fudai(self) -> None: - """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号".""" - start_time = time.time() - # 设置当前参与的福袋类型为高价值福袋(非预约) - self._current_attending_reservation_fudai = False - # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) - # 如果已验证过详情页但任务数为0,说明详情页正在加载,不应该再次查找福袋 - try: - already_verified = bool( - getattr(self, "_fudai_detail_verified", False) or False - ) - if already_verified: - try: - self._log_kv( - "流程", - "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋", - ) - except Exception: - pass - # 直接调用详情处理逻辑,不查找福袋 - self._handle_in_fudai_detail() - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_live_room_has_or_not_fudai完成(已验证详情页)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - - # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 - try: - now_ts = time.time() - focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0) - queue_full_waiting = bool( - getattr(self, "queue_full_waiting_at_earliest", False) or False - ) - - if focus_until > 0 and now_ts < focus_until and queue_full_waiting: - # 在锁定期内,且队列满等待中,检查时间窗口 - if self.reservations and len(self.reservations) > 0: - earliest = self.reservations[0] - try: - ft = float(earliest.get("future_ts") or 0.0) - if ft > 0: - join_ahead = float( - getattr( - self, "high_value_fudai_join_ahead_seconds", 100 - ) - or 120 - ) - time_window_start_ts = ft - join_ahead - - # 如果时间窗口未到,避免重复打开福袋详情 - if now_ts < time_window_start_ts: - try: - self._log_kv( - "预约", - "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", - focus_until=int(focus_until), - now_ts=int(now_ts), - time_window_start=int(time_window_start_ts), - remain_seconds=int( - time_window_start_ts - now_ts - ), - ) - except Exception: - pass - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", - elapsed_seconds=round(elapsed, 2), - ) - return - except Exception: - pass - except Exception: - pass - - room_pos_ref: List[int] = [0] - opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref) - if not opened: - # 无福袋,交给 flow_control 的“无福袋处理”逻辑 - # 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房) - try: - need_switch_config = bool(getattr(self, "needswitch", True)) - except Exception: - need_switch_config = True - - wait_times_ref = [0] - swipe_times_ref = [0] - reservation_focus_until_ts_ref = [0.0] - reset_to_list_after_reservations_ref = [False] - douyin_flow_control.handle_no_fudai_situation( - self, - x=0, - swipe_times=0, - wait_times_ref=wait_times_ref, - needswitch=need_switch_config, - reservation_focus_until_ts=0.0, - reservations=[], - room_pos=room_pos_ref[0], - post_switch_delay_s=1.5, - swipe_up_switch_callback=self.swipe_up_to_next_live, - swipe_down_back_callback=lambda: None, - sort_reservations_callback=lambda: None, - clear_reservations_callback=lambda: None, - write_state_callback=lambda: None, - back_to_list_callback=lambda: None, - into_list_callback=lambda: None, - reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, - reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, - swipe_times_ref=swipe_times_ref, - ) - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_live_room_has_or_not_fudai完成(无福袋)", - elapsed_seconds=round(elapsed, 2), - ) - return - - # 成功打开详情:调用同一套详情处理逻辑 - self._handle_in_fudai_detail() - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_live_room_has_or_not_fudai完成(成功打开详情)", - elapsed_seconds=round(elapsed, 2), - ) + """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定继续策略。""" + from douyin.core.fudai_modules.live_room_handlers import handle_live_room_has_or_not_fudai as _impl + return _impl(self) diff --git a/douyin/core/fudai_modules/fudai_run_loop.py b/douyin/core/fudai_modules/fudai_run_loop.py new file mode 100644 index 0000000..9b3e602 --- /dev/null +++ b/douyin/core/fudai_modules/fudai_run_loop.py @@ -0,0 +1,95 @@ +"""fudai_choujiang 运行循环辅助逻辑。""" + +from __future__ import annotations + +import os +import time +from datetime import datetime +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def _append_actions_end_log(reason_text: str) -> None: + """写入 actions.log 的运行结束记录。""" + try: + from douyin.core import path_config as _pc + + actions_log_path = _pc.get_actions_log_path() + except Exception: + actions_log_path = os.path.normpath( + os.path.join(os.path.dirname(__file__), "..", "..", "..", "logs", "actions.log") + ) + + try: + log_dir = os.path.dirname(actions_log_path) + if log_dir: + os.makedirs(log_dir, exist_ok=True) + end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + with open(actions_log_path, "a", encoding="utf-8-sig", errors="replace") as f: + f.write("=" * 80 + "\n") + f.write(f"{end_time} - [GUI] - [运行] 程序运行结束({reason_text})\n") + f.flush() + except Exception: + pass + + +def _run_once_with_recover(self: "fudai_analyse") -> bool: + """执行单轮 run_once_basic;返回 True 表示继续,False 表示中断退出。""" + try: + self.run_once_basic() + return True + except KeyboardInterrupt: + try: + self._log_kv("循环", "收到中断信号,退出循环") + except Exception: + pass + _append_actions_end_log("中断退出") + return False + except Exception as exc: + try: + self._log_kv( + "循环", + "run_once_basic 异常", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + try: + self.operation.delay(2.0) + except Exception: + time.sleep(2.0) + return True + + +def run_timed_loop(self: "fudai_analyse", wait_minutes: int) -> None: + """定时运行模式。""" + end_ts = time.time() + int(wait_minutes) * 60 + while time.time() < end_ts: + ok = _run_once_with_recover(self) + if not ok: + raise KeyboardInterrupt() + try: + self.operation.delay(1.0) + except Exception: + time.sleep(1.0) + _append_actions_end_log("时间到") + + +def run_infinite_loop(self: "fudai_analyse") -> None: + """无限循环运行模式。""" + try: + self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)") + except Exception: + pass + while True: + ok = _run_once_with_recover(self) + if not ok: + raise KeyboardInterrupt() + try: + self.operation.delay(1.0) + except Exception: + time.sleep(1.0) + diff --git a/douyin/core/fudai_modules/handle_detail_filter.py b/douyin/core/fudai_modules/handle_detail_filter.py new file mode 100644 index 0000000..276f2df --- /dev/null +++ b/douyin/core/fudai_modules/handle_detail_filter.py @@ -0,0 +1,184 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def check_skip_and_handle( + self: "fudai_analyse", detail, step2_start: float, start_time: float +) -> str: + """筛选检查 + 高价值预约 + 筛选不通过切房。""" + from douyin.fudai import douyin_fudai_core + + try: + skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(self, detail) + except Exception as e: + try: + self._log_kv("流程", "_handle_in_fudai_detail:筛选检查异常", error=str(e)) + except Exception: + pass + return "continue" + + if not skip: + return "continue" + + high_value_result = try_high_value_reservation(self, detail, skip, skip_reason, start_time) + if high_value_result == "return": + return "return" + if high_value_result == "continue": + return "continue" + return handle_skip_filter(self, skip_reason, start_time) + + +def try_high_value_reservation( + self: "fudai_analyse", detail, skip: bool, skip_reason: str, start_time: float +) -> str: + """高价值倒计时筛选处理。""" + import time + + from douyin.fudai import douyin_fudai_core + + try: + prize_value_yuan = 0.0 + countdown_tuple = None + if isinstance(detail, tuple) and len(detail) >= 6: + _, _, _, _, prize_value_yuan, countdown_tuple = detail + + high_value_enabled = bool(getattr(self, "high_value_fudai_enabled", False)) + high_value_threshold = float( + getattr(self, "high_value_fudai_threshold_yuan", 500.0) or 500.0 + ) + + is_high_value = ( + high_value_enabled + and prize_value_yuan > 0 + and prize_value_yuan >= high_value_threshold + and isinstance(countdown_tuple, (tuple, list)) + and len(countdown_tuple) >= 2 + and float(countdown_tuple[1] or 0.0) > 0.0 + ) + + if not (is_high_value and skip_reason.startswith("countdown_gt_")): + return "still_skip" + + remain_seconds = None + if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: + try: + now = time.time() + cd_start = float(countdown_tuple[0] or 0.0) + cd_end = float(countdown_tuple[1] or 0.0) + if cd_start > 0 and cd_end > cd_start: + remain_seconds = float(cd_end - now) + except Exception: + pass + + join_ahead_seconds = int(getattr(self, "high_value_fudai_join_ahead_seconds", 100) or 120) + + if remain_seconds is not None and remain_seconds <= join_ahead_seconds: + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与", + reason=skip_reason, + value_yuan=prize_value_yuan, + threshold=high_value_threshold, + remain_seconds=int(remain_seconds), + join_ahead_threshold=join_ahead_seconds, + ) + except Exception: + pass + return "continue" + + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:倒计时大于阈值,但价值达到高价值阈值,记录预约", + reason=skip_reason, + value_yuan=prize_value_yuan, + threshold=high_value_threshold, + remain_seconds=(int(remain_seconds) if remain_seconds is not None else None), + join_ahead_threshold=join_ahead_seconds, + level="DEBUG", + ) + except Exception: + pass + try: + douyin_fudai_core.basic_join_decision(self, detail) + except Exception as e: + try: + self._log_kv("流程", "_handle_in_fudai_detail:记录预约时出错", error=str(e)) + except Exception: + pass + elapsed = time.time() - start_time + self._log_kv("流程", "_handle_in_fudai_detail完成(记录预约)", elapsed_seconds=round(elapsed, 2)) + return "return" + except Exception as e: + try: + self._log_kv("流程", "_handle_in_fudai_detail:高价值检查异常", error=str(e)) + except Exception: + pass + return "still_skip" + + +def handle_skip_filter(self: "fudai_analyse", skip_reason: str, start_time: float) -> str: + """普通筛选不通过:关详情 + 按需切直播间。返回 return。""" + import time + + from douyin.fudai import douyin_fudai_detail + + try: + self._log_kv("流程", "_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过", skip_reason=skip_reason) + except Exception: + pass + try: + douyin_fudai_detail.close_fudai_detail(self) + except Exception: + pass + + try: + needswitch = bool(getattr(self, "needswitch", True)) + except Exception: + needswitch = True + + if needswitch: + try: + self._log_kv("流程", "_handle_in_fudai_detail:筛选不通过后切换直播间", skip_reason=skip_reason) + except Exception: + pass + try: + if hasattr(self, "swipe_up_to_next_live"): + self.swipe_up_to_next_live() + else: + fallback_swipe_up(self) + except Exception: + pass + + _clear_task_count_flag(self) + elapsed = time.time() - start_time + self._log_kv("流程", "_handle_in_fudai_detail完成(筛选不通过)", elapsed_seconds=round(elapsed, 2)) + return "return" + + +def fallback_swipe_up(self: "fudai_analyse") -> None: + """没有 swipe_up_to_next_live 时的兜底 swipe。""" + from douyin.core.fudai_modules.fudai_device_control import fallback_swipe_up_via_adb + + fallback_swipe_up_via_adb(self) + + +def _clear_task_count_flag(self: "fudai_analyse") -> None: + """清除任务数量标志。""" + try: + self._fudai_detail_task_count_from_stage = None + try: + self._log_kv( + "福袋详情", + "_handle_in_fudai_detail:清除任务数量标志", + log_type="DEBUG", + ) + except Exception: + pass + except Exception: + pass diff --git a/douyin/core/fudai_modules/handle_detail_first_open.py b/douyin/core/fudai_modules/handle_detail_first_open.py new file mode 100644 index 0000000..49878c9 --- /dev/null +++ b/douyin/core/fudai_modules/handle_detail_first_open.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_first_open_branch(self: "fudai_analyse", start_time: float) -> bool: + """第一次打开福袋详情分支。""" + from douyin.fudai import douyin_fudai_detail + from .handle_detail_filter import check_skip_and_handle + + step2_start = __import__("time").time() + detail = douyin_fudai_detail.read_fudai_detail_with_retries( + self, + fudai_x=0, + read_once_callback=douyin_fudai_detail.read_fudai_detail_once, + close_detail_callback=douyin_fudai_detail.close_fudai_detail, + ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, + ) + + if not (detail and isinstance(detail, tuple) and len(detail) >= 6): + try: + self._log_kv("流程", "_handle_in_fudai_detail:第一次打开时详情数据无效,跳过") + except Exception: + pass + return True + + if validate_first_open_detail(self, detail, step2_start, start_time): + return True + + branch_result = check_skip_and_handle(self, detail, step2_start, start_time) + if branch_result == "return": + return True + + try: + self._last_fudai_detail_tuple = detail + self._fudai_detail_first_read = True + if detail and isinstance(detail, tuple) and len(detail) >= 1: + self._current_fudai_content = str(detail[0] if detail[0] else "") + self._log_kv( + "流程", + "_handle_in_fudai_detail:福袋详情识别成功", + fudai_content=(detail[0] if len(detail) > 0 else "")[:50], + prize_value_yuan=float(detail[4] if len(detail) > 4 else 0.0), + ) + except Exception: + pass + return False + + +def validate_first_open_detail( + self: "fudai_analyse", detail, step2_start: float, start_time: float +) -> bool: + """第一次打开详情的数据验证。""" + import time + + from douyin.fudai import douyin_fudai_detail + + try: + is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self) + except Exception: + return False + + if is_valid: + return False + + actionable = {"可以参与", "需要加入粉丝团", "需要评论", "需要观看", "已参与"} + button_status = getattr(self, "_fudai_button_status", None) + if button_status in actionable: + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:数据验证失败但按钮可操作,继续参与", + validation_reason=reason, + button_status=button_status, + ) + except Exception: + pass + return False + + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:第一次打开时数据验证失败,跳过", + validation_reason=reason, + ) + except Exception: + pass + try: + douyin_fudai_detail.close_fudai_detail(self) + except Exception: + pass + + step2_elapsed = (time.time() - step2_start) * 1000 + self._log_kv("详情处理", "步骤2[读取福袋详情]-完成", 总耗时毫秒=step2_elapsed) + _clear_task_count_flag(self) + elapsed = time.time() - start_time + self._log_kv("流程", "_handle_in_fudai_detail完成(数据验证失败)", elapsed_seconds=round(elapsed, 2)) + return True + + +def _clear_task_count_flag(self: "fudai_analyse") -> None: + try: + self._fudai_detail_task_count_from_stage = None + try: + self._log_kv( + "福袋详情", + "_handle_in_fudai_detail:清除任务数量标志", + log_type="DEBUG", + ) + except Exception: + pass + except Exception: + pass + diff --git a/douyin/core/fudai_modules/handle_detail_helpers.py b/douyin/core/fudai_modules/handle_detail_helpers.py index 72a5cbb..f77ce54 100644 --- a/douyin/core/fudai_modules/handle_detail_helpers.py +++ b/douyin/core/fudai_modules/handle_detail_helpers.py @@ -545,119 +545,8 @@ def step4_make_join_decision( def _handle_reservation_completion( self: "fudai_analyse", future_timestamp: float ) -> None: - """参与成功是预约福袋时:处理锁定期 + 移除已完成的预约。""" - import time - - from douyin.reservation import douyin_reservation_logic - - try: - if not getattr(self, "reservation_after_action_pending", False): - return - - try: - self._log_kv( - "预约", - "[预约] 参与成功,处理锁定期并移除预约", - future_ts=int(future_timestamp), - current_focus_until=int( - getattr(self, "reservation_focus_until_ts", 0) - ), - ) - except Exception: - pass - - # 检查是否还有其他预约 - has_other_reservations = False - if hasattr(self, "reservations") and self.reservations: - for r in self.reservations: - try: - r_ft = float(r.get("future_ts") or 0.0) - if r_ft > 0 and abs(r_ft - future_timestamp) >= 5.0: - has_other_reservations = True - break - except Exception: - continue - - if has_other_reservations: - # 还有其他预约,设置短暂保护期 - protection_until = time.time() + 10.0 - self.reservation_focus_until_ts = max( - self.reservation_focus_until_ts, protection_until - ) - try: - self._log_kv( - "预约", - "[预约] 参与成功,设置保护期确保依次参与", - protection_seconds=10, - new_focus_until=int(self.reservation_focus_until_ts), - remaining_reservations=len( - [ - r - for r in self.reservations - if float(r.get("future_ts", 0)) > 0 - ] - ), - ) - except Exception: - pass - else: - # 没有其他预约,清除锁定期 - self.reservation_focus_until_ts = 0.0 - try: - self._log_kv( - "预约", - "[预约] 参与成功,清除锁定期(无其他预约)", - future_ts=int(future_timestamp), - ) - except Exception: - pass - - self.reservation_after_action_pending = False - - # 从预约队列中移除已完成的预约(匹配 future_ts,允许 5 秒误差) - if hasattr(self, "reservations") and self.reservations: - reservations_to_remove = [] - for idx, r in enumerate(self.reservations): - try: - r_ft = float(r.get("future_ts") or 0.0) - if r_ft > 0 and abs(r_ft - future_timestamp) < 5.0: - reservations_to_remove.append(idx) - except Exception: - continue - - # 从后往前删除,避免索引变化 - for idx in reversed(reservations_to_remove): - try: - removed = self.reservations.pop(idx) - try: - self._log_kv( - "预约", - "[预约] 已从队列中移除已完成的预约", - future_ts=int(removed.get("future_ts", 0)), - content=str(removed.get("content", ""))[:50], - ) - except Exception: - pass - except Exception: - pass - - # 重新排序预约队列 - if self.reservations: - try: - douyin_reservation_logic._sort_reservations_inplace( - self.reservations - ) - except Exception: - pass - except Exception as e: - try: - self._log_kv( - "预约", - "[预约] 清除锁定期和移除预约时出错", - error=str(e), - ) - except Exception: - pass + from .handle_detail_second_open import handle_reservation_completion as _impl + return _impl(self, future_timestamp) def _close_detail_after_attend(self: "fudai_analyse") -> None: @@ -687,521 +576,45 @@ def _close_detail_after_attend(self: "fudai_analyse") -> None: def handle_second_open_branch( self: "fudai_analyse", start_time: float, step1_start: float ) -> bool: - """步骤1:第二次打开福袋详情,直接点击参与(跳过验证和内容识别)。 - - 流程: - 1. 取 self._last_fudai_detail_tuple - 2. 缺失或无效 → 重新读取,保存到 self(兜底)后 fall through - 3. 有效 → 设置 self._current_fudai_future_ts 等倒计时信息 - 4. 调 douyin_fudai_core.attend_choujiang - - 成功:清标志 + 步骤1结束日志 + return True - - 失败:增加连续失败计数 + 清标志 + 步骤1结束日志 + return True - - 异常:log + 继续走正常流程,return False - - 返回 True 表示 caller 应当 `return`;False 表示需要走后续步骤 - (fall through 到 last_status / 验证 / 兜底 / step4)。 - """ - import time - from typing import Any, Tuple - - from douyin.fudai import douyin_fudai_core, douyin_fudai_detail - - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别", - ) - except Exception: - pass - - # 取第一次读取的详情数据 - detail = getattr(self, "_last_fudai_detail_tuple", None) - if detail is None or not isinstance(detail, tuple) or len(detail) < 6: - # 没有保存的详情数据,需要重新读取(兜底逻辑) - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取", - ) - except Exception: - pass - detail = douyin_fudai_detail.read_fudai_detail_with_retries( - self, - fudai_x=0, - read_once_callback=douyin_fudai_detail.read_fudai_detail_once, - close_detail_callback=douyin_fudai_detail.close_fudai_detail, - ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, - ) - # 重新读取后,更新保存的详情数据 - if detail and isinstance(detail, tuple) and len(detail) >= 6: - self._last_fudai_detail_tuple = detail - detail_t: Tuple[Any, ...] = tuple(detail) - self._current_fudai_content = ( - detail_t[0] if len(detail_t) > 0 else "" - ) - # 兜底重读后无论成功失败,都不在此 return —— 让 caller 继续走正常流程 - return False - - # 有效详情:设置倒计时信息 - try: - if ( - detail is not None - and isinstance(detail, tuple) - and len(detail) >= 6 - ): - detail_t = tuple(detail) - countdown_tuple = detail_t[5] - if ( - isinstance(countdown_tuple, (tuple, list)) - and len(countdown_tuple) >= 3 - ): - future_ts = float(countdown_tuple[1] or 0.0) - original_seconds = countdown_tuple[2] - if future_ts > 0: - self._current_fudai_future_ts = future_ts - self._current_fudai_content = ( - detail_t[0] if len(detail_t) > 0 else "" - ) - remain_seconds = ( - max(0, int(original_seconds or 0)) - if original_seconds is not None - else int(future_ts - time.time()) - ) - self._log_kv( - "参与", - "第二次打开:使用第一次的倒计时信息", - future_ts=int(future_ts), - remain_seconds=remain_seconds, - original_seconds=( - int(original_seconds or 0) - if original_seconds is not None - else None - ), - ) - except Exception as e: - try: - self._log_kv( - "参与", - "第二次打开:设置倒计时信息时出错", - error=str(e), - ) - except Exception: - pass - - # 直接调用参与函数,不进行验证 - try: - attend_result = douyin_fudai_core.attend_choujiang(self) - - if attend_result: - self._log_kv( - "参与", - "第二次打开:直接点击参与成功", - result="参与成功", - ) - self._consecutive_attend_failures = 0 - else: - self._log_kv( - "参与", - "第二次打开:直接点击参与失败", - result="参与失败", - ) - self._consecutive_attend_failures = ( - getattr(self, "_consecutive_attend_failures", 0) + 1 - ) - - # 清除第一次读取标志,下次打开新福袋时重新识别 - try: - self._fudai_detail_first_read = False - self._last_fudai_detail_tuple = None - except Exception: - pass - - # 清除任务数量标志 - _clear_task_count_flag(self) - - # 步骤1结束计时 - step1_elapsed = (time.time() - step1_start) * 1000 - self._log_kv( - "详情处理", - "步骤1[检查是否第二次打开]-完成", - 总耗时毫秒=step1_elapsed, - ) - - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_in_fudai_detail完成(第二次打开直接参与)", - elapsed_seconds=round(elapsed, 2), - attend_result=attend_result, - ) - return True - except Exception as e: - self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e)) - # 异常时继续正常流程 - return False + from .handle_detail_second_open import handle_second_open_branch as _impl + return _impl(self, start_time, step1_start) def handle_first_open_branch( self: "fudai_analyse", start_time: float ) -> bool: - """步骤2 + 步骤3:第一次打开福袋详情的完整分支。 - - 流程: - 1. read_fudai_detail_with_retries 完整读取详情 - 2. 数据验证 — 失败则关详情 return True - 3. should_skip_fudai_by_config 筛选检查 - - skip=True 且高价值且倒计时大于阈值: - * 剩余秒数在预约阈值内 → skip=False,fall through 继续走立即参与 - * 剩余秒数大于预约阈值 → 调 basic_join_decision 记录预约 return True - - skip=True 普通筛选不通过 → 关详情 + 切直播间 return True - - skip=False 筛选通过 → 保存详情数据 + 标记已读取,fall through - 4. detail 无效(< 6 元素或 None)→ return True - - 返回 True 表示 caller 应当 `return`;False 表示继续走后续步骤 - (步骤3末尾的 last_status / 兜底 / step4)。 - """ - import time - - from douyin.fudai import douyin_fudai_detail - - step2_start = time.time() - detail = douyin_fudai_detail.read_fudai_detail_with_retries( - self, - fudai_x=0, - read_once_callback=douyin_fudai_detail.read_fudai_detail_once, - close_detail_callback=douyin_fudai_detail.close_fudai_detail, - ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, - ) - - # detail 无效 → 提前 return - if not (detail and isinstance(detail, tuple) and len(detail) >= 6): - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:第一次打开时详情数据无效,跳过", - ) - except Exception: - pass - return True - - # 数据验证失败 → return - if _validate_first_open_detail(self, detail, step2_start, start_time): - return True - - # 筛选检查 - branch_result = _check_skip_and_handle( - self, detail, step2_start, start_time - ) - if branch_result == "return": - return True - # branch_result == "continue" → 筛选通过或高价值阈值内立即参与,保存数据后继续 - - # 筛选通过,保存详情数据并标记为已读取 - try: - self._last_fudai_detail_tuple = detail - self._fudai_detail_first_read = True - if detail and isinstance(detail, tuple) and len(detail) >= 1: - self._current_fudai_content = str( - detail[0] if detail[0] else "" - ) - self._log_kv( - "流程", - "_handle_in_fudai_detail:福袋详情识别成功", - fudai_content=(detail[0] if len(detail) > 0 else "")[:50], - prize_value_yuan=float(detail[4] if len(detail) > 4 else 0.0), - ) - except Exception: - pass - return False + from .handle_detail_first_open import handle_first_open_branch as _impl + return _impl(self, start_time) def _validate_first_open_detail( self: "fudai_analyse", detail, step2_start: float, start_time: float ) -> bool: - """数据验证。失败时关详情 + 清标志 + log,返回 True。""" - import time - - from douyin.fudai import douyin_fudai_detail - - try: - is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self) - except Exception: - return False - - if is_valid: - return False - - # 按钮状态为可操作时,即使其他字段验证失败也继续走参与流程 - _ACTIONABLE_BUTTON_STATUSES = { - "可以参与", - "需要加入粉丝团", - "需要评论", - "需要观看", - "已参与", - } - button_status = getattr(self, "_fudai_button_status", None) - if button_status in _ACTIONABLE_BUTTON_STATUSES: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:数据验证失败但按钮可操作,继续参与", - validation_reason=reason, - button_status=button_status, - ) - except Exception: - pass - return False - - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:第一次打开时数据验证失败,跳过", - validation_reason=reason, - ) - except Exception: - pass - try: - douyin_fudai_detail.close_fudai_detail(self) - except Exception: - pass - - step2_elapsed = (time.time() - step2_start) * 1000 - self._log_kv( - "详情处理", - "步骤2[读取福袋详情]-完成", - 总耗时毫秒=step2_elapsed, - ) - _clear_task_count_flag(self) - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_in_fudai_detail完成(数据验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return True + from .handle_detail_first_open import validate_first_open_detail as _impl + return _impl(self, detail, step2_start, start_time) def _check_skip_and_handle( self: "fudai_analyse", detail, step2_start: float, start_time: float ) -> str: - """筛选检查 + 高价值预约 + 筛选不通过切房。 - - 返回: - - "return" caller 应当 return(已记预约 / 切房) - - "continue" 筛选通过或高价值阈值内立即参与,caller 继续走保存逻辑 - """ - from douyin.fudai import douyin_fudai_core - - try: - skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config( - self, detail - ) - except Exception as e: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:筛选检查异常", - error=str(e), - ) - except Exception: - pass - return "continue" - - if not skip: - return "continue" - - # 高价值倒计时筛选处理 - high_value_result = _try_high_value_reservation( - self, detail, skip, skip_reason, start_time - ) - if high_value_result == "return": - return "return" - if high_value_result == "continue": - # 阈值内立即参与,回到保存路径 - return "continue" - # "still_skip" → 走普通跳过 - return _handle_skip_filter(self, skip_reason, start_time) + from .handle_detail_filter import check_skip_and_handle as _impl + return _impl(self, detail, step2_start, start_time) def _try_high_value_reservation( self: "fudai_analyse", detail, skip: bool, skip_reason: str, start_time: float ) -> str: - """高价值倒计时筛选处理。 - - 返回: - - "return" 已记录预约,caller return - - "continue" 阈值内立即参与,caller 走保存路径 - - "still_skip" 不是高价值或不是倒计时原因,走普通跳过 - """ - import time - - from douyin.fudai import douyin_fudai_core - - try: - prize_value_yuan = 0.0 - countdown_tuple = None - if isinstance(detail, tuple) and len(detail) >= 6: - _, _, _, _, prize_value_yuan, countdown_tuple = detail - - high_value_enabled = bool( - getattr(self, "high_value_fudai_enabled", False) - ) - high_value_threshold = float( - getattr(self, "high_value_fudai_threshold_yuan", 500.0) or 500.0 - ) - - is_high_value = ( - high_value_enabled - and prize_value_yuan > 0 - and prize_value_yuan >= high_value_threshold - and isinstance(countdown_tuple, (tuple, list)) - and len(countdown_tuple) >= 2 - and float(countdown_tuple[1] or 0.0) > 0.0 - ) - - if not (is_high_value and skip_reason.startswith("countdown_gt_")): - return "still_skip" - - # 计算剩余秒数 - remain_seconds = None - if ( - isinstance(countdown_tuple, (tuple, list)) - and len(countdown_tuple) >= 2 - ): - try: - now = time.time() - cd_start = float(countdown_tuple[0] or 0.0) - cd_end = float(countdown_tuple[1] or 0.0) - if cd_start > 0 and cd_end > cd_start: - remain_seconds = float(cd_end - now) - except Exception: - pass - - join_ahead_seconds = int( - getattr(self, "high_value_fudai_join_ahead_seconds", 100) or 120 - ) - - # 阈值内立即参与 - if ( - remain_seconds is not None - and remain_seconds <= join_ahead_seconds - ): - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与", - reason=skip_reason, - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=int(remain_seconds), - join_ahead_threshold=join_ahead_seconds, - ) - except Exception: - pass - return "continue" - - # 阈值外:记录预约 - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:倒计时大于阈值,但价值达到高价值阈值,记录预约", - reason=skip_reason, - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - remain_seconds=( - int(remain_seconds) if remain_seconds is not None else None - ), - join_ahead_threshold=join_ahead_seconds, - level="DEBUG", - ) - except Exception: - pass - try: - douyin_fudai_core.basic_join_decision(self, detail) - except Exception as e: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:记录预约时出错", - error=str(e), - ) - except Exception: - pass - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_in_fudai_detail完成(记录预约)", - elapsed_seconds=round(elapsed, 2), - ) - return "return" - except Exception as e: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:高价值检查异常", - error=str(e), - ) - except Exception: - pass - return "still_skip" + from .handle_detail_filter import try_high_value_reservation as _impl + return _impl(self, detail, skip, skip_reason, start_time) def _handle_skip_filter( self: "fudai_analyse", skip_reason: str, start_time: float ) -> str: - """普通筛选不通过:关详情 + 按需切直播间。返回 "return"。""" - import time - - from douyin.fudai import douyin_fudai_detail - - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过", - skip_reason=skip_reason, - ) - except Exception: - pass - try: - douyin_fudai_detail.close_fudai_detail(self) - except Exception: - pass - - try: - needswitch = bool(getattr(self, "needswitch", True)) - except Exception: - needswitch = True - - if needswitch: - try: - self._log_kv( - "流程", - "_handle_in_fudai_detail:筛选不通过后切换直播间", - skip_reason=skip_reason, - ) - except Exception: - pass - try: - if hasattr(self, "swipe_up_to_next_live"): - self.swipe_up_to_next_live() - else: - _fallback_swipe_up(self) - except Exception: - pass - - _clear_task_count_flag(self) - elapsed = time.time() - start_time - self._log_kv( - "流程", - "_handle_in_fudai_detail完成(筛选不通过)", - elapsed_seconds=round(elapsed, 2), - ) - return "return" + from .handle_detail_filter import handle_skip_filter as _impl + return _impl(self, skip_reason, start_time) def _fallback_swipe_up(self: "fudai_analyse") -> None: - """没有 swipe_up_to_next_live 时的兜底 swipe(基于 1080x2400 基准坐标)。""" - from douyin.core.fudai_modules.fudai_device_control import ( - fallback_swipe_up_via_adb, - ) - fallback_swipe_up_via_adb(self) + from .handle_detail_filter import fallback_swipe_up as _impl + return _impl(self) diff --git a/douyin/core/fudai_modules/handle_detail_second_open.py b/douyin/core/fudai_modules/handle_detail_second_open.py new file mode 100644 index 0000000..3c973c6 --- /dev/null +++ b/douyin/core/fudai_modules/handle_detail_second_open.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_reservation_completion( + self: "fudai_analyse", future_timestamp: float +) -> None: + """参与成功是预约福袋时:处理锁定期 + 移除已完成的预约。""" + import time + + from douyin.reservation import douyin_reservation_logic + + try: + if not getattr(self, "reservation_after_action_pending", False): + return + + try: + self._log_kv( + "预约", + "[预约] 参与成功,处理锁定期并移除预约", + future_ts=int(future_timestamp), + current_focus_until=int(getattr(self, "reservation_focus_until_ts", 0)), + ) + except Exception: + pass + + has_other_reservations = False + if hasattr(self, "reservations") and self.reservations: + for r in self.reservations: + try: + r_ft = float(r.get("future_ts") or 0.0) + if r_ft > 0 and abs(r_ft - future_timestamp) >= 5.0: + has_other_reservations = True + break + except Exception: + continue + + if has_other_reservations: + protection_until = time.time() + 10.0 + self.reservation_focus_until_ts = max( + self.reservation_focus_until_ts, protection_until + ) + try: + self._log_kv( + "预约", + "[预约] 参与成功,设置保护期确保依次参与", + protection_seconds=10, + new_focus_until=int(self.reservation_focus_until_ts), + remaining_reservations=len( + [r for r in self.reservations if float(r.get("future_ts", 0)) > 0] + ), + ) + except Exception: + pass + else: + self.reservation_focus_until_ts = 0.0 + try: + self._log_kv( + "预约", + "[预约] 参与成功,清除锁定期(无其他预约)", + future_ts=int(future_timestamp), + ) + except Exception: + pass + + self.reservation_after_action_pending = False + + if hasattr(self, "reservations") and self.reservations: + reservations_to_remove = [] + for idx, r in enumerate(self.reservations): + try: + r_ft = float(r.get("future_ts") or 0.0) + if r_ft > 0 and abs(r_ft - future_timestamp) < 5.0: + reservations_to_remove.append(idx) + except Exception: + continue + + for idx in reversed(reservations_to_remove): + try: + removed = self.reservations.pop(idx) + try: + self._log_kv( + "预约", + "[预约] 已从队列中移除已完成的预约", + future_ts=int(removed.get("future_ts", 0)), + content=str(removed.get("content", ""))[:50], + ) + except Exception: + pass + except Exception: + pass + + if self.reservations: + try: + douyin_reservation_logic._sort_reservations_inplace(self.reservations) + except Exception: + pass + except Exception as e: + try: + self._log_kv("预约", "[预约] 清除锁定期和移除预约时出错", error=str(e)) + except Exception: + pass + + +def handle_second_open_branch( + self: "fudai_analyse", start_time: float, step1_start: float +) -> bool: + """步骤1:第二次打开福袋详情,直接点击参与(跳过验证和内容识别)。""" + import time + from typing import Any, Tuple + + from douyin.fudai import douyin_fudai_core, douyin_fudai_detail + + try: + self._log_kv("流程", "_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别") + except Exception: + pass + + detail = getattr(self, "_last_fudai_detail_tuple", None) + if detail is None or not isinstance(detail, tuple) or len(detail) < 6: + try: + self._log_kv("流程", "_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取") + except Exception: + pass + detail = douyin_fudai_detail.read_fudai_detail_with_retries( + self, + fudai_x=0, + read_once_callback=douyin_fudai_detail.read_fudai_detail_once, + close_detail_callback=douyin_fudai_detail.close_fudai_detail, + ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, + ) + if detail and isinstance(detail, tuple) and len(detail) >= 6: + self._last_fudai_detail_tuple = detail + detail_t: Tuple[Any, ...] = tuple(detail) + self._current_fudai_content = detail_t[0] if len(detail_t) > 0 else "" + return False + + try: + if detail is not None and isinstance(detail, tuple) and len(detail) >= 6: + detail_t = tuple(detail) + countdown_tuple = detail_t[5] + if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 3: + future_ts = float(countdown_tuple[1] or 0.0) + original_seconds = countdown_tuple[2] + if future_ts > 0: + self._current_fudai_future_ts = future_ts + self._current_fudai_content = detail_t[0] if len(detail_t) > 0 else "" + remain_seconds = ( + max(0, int(original_seconds or 0)) + if original_seconds is not None + else int(future_ts - time.time()) + ) + self._log_kv( + "参与", + "第二次打开:使用第一次的倒计时信息", + future_ts=int(future_ts), + remain_seconds=remain_seconds, + original_seconds=(int(original_seconds or 0) if original_seconds is not None else None), + ) + except Exception as e: + try: + self._log_kv("参与", "第二次打开:设置倒计时信息时出错", error=str(e)) + except Exception: + pass + + try: + attend_result = douyin_fudai_core.attend_choujiang(self) + + if attend_result: + self._log_kv("参与", "第二次打开:直接点击参与成功", result="参与成功") + self._consecutive_attend_failures = 0 + else: + self._log_kv("参与", "第二次打开:直接点击参与失败", result="参与失败") + self._consecutive_attend_failures = getattr(self, "_consecutive_attend_failures", 0) + 1 + + try: + self._fudai_detail_first_read = False + self._last_fudai_detail_tuple = None + except Exception: + pass + + _clear_task_count_flag(self) + + step1_elapsed = (time.time() - step1_start) * 1000 + self._log_kv("详情处理", "步骤1[检查是否第二次打开]-完成", 总耗时毫秒=step1_elapsed) + + elapsed = time.time() - start_time + self._log_kv( + "流程", + "_handle_in_fudai_detail完成(第二次打开直接参与)", + elapsed_seconds=round(elapsed, 2), + attend_result=attend_result, + ) + return True + except Exception as e: + self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e)) + return False + + +def _clear_task_count_flag(self: "fudai_analyse") -> None: + try: + self._fudai_detail_task_count_from_stage = None + try: + self._log_kv("福袋详情", "_handle_in_fudai_detail:清除任务数量标志", log_type="DEBUG") + except Exception: + pass + except Exception: + pass + diff --git a/douyin/core/fudai_modules/live_room_handlers.py b/douyin/core/fudai_modules/live_room_handlers.py new file mode 100644 index 0000000..9a237d1 --- /dev/null +++ b/douyin/core/fudai_modules/live_room_handlers.py @@ -0,0 +1,184 @@ +"""直播间/福袋详情处理逻辑下沉模块。""" +from __future__ import annotations + +import time +from typing import TYPE_CHECKING, List + +from douyin.core import douyin_flow_control +from douyin.fudai import douyin_fudai_detail + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_in_fudai_detail(self: "fudai_analyse") -> None: + from douyin.core.fudai_modules import handle_detail_helpers as _hd_helpers + + start_time = time.time() + _hd_helpers.log_entry_flags(self) + + if _hd_helpers.handle_consecutive_failures_check(self): + return + + step1_start = time.time() + is_second_open = getattr(self, "_fudai_detail_first_read", False) + if is_second_open: + if _hd_helpers.handle_second_open_branch(self, start_time, step1_start): + return + else: + if _hd_helpers.handle_first_open_branch(self, start_time): + return + + if _hd_helpers.check_last_status_branch(self, start_time): + return + + detail = getattr(self, "_last_fudai_detail_tuple", None) + try: + self._fudai_detail_consecutive_failures = 0 + except Exception: + pass + + try: + if detail is None: + try: + self._log_kv("福袋详情", "详情数据为 None,跳过验证") + except Exception: + pass + else: + is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self) + if not is_valid: + actionable = {"可以参与", "需要加入粉丝团", "需要评论", "需要观看", "已参与"} + btn_st = getattr(self, "_fudai_button_status", None) + if btn_st in actionable: + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:验证失败但按钮可操作,继续参与", + validation_reason=reason, + button_status=btn_st, + ) + except Exception: + pass + else: + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:福袋详情数据验证失败,识别出错", + validation_reason=reason, + ) + except Exception: + pass + douyin_fudai_detail.close_fudai_detail(self) + _hd_helpers._clear_task_count_flag(self) + elapsed = time.time() - start_time + self._log_kv( + "流程", + "_handle_in_fudai_detail完成(验证失败)", + elapsed_seconds=round(elapsed, 2), + ) + return + except Exception: + pass + + if _hd_helpers.check_invalid_detail_fallback(self, detail, start_time): + return + + attend_before_ts = _hd_helpers.prepare_for_attend(self, detail) + _hd_helpers.step4_make_join_decision(self, detail, False, "", attend_before_ts, start_time) + + +def handle_live_room_has_or_not_fudai(self: "fudai_analyse") -> None: + start_time = time.time() + self._current_attending_reservation_fudai = False + + try: + already_verified = bool(getattr(self, "_fudai_detail_verified", False) or False) + if already_verified: + try: + self._log_kv("流程", "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋") + except Exception: + pass + self._handle_in_fudai_detail() + elapsed = time.time() - start_time + self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(已验证详情页)", elapsed_seconds=round(elapsed, 2)) + return + except Exception: + pass + + try: + now_ts = time.time() + focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0) + queue_full_waiting = bool(getattr(self, "queue_full_waiting_at_earliest", False) or False) + + if focus_until > 0 and now_ts < focus_until and queue_full_waiting: + if self.reservations and len(self.reservations) > 0: + earliest = self.reservations[0] + try: + ft = float(earliest.get("future_ts") or 0.0) + if ft > 0: + join_ahead = float(getattr(self, "high_value_fudai_join_ahead_seconds", 100) or 120) + time_window_start_ts = ft - join_ahead + if now_ts < time_window_start_ts: + try: + self._log_kv( + "预约", + "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", + focus_until=int(focus_until), + now_ts=int(now_ts), + time_window_start=int(time_window_start_ts), + remain_seconds=int(time_window_start_ts - now_ts), + ) + except Exception: + pass + elapsed = time.time() - start_time + self._log_kv( + "流程", + "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", + elapsed_seconds=round(elapsed, 2), + ) + return + except Exception: + pass + except Exception: + pass + + room_pos_ref: List[int] = [0] + opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref) + if not opened: + try: + need_switch_config = bool(getattr(self, "needswitch", True)) + except Exception: + need_switch_config = True + + wait_times_ref = [0] + swipe_times_ref = [0] + reservation_focus_until_ts_ref = [0.0] + reset_to_list_after_reservations_ref = [False] + douyin_flow_control.handle_no_fudai_situation( + self, + x=0, + swipe_times=0, + wait_times_ref=wait_times_ref, + needswitch=need_switch_config, + reservation_focus_until_ts=0.0, + reservations=[], + room_pos=room_pos_ref[0], + post_switch_delay_s=1.5, + swipe_up_switch_callback=self.swipe_up_to_next_live, + swipe_down_back_callback=lambda: None, + sort_reservations_callback=lambda: None, + clear_reservations_callback=lambda: None, + write_state_callback=lambda: None, + back_to_list_callback=lambda: None, + into_list_callback=lambda: None, + reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, + reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, + swipe_times_ref=swipe_times_ref, + ) + elapsed = time.time() - start_time + self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(无福袋)", elapsed_seconds=round(elapsed, 2)) + return + + self._handle_in_fudai_detail() + elapsed = time.time() - start_time + self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(成功打开详情)", elapsed_seconds=round(elapsed, 2)) diff --git a/douyin/core/fudai_modules/run_once_basic_fansclub.py b/douyin/core/fudai_modules/run_once_basic_fansclub.py new file mode 100644 index 0000000..6182585 --- /dev/null +++ b/douyin/core/fudai_modules/run_once_basic_fansclub.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_fansclub_join(self: "fudai_analyse", start_time: float) -> None: + """FANSCLUB_JOIN 阶段处理:参与按钮 + 预设位置点击 + 关闭详情。""" + self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理") + try: + attend_x = int(543 * self.resolution_ratio_x // 1080) + attend_y = int(2070 * self.resolution_ratio_y // 2400) + self.operation.click(self.device_id, attend_x, attend_y) + self._log_kv( + "粉丝团处理", + "先点击参与按钮", + x=attend_x, + y=attend_y, + base_x=543, + base_y=2070, + region="(306,2030)-(780,2110)", + ) + self.operation.delay(0.5) + + preset_x = int(527 * self.resolution_ratio_x // 1080) + preset_y = int(567 * self.resolution_ratio_y // 2400) + + self.operation.click(self.device_id, preset_x, preset_y) + self._log_kv( + "粉丝团处理", + "第一次点击预设位置", + x=preset_x, + y=preset_y, + base_x=527, + base_y=567, + ) + self.operation.delay(0.5) + + self.operation.click(self.device_id, preset_x, preset_y) + self._log_kv( + "粉丝团处理", + "第二次点击预设位置", + x=preset_x, + y=preset_y, + base_x=527, + base_y=567, + ) + self.operation.delay(1.0) + + close_x = int(500 * self.resolution_ratio_x // 1080) + close_y = int(470 * self.resolution_ratio_y // 2400) + self.operation.click(self.device_id, close_x, close_y) + self._log_kv( + "粉丝团处理", + "关闭详情页", + x=close_x, + y=close_y, + base_x=500, + base_y=470, + ) + self.operation.delay(1.0) + except Exception as exc: + self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc)) + + if getattr(self, "auto_join_fansclub", False): + self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载") + self.operation.delay(1.0) + try: + stage_after, _ = self._diagnose_stage_from_current_screen() + if stage_after == "FANSCLUB_JOIN": + preset_x = int(527 * self.resolution_ratio_x // 1080) + preset_y = int(567 * self.resolution_ratio_y // 2400) + self.operation.click(self.device_id, preset_x, preset_y) + self._log_kv( + "粉丝团处理", + "仍在粉丝团加入页,再次第一次点击", + x=preset_x, + y=preset_y, + base_x=527, + base_y=567, + ) + self.operation.delay(0.5) + self.operation.click(self.device_id, preset_x, preset_y) + self._log_kv( + "粉丝团处理", + "仍在粉丝团加入页,再次第二次点击", + x=preset_x, + y=preset_y, + base_x=527, + base_y=567, + ) + self.operation.delay(2.0) + + try: + return_x = int(527 * self.resolution_ratio_x // 1080) + return_y = int(567 * self.resolution_ratio_y // 2400) + self.operation.click(self.device_id, return_x, return_y) + self._log_kv( + "粉丝团处理", + "加入粉丝团成功后,点击返回直播间", + x=return_x, + y=return_y, + base_x=527, + base_y=567, + ) + self.operation.delay(1.0) + except Exception as exc_inner: + self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc_inner)) + except Exception: + pass + else: + self._log_kv("粉丝团处理", "未启用自动加入粉丝团,等待手动确认", wait_seconds=15) + self.operation.delay(15.0) + try: + return_x = int(527 * self.resolution_ratio_x // 1080) + return_y = int(567 * self.resolution_ratio_y // 2400) + self.operation.click(self.device_id, return_x, return_y) + self._log_kv( + "粉丝团处理", + "加入粉丝团成功后,点击返回直播间", + x=return_x, + y=return_y, + base_x=527, + base_y=567, + ) + self.operation.delay(1.0) + except Exception as exc_inner2: + self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc_inner2)) + + self.operation.delay(0.5) + + fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay") + if fansclub_fail_action == "switch": + self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间") + try: + self.swipe_up_to_next_live() + except Exception: + pass + elapsed = time.time() - start_time + self._log_kv("流程", "run_once_basic完成(处理粉丝团)", elapsed_seconds=round(elapsed, 2)) + diff --git a/douyin/core/fudai_modules/run_once_basic_helpers.py b/douyin/core/fudai_modules/run_once_basic_helpers.py index d9a960e..d7fd625 100644 --- a/douyin/core/fudai_modules/run_once_basic_helpers.py +++ b/douyin/core/fudai_modules/run_once_basic_helpers.py @@ -15,6 +15,20 @@ if TYPE_CHECKING: from ..douyin_fudai import fudai_analyse +def _emit_flow_flag(self: "fudai_analyse", flag: str, status: str, **extra) -> None: + """输出统一流程标志,便于按关键节点检索整条福袋流程。""" + try: + payload = { + "flag": str(flag or ""), + "status": str(status or ""), + "run_id": str(getattr(self, "_run_id", "") or ""), + } + payload.update(extra or {}) + self._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload) + except Exception: + pass + + def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float) -> bool: """0. 等待开奖期间持续 OCR 检测开奖结果。 @@ -252,247 +266,56 @@ def handle_no_attend_timeout(self: "fudai_analyse", start_time: float) -> bool: return False -def handle_desktop_recovery(self: "fudai_analyse") -> bool: - """1.5 桌面检测自救:检测前台包名,若不在抖音则尝试恢复并重跑一次 run_once_basic。 - - 返回 True 表示已触发自救并递归调用过 run_once_basic,caller 应当 `return`; - 返回 False 表示不需要自救,继续走后续步骤。 - """ - from douyin.core import recovery as _recovery +def run_once_basic_prelude(self: "fudai_analyse", start_time: float) -> None: + """run_once_basic 前置逻辑:启动日志、养号触发、直播间标题记录。""" + self._log_kv("流程", "run_once_basic开始", start_timestamp=start_time) + _emit_flow_flag( + self, + "run_once_basic", + "start", + room_pos=int(getattr(self, "room_pos", 0) or 0), + wait_minutes=int(getattr(self, "wait_minutes", 0) or 0), + needswitch=bool(getattr(self, "needswitch", True)), + ) + # 在主循环开始时检查是否需要定时触发推荐页养号 try: - top_pkg = "" - try: - top_pkg = self.operation.get_top_package(self.device_id) or "" - self._log_kv("自救", "桌面检测:获取前台包名", top_pkg=top_pkg) - except Exception as exc: - top_pkg = "" - self._log_kv("自救", "桌面检测:获取前台包名失败", error=str(exc)) + self._maybe_run_yanghao_during_run() + except Exception: + pass - if top_pkg and not _recovery.is_douyin_foreground(top_pkg): + # 尝试记录当前直播间的标题与位置,确保所有直播间(不限福袋)都被采集到运行时映射表 + # 但如果刚刚切换直播间,避免重复记录(切换前已记录) + try: + just_switched = getattr(self, "_just_switched_room", False) + if not just_switched: + self._record_room_title_and_pos() + else: self._log_kv( - "自救", - "桌面检测:检测到不在抖音前台", - top_pkg=top_pkg, - is_douyin=False, + "预约", + "[预约] 刚刚切换直播间,跳过重复记录标题", + reason="avoid_duplicate_after_switch", ) - try: - self._log_kv( - "自救", - "发现前台包不在抖音,尝试通过包名启动抖音", - top_pkg=top_pkg, - ) - _recovery.recover_to_douyin( - self, - log=lambda msg: self._log_kv("自救", msg), - ) - # 自救完成后立即重新执行一次主流程 - try: - self._log_kv( - "流程", - "run_once_basic:自救完成,立即重新执行一次主流程", - ) - except Exception: - pass - # 为避免递归过深,仅在当前检测到不在抖音前台的场景下递归一次; - # 自救完成后前台包名应为抖音,下一次 run_once_basic 将不会再次进入自救分支。 - try: - self.operation.delay(0.5) - except Exception: - time.sleep(0.5) - self.run_once_basic() - return True - except Exception as e: - try: - self._log_kv( - "自救", - "恢复失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - except Exception as exc: - # 桌面检测本身出错,记录日志 - try: - self._log_kv( - "自救", - "桌面检测异常", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - return False + except Exception: + pass + + +def handle_desktop_recovery(self: "fudai_analyse") -> bool: + from .run_once_basic_stage import handle_desktop_recovery as _impl + return _impl(self) def screenshot_and_diagnose( self: "fudai_analyse", start_time: float, ): - """1. 截图 + 阶段诊断。 - - 返回值: - - 截图失败:返回 None(caller 应当 `return`) - - 截图成功:返回 (stage, seen) 元组,并已设置 self._last_diag_* - """ - screenshot_start = time.time() - max_screenshot_retries = 3 - ok = False - - for retry in range(max_screenshot_retries): - ok = self.operation.get_screenshot(self.device_id, use_service=False) - if ok: - break - - if retry < max_screenshot_retries - 1: - self._log_kv( - "截图", - f"截图失败,重试中 ({retry + 1}/{max_screenshot_retries})", - retry=retry + 1, - max_retries=max_screenshot_retries, - ) - try: - self.operation.delay(1.0) - except Exception: - time.sleep(1.0) - - screenshot_elapsed = time.time() - screenshot_start - if not ok: - elapsed = time.time() - start_time - self._log_kv( - "截图", - "获取截图失败(多次重试后仍失败)", - ok=0, - retries=max_screenshot_retries, - elapsed_seconds=round(elapsed, 2), - screenshot_elapsed_seconds=round(screenshot_elapsed, 2), - reservation_after_action_pending=bool( - getattr(self, "reservation_after_action_pending", False) - ), - reservation_focus_until_ts=float( - getattr(self, "reservation_focus_until_ts", 0.0) or 0.0 - ), - waiting_for_lottery=bool( - getattr(self, "_waiting_for_lottery_result", False) - ), - room_pos=int(getattr(self, "room_pos", 0) or 0), - suggestion="检查设备连接状态和ADB服务", - ) - return None - - # 结构化预日志,便于排查为何后续没复用首次诊断结果 - try: - self._log_kv( - "阶段诊断", - "调用阶段诊断-前置检查", - trigger_reason="run_once_basic_initial", - fudai_detail_task_count_from_stage=getattr( - self, "_fudai_detail_task_count_from_stage", None - ), - screenshot_ready_for_ocr=bool( - getattr(self, "_screenshot_ready_for_ocr", False) - ), - ) - except Exception: - pass - - stage, seen = self._diagnose_stage_from_current_screen( - trigger_reason="run_once_basic_initial" - ) - self._last_diag_stage = stage - self._last_diag_seen = seen - self._last_diag_ts = time.time() - elapsed = time.time() - start_time - self._log_kv( - "截图", - "截图+阶段诊断", - stage=stage, - seen=seen, - elapsed_seconds=round(elapsed, 2), - screenshot_elapsed_seconds=round(screenshot_elapsed, 2), - ) - return stage, seen + from .run_once_basic_stage import screenshot_and_diagnose as _impl + return _impl(self, start_time) def handle_high_value_room_revisit(self: "fudai_analyse", start_time: float) -> bool: - """2.0 高价值房间重访检查。 - - 返回 True 表示重访成功,caller 应当 `return`; - 返回 False 表示未触发重访或重访失败,继续后续步骤。 - """ - try: - revisit_enabled = bool( - getattr(self, "high_value_room_revisit_enabled", False) - ) - only_current_run = bool( - getattr(self, "high_value_room_revisit_only_current_run", False) - ) - - if revisit_enabled: - from douyin.other import douyin_high_value_room - - should_revisit = douyin_high_value_room.should_trigger_revisit( - analyser=self, - revisit_enabled=revisit_enabled, - only_current_run=only_current_run, - min_interval_seconds=getattr( - self, "high_value_room_revisit_min_interval_seconds", 300 - ), - max_revisit_per_run=getattr( - self, "high_value_room_revisit_max_per_run", 5 - ), - ) - - if should_revisit: - candidates = douyin_high_value_room.get_revisit_candidates( - analyser=self, - only_current_run=only_current_run, - min_prize_value=getattr( - self, "high_value_room_revisit_min_prize_value", 0.0 - ), - max_age_days=getattr( - self, "high_value_room_revisit_max_age_days", 30 - ), - ) - - if candidates: - target_room = candidates[0] # 取优先级最高的房间 - self._log_kv( - "高价值房间", - "[重访] 触发高价值房间重访", - target_room_title=target_room.get("room_title", "")[:30], - max_prize_value=target_room.get("max_prize_value_yuan", 0), - candidates_count=len(candidates), - ) - - revisit_success = douyin_high_value_room.execute_room_revisit( - analyser=self, target_room=target_room - ) - - if revisit_success: - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(高价值房间重访成功)", - elapsed_seconds=round(elapsed, 2), - ) - return True - else: - self._log_kv( - "高价值房间", "[重访] 高价值房间重访失败,继续正常流程" - ) - except Exception as exc: - try: - self._log_kv( - "高价值房间", - "[重访] 高价值房间重访检查异常", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - return False + from .run_once_basic_stage import handle_high_value_room_revisit as _impl + return _impl(self, start_time) def dispatch_stage_branch( @@ -506,6 +329,12 @@ def dispatch_stage_branch( 本函数总是消费完一轮分发后返回;caller 不需要判断返回值——run_once_basic 在调用本函数后即结束本轮(原本各分支后面也没有更多代码)。 """ + _emit_flow_flag( + self, + "stage_dispatch", + "enter", + stage=str(stage or ""), + ) # 处理弹窗阶段 if stage == "COUPON_POPUP": # 优惠券弹窗:按返回键关闭 @@ -707,162 +536,8 @@ def dispatch_stage_branch( def _handle_fansclub_join(self: "fudai_analyse", start_time: float) -> None: - """FANSCLUB_JOIN 阶段处理:参与按钮 + 预设位置点击 + 关闭详情。""" - self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理") - try: - # 第一步:先点击参与按钮 - attend_x = int(543 * self.resolution_ratio_x // 1080) - attend_y = int(2070 * self.resolution_ratio_y // 2400) - self.operation.click(self.device_id, attend_x, attend_y) - self._log_kv( - "粉丝团处理", - "先点击参与按钮", - x=attend_x, - y=attend_y, - base_x=543, - base_y=2070, - region="(306,2030)-(780,2110)", - ) - self.operation.delay(0.5) - - # 第二步:点击两次预设位置(527, 567) - preset_x = int(527 * self.resolution_ratio_x // 1080) - preset_y = int(567 * self.resolution_ratio_y // 2400) - - self.operation.click(self.device_id, preset_x, preset_y) - self._log_kv( - "粉丝团处理", - "第一次点击预设位置", - x=preset_x, - y=preset_y, - base_x=527, - base_y=567, - ) - self.operation.delay(0.5) - - self.operation.click(self.device_id, preset_x, preset_y) - self._log_kv( - "粉丝团处理", - "第二次点击预设位置", - x=preset_x, - y=preset_y, - base_x=527, - base_y=567, - ) - self.operation.delay(1.0) - - # 第三步:关闭详情页 - close_x = int(500 * self.resolution_ratio_x // 1080) - close_y = int(470 * self.resolution_ratio_y // 2400) - self.operation.click(self.device_id, close_x, close_y) - self._log_kv( - "粉丝团处理", - "关闭详情页", - x=close_x, - y=close_y, - base_x=500, - base_y=470, - ) - self.operation.delay(1.0) - except Exception as exc: - self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc)) - - # 如果启用了自动加入,等待页面加载后再次点击 - if getattr(self, "auto_join_fansclub", False): - self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载") - self.operation.delay(1.0) - try: - stage_after, _ = self._diagnose_stage_from_current_screen() - if stage_after == "FANSCLUB_JOIN": - preset_x = int(527 * self.resolution_ratio_x // 1080) - preset_y = int(567 * self.resolution_ratio_y // 2400) - self.operation.click(self.device_id, preset_x, preset_y) - self._log_kv( - "粉丝团处理", - "仍在粉丝团加入页,再次第一次点击", - x=preset_x, - y=preset_y, - base_x=527, - base_y=567, - ) - self.operation.delay(0.5) - self.operation.click(self.device_id, preset_x, preset_y) - self._log_kv( - "粉丝团处理", - "仍在粉丝团加入页,再次第二次点击", - x=preset_x, - y=preset_y, - base_x=527, - base_y=567, - ) - self.operation.delay(2.0) - - # 加入粉丝团成功后,点击 (527, 567) 返回直播间 - try: - return_x = int(527 * self.resolution_ratio_x // 1080) - return_y = int(567 * self.resolution_ratio_y // 2400) - self.operation.click(self.device_id, return_x, return_y) - self._log_kv( - "粉丝团处理", - "加入粉丝团成功后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - self.operation.delay(1.0) - except Exception as exc_inner: - self._log_kv( - "粉丝团处理", - "点击返回直播间失败", - error=str(exc_inner), - ) - except Exception: - pass - else: - self._log_kv( - "粉丝团处理", - "未启用自动加入粉丝团,等待手动确认", - wait_seconds=15, - ) - self.operation.delay(15.0) - - # 未启用自动加入时,也需要在等待后点击返回 - try: - return_x = int(527 * self.resolution_ratio_x // 1080) - return_y = int(567 * self.resolution_ratio_y // 2400) - self.operation.click(self.device_id, return_x, return_y) - self._log_kv( - "粉丝团处理", - "加入粉丝团成功后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - self.operation.delay(1.0) - except Exception as exc_inner2: - self._log_kv( - "粉丝团处理", "点击返回直播间失败", error=str(exc_inner2) - ) - - # 延迟后返回,让主循环继续处理 - self.operation.delay(0.5) - - # 如果失败,根据配置决定是否切换直播间 - fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay") - if fansclub_fail_action == "switch": - self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间") - try: - self.swipe_up_to_next_live() - except Exception: - pass - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(处理粉丝团)", - elapsed_seconds=round(elapsed, 2), - ) + from .run_once_basic_fansclub import handle_fansclub_join as _impl + return _impl(self, start_time) def handle_just_recorded_reservation(self: "fudai_analyse", start_time: float) -> bool: @@ -951,545 +626,44 @@ def handle_reservation_check(self: "fudai_analyse", start_time: float) -> bool: 返回 True 表示有 return-out 出口被触发,caller 应当 `return`; 返回 False 表示走完所有逻辑后继续执行后续步骤。 """ - import json - import os - from datetime import datetime - - from douyin.reservation import douyin_reservation_logic - - try: - reservation_check_start = time.time() - self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start) - - # 第一次运行时清空预约队列 + 状态文件 - _maybe_clear_reservations_on_first_run(self) - - high_value_enabled = getattr(self, "high_value_fudai_enabled", False) - reservations_list = getattr(self, "reservations", None) - reservations_count = len(reservations_list) if reservations_list else 0 - - # 调试日志:检查触发条件 - _log_reservation_check_trigger( - self, high_value_enabled, reservations_list, reservations_count - ) - - if not high_value_enabled: - try: - self._log_kv( - "预约", - "[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查", - ) - except Exception: - pass - elif not reservations_list or reservations_count == 0: - try: - self._log_kv( - "预约", - "[预约] 预约队列为空,跳过预约回退检查", - reservations_is_none=(reservations_list is None), - reservations_count=reservations_count, - ) - except Exception: - pass - - if not (high_value_enabled and reservations_list): - return False - - # 启用 + 有预约:执行真正的检查 - return _run_reservation_attend_window(self, start_time) - except Exception: - return False + from .run_once_basic_reservation import handle_reservation_check as _impl + return _impl(self, start_time) -def _maybe_clear_reservations_on_first_run(self: "fudai_analyse") -> None: - """第一次进入 run_once_basic 时清空预约队列 + 状态文件,并标记非首次。""" - try: - is_first_run = getattr(self, "_first_run_once_basic", True) - # 记录清空前的队列状态(用于调试) - old_reservations_count = 0 - try: - old_reservations_count = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - except Exception: - pass +def run_once_basic_post_reservation(self: "fudai_analyse", start_time: float) -> None: + """run_once_basic 在预约检查之后的阶段处理总流程。""" + # 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后) + if handle_skip_stage_diagnosis(self, start_time): + return - if is_first_run: - try: - self._log_kv( - "预约", - "[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件", - old_reservations_count=old_reservations_count, - ) - except Exception: - pass - try: - before_clear = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - self.reservations = [] - after_clear = ( - len(self.reservations) - if hasattr(self, "reservations") - else 0 - ) + # 1. 截图 + 阶段诊断 + diag = screenshot_and_diagnose(self, start_time) + if diag is None: + return + stage, seen = diag - # 同时清空状态文件 - try: - state_path = getattr(self, "_reservations_state_path", None) - if state_path: - from douyin.reservation.douyin_reservation import ( - write_reservations_state, - ) + # 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复 + if handle_desktop_recovery(self): + return - write_reservations_state( - state_path=state_path, - reservations=[], - room_pos=0, - current_room_title="", - current_room_title_raw="", - reason="startup_clear", - ) - try: - self._log_kv( - "预约", - "[预约] 已清空预约队列并更新状态文件", - before_clear=before_clear, - after_clear=after_clear, - ) - except Exception: - pass - except Exception as exc: - try: - self._log_kv( - "预约", - "[预约] 清空状态文件时出错", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - except Exception as exc: - # 如果清空失败,尝试直接设置 - try: - if hasattr(self, "reservations"): - self.reservations = [] - self._log_kv( - "预约", - "[预约] 清空预约队列时出错,已尝试直接设置", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - try: - self._first_run_once_basic = False - except Exception: - pass - else: - try: - current_count = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - self._log_kv( - "预约", - "[预约] 非第一次运行,保持当前预约队列", - reservations_count=current_count, - is_first_run=False, - ) - except Exception: - pass - except Exception as exc: - try: - self._log_kv( - "预约", - "[预约] 初始化预约队列时出错", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass + # 2.0. 高价值房间重访检查(在处理其他状态之前) + if handle_high_value_room_revisit(self, start_time): + return + + # 处理弹窗 / 详情 / 直播间 / 推荐页 / 开奖结果 / 直播结束 阶段分发 + dispatch_stage_branch(self, stage, seen, start_time) -def _log_reservation_check_trigger( - self: "fudai_analyse", - high_value_enabled: bool, - reservations_list, - reservations_count: int, -) -> None: - """调试日志:检查预约回退逻辑的触发条件。""" - try: - from datetime import datetime as _dt +def handle_reservation_pipeline(self: "fudai_analyse", start_time: float) -> bool: + """run_once_basic 的预约处理聚合管线。""" + reservation_check_start = time.time() - reservations_detail = [] - if reservations_list: - for idx, r in enumerate(reservations_list[:3]): - try: - ft = float(r.get("future_ts") or 0) - ft_str = ( - _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - reservations_detail.append( - { - "index": idx, - "future_ts": int(ft) if ft > 0 else 0, - "future_str": ft_str, - "value": float(r.get("prize_value_yuan", 0)), - "pos_seen": int(r.get("pos_seen", 0)), - } - ) - except Exception: - pass - - self._log_kv( - "预约", - "[预约] run_once_basic:检查预约回退触发条件", - high_value_enabled=high_value_enabled, - reservations_count=reservations_count, - reservations_is_none=(reservations_list is None), - will_check_reservations=bool( - high_value_enabled and reservations_list - ), - reservations_detail=reservations_detail, - ) - except Exception: - pass - - -def _run_reservation_attend_window( - self: "fudai_analyse", start_time: float -) -> bool: - """已确认 high_value_enabled + 有预约:执行队列满处理 / 抢占逻辑。 - - 返回 True 表示触发了 return-out 出口(队列满等待 / 重置到第一个直播间)。 - """ - from douyin.reservation import douyin_reservation_logic - - def _swipe_down_once() -> None: - self.swipe_down_back_from_live() - - def _sort_reservations() -> None: - douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined] - - def _write_state() -> None: - _write_reservations_state(self) - - focus_ref = [float(self.reservation_focus_until_ts or 0.0)] - after_action_ref = [bool(self.reservation_after_action_pending or False)] - - def _seek_reservation_room(item: dict) -> bool: - try: - return bool( - self._seek_reservation_room(item, operation_type="预约") - ) - except Exception: - return False - - # 检查队列是否已满且需要等待 - max_reservations = int( - getattr(self, "high_value_fudai_max_reservations", 3) or 3 - ) - if ( - len(self.reservations) >= max_reservations - and not self.queue_full_waiting_at_earliest - ): - waiting = douyin_reservation_logic.handle_queue_full_wait_at_earliest( - analyser=self, - reservations=self.reservations, - room_pos=int(getattr(self, "room_pos", 0) or 0), - reservation_focus_until_ts_ref=focus_ref, - reservation_back_swipe_delay_s=float( - self.reservation_back_swipe_delay or 0.6 - ), - swipe_down_back_callback=_swipe_down_once, - seek_reservation_room_callback=_seek_reservation_room, - sort_reservations_callback=_sort_reservations, - write_state_callback=_write_state, - ) - if waiting: - self.queue_full_waiting_at_earliest = True - if focus_ref: - self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(预约队列满等待)", - elapsed_seconds=round(elapsed, 2), - ) - return True - - # 等待开奖 / 正在参与预约福袋 / 队列满等待 → 跳过预约回退检查 - if getattr(self, "_waiting_for_lottery_result", False): - try: - self._log_kv( - "预约", - "[预约] 正在等待开奖,跳过预约回退检查", - waiting_for_lottery=True, - ) - except Exception: - pass - elif getattr(self, "_current_attending_reservation_fudai", False): - try: - self._log_kv( - "预约", - "[预约] 正在参与预约福袋,跳过预约回退检查,避免被其他预约打断", - current_attending_reservation=True, - ) - except Exception: - pass - elif self.queue_full_waiting_at_earliest: - # 队列已满且正在等待最早开奖直播间,按正常等待逻辑处理 - pass - - # 检查是否所有预约已完成,需要重置到第一个直播间 - if self.queue_full_waiting_at_earliest and not self.reservations: - try: - self._log_kv( - "预约", - "[预约] 所有预约已完成,重置到第一个直播间", - ) - except Exception: - pass - self.queue_full_waiting_at_earliest = False - self.reservation_focus_until_ts = 0.0 - try: - current_pos = int(getattr(self, "room_pos", 0) or 0) - back_times = abs(current_pos) - if back_times > 100: - back_times = 100 - if back_times > 0: - for i in range(back_times): - _swipe_down_once() - self.operation.delay(0.6) - self.room_pos = 0 - if hasattr(self, "_swipe_times"): - self._swipe_times = 0 - try: - self._log_kv( - "预约", - "[预约] 已回退到第一个直播间", - back_times=back_times, - ) - except Exception: - pass - except Exception: - pass + if handle_reservation_check(self, start_time): return True - # 单间模式不启用预约回退 - try: - needswitch_cfg = bool(getattr(self, "needswitch", True)) - except Exception: - needswitch_cfg = True - - _log_reservation_attend_check(self, needswitch_cfg) - - if needswitch_cfg: - # 多间模式:调 process_reservation_attend_window - try: - self._log_kv( - "预约", - "[预约] 多间模式:开始调用 process_reservation_attend_window", - reservations_count=( - len(self.reservations) if self.reservations else 0 - ), - room_pos=int(getattr(self, "room_pos", 0) or 0), - ) - except Exception: - pass - - preempted = douyin_reservation_logic.process_reservation_attend_window( - analyser=self, - reservations=self.reservations, - room_pos=int(getattr(self, "room_pos", 0) or 0), - reservation_focus_until_ts_ref=focus_ref, - reservation_after_action_pending_ref=after_action_ref, - reservation_back_swipe_delay_s=float( - self.reservation_back_swipe_delay or 0.6 - ), - swipe_down_back_callback=_swipe_down_once, - seek_reservation_room_callback=_seek_reservation_room, - sort_reservations_callback=_sort_reservations, - write_state_callback=_write_state, - ) - - try: - self._log_kv( - "预约", - "[预约] process_reservation_attend_window 返回结果", - preempted=preempted, - focus_until=( - int(focus_ref[0]) - if focus_ref and focus_ref[0] > 0 - else 0 - ), - ) - except Exception: - pass - # 同步回写 ref 值 - if focus_ref: - self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) - if after_action_ref: - self.reservation_after_action_pending = bool(after_action_ref[0]) - - # 如果抢占成功,设置当前参与的福袋类型为预约福袋 - if preempted: - self._current_attending_reservation_fudai = True - else: - # 单间模式:清理过期预约 - try: - self._log_kv( - "预约", - "[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与", - reservations_count=( - len(self.reservations) if self.reservations else 0 - ), - ) - - douyin_reservation_logic.cleanup_expired_reservations( - self, self.reservations, _write_state - ) - except Exception as exc: - try: - self._log_kv( - "预约", - "[预约] 单间模式下清理过期预约时出错", - error=str(exc), - ) - except Exception: - pass + if handle_just_recorded_reservation(self, start_time): + return True + reservation_elapsed = time.time() - reservation_check_start + self._log_kv("预约", f"预约检查完成,耗时: {reservation_elapsed:.3f}s") return False - - -def _write_reservations_state(self: "fudai_analyse") -> None: - """把预约队列写入状态文件(节流 1s/次),供外部 GUI 跨进程查看。 - - 从 _run_reservation_attend_window 内嵌闭包抽出来,行为不变。 - 依赖 self 上的 _reservations_state_path / _reservations_state_last_write_ts / - reservations / current_room_title* / room_pos / _log_kv。 - """ - import json - import os - from datetime import datetime - - try: - # 节流:避免高频写盘 - now_ts = time.time() - last_ts = float( - getattr(self, "_reservations_state_last_write_ts", 0.0) or 0.0 - ) - if (now_ts - last_ts) < 1.0: - return - self._reservations_state_last_write_ts = now_ts - - os.makedirs( - os.path.dirname(self._reservations_state_path), - exist_ok=True, - ) - - items = [] - for r in self.reservations or []: - try: - ft = float(r.get("future_ts") or 0) - except Exception: - ft = 0.0 - try: - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft - else "" - ) - except Exception: - ft_str = str(r.get("future_str", "")) - - items.append( - { - "prize_value_yuan": float(r.get("prize_value_yuan") or 0), - "content": str(r.get("content") or ""), - "future_ts": ft, - "future_str": ft_str, - "pos_seen": int(r.get("pos_seen") or 0), - "room_title": str(r.get("room_title", "") or ""), - "room_title_raw": str(r.get("room_title_raw", "") or ""), - "created_ts": float(r.get("created_ts") or 0), - } - ) - - current_title = str(getattr(self, "current_room_title", "") or "") - current_title_raw = str(getattr(self, "current_room_title_raw", "") or "") - - data = { - "updated_ts": time.time(), - "reason": "process_reservation", - "room_pos": int(getattr(self, "room_pos", 0) or 0), - "current_room_title": current_title, - "current_room_title_raw": current_title_raw, - "reservations": items, - } - - with open(self._reservations_state_path, "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=2) - except Exception as exc: - try: - self._log_kv( - "预约", - "写入预约队列状态文件失败", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - - -def _log_reservation_attend_check( - self: "fudai_analyse", needswitch_cfg: bool -) -> None: - """调试日志:检查 needswitch 和第一个预约的详细信息。""" - try: - from datetime import datetime as _dt - - first_reservation_info = {} - if self.reservations and len(self.reservations) > 0: - first_r = self.reservations[0] - try: - ft = float(first_r.get("future_ts") or 0) - now_ts = time.time() - ft_str = ( - _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - remain_seconds = int(ft - now_ts) if ft > 0 else 0 - first_reservation_info = { - "future_ts": int(ft) if ft > 0 else 0, - "future_str": ft_str, - "value": float(first_r.get("prize_value_yuan", 0)), - "pos_seen": int(first_r.get("pos_seen", 0)), - "remain_seconds": remain_seconds, - "current_room_pos": int( - getattr(self, "room_pos", 0) or 0 - ), - } - except Exception: - pass - - self._log_kv( - "预约", - "[预约] run_once_basic:检查预约回退条件", - needswitch_cfg=needswitch_cfg, - reservations_count=( - len(self.reservations) if self.reservations else 0 - ), - first_reservation=first_reservation_info, - ) - except Exception: - pass diff --git a/douyin/core/fudai_modules/run_once_basic_reservation.py b/douyin/core/fudai_modules/run_once_basic_reservation.py new file mode 100644 index 0000000..2d3a6c5 --- /dev/null +++ b/douyin/core/fudai_modules/run_once_basic_reservation.py @@ -0,0 +1,427 @@ +"""run_once_basic 预约检查相关辅助逻辑。""" +from __future__ import annotations + +import json +import os +import time +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_reservation_check(self: "fudai_analyse", start_time: float) -> bool: + """0.1 高价值预约检查:清空队列 / 处理队列已满 / 调 process_reservation_attend_window。""" + try: + reservation_check_start = time.time() + self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start) + + _maybe_clear_reservations_on_first_run(self) + + high_value_enabled = getattr(self, "high_value_fudai_enabled", False) + reservations_list = getattr(self, "reservations", None) + reservations_count = len(reservations_list) if reservations_list else 0 + _log_reservation_check_trigger( + self, high_value_enabled, reservations_list, reservations_count + ) + + if not high_value_enabled: + try: + self._log_kv( + "预约", + "[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查", + ) + except Exception: + pass + elif not reservations_list or reservations_count == 0: + try: + self._log_kv( + "预约", + "[预约] 预约队列为空,跳过预约回退检查", + reservations_is_none=(reservations_list is None), + reservations_count=reservations_count, + ) + except Exception: + pass + + if not (high_value_enabled and reservations_list): + return False + return _run_reservation_attend_window(self, start_time) + except Exception: + return False + + +def _maybe_clear_reservations_on_first_run(self: "fudai_analyse") -> None: + try: + is_first_run = getattr(self, "_first_run_once_basic", True) + old_reservations_count = 0 + try: + old_reservations_count = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + except Exception: + pass + + if is_first_run: + try: + self._log_kv( + "预约", + "[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件", + old_reservations_count=old_reservations_count, + ) + except Exception: + pass + try: + before_clear = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + self.reservations = [] + after_clear = len(self.reservations) if hasattr(self, "reservations") else 0 + + try: + state_path = getattr(self, "_reservations_state_path", None) + if state_path: + from douyin.reservation.douyin_reservation import write_reservations_state + + write_reservations_state( + state_path=state_path, + reservations=[], + room_pos=0, + current_room_title="", + current_room_title_raw="", + reason="startup_clear", + ) + try: + self._log_kv( + "预约", + "[预约] 已清空预约队列并更新状态文件", + before_clear=before_clear, + after_clear=after_clear, + ) + except Exception: + pass + except Exception as exc: + try: + self._log_kv( + "预约", + "[预约] 清空状态文件时出错", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + except Exception as exc: + try: + if hasattr(self, "reservations"): + self.reservations = [] + self._log_kv( + "预约", + "[预约] 清空预约队列时出错,已尝试直接设置", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + try: + self._first_run_once_basic = False + except Exception: + pass + else: + try: + current_count = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + self._log_kv( + "预约", + "[预约] 非第一次运行,保持当前预约队列", + reservations_count=current_count, + is_first_run=False, + ) + except Exception: + pass + except Exception as exc: + try: + self._log_kv( + "预约", + "[预约] 初始化预约队列时出错", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + + +def _log_reservation_check_trigger( + self: "fudai_analyse", + high_value_enabled: bool, + reservations_list, + reservations_count: int, +) -> None: + try: + from datetime import datetime as _dt + + reservations_detail = [] + if reservations_list: + for idx, r in enumerate(reservations_list[:3]): + try: + ft = float(r.get("future_ts") or 0) + ft_str = _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + reservations_detail.append( + { + "index": idx, + "future_ts": int(ft) if ft > 0 else 0, + "future_str": ft_str, + "value": float(r.get("prize_value_yuan", 0)), + "pos_seen": int(r.get("pos_seen", 0)), + } + ) + except Exception: + pass + + self._log_kv( + "预约", + "[预约] run_once_basic:检查预约回退触发条件", + high_value_enabled=high_value_enabled, + reservations_count=reservations_count, + reservations_is_none=(reservations_list is None), + will_check_reservations=bool(high_value_enabled and reservations_list), + reservations_detail=reservations_detail, + ) + except Exception: + pass + + +def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) -> bool: + from douyin.reservation import douyin_reservation_logic + + def _swipe_down_once() -> None: + self.swipe_down_back_from_live() + + def _sort_reservations() -> None: + douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined] + + def _write_state() -> None: + _write_reservations_state(self) + + focus_ref = [float(self.reservation_focus_until_ts or 0.0)] + after_action_ref = [bool(self.reservation_after_action_pending or False)] + + def _seek_reservation_room(item: dict) -> bool: + try: + return bool(self._seek_reservation_room(item, operation_type="预约")) + except Exception: + return False + + max_reservations = int(getattr(self, "high_value_fudai_max_reservations", 3) or 3) + if len(self.reservations) >= max_reservations and not self.queue_full_waiting_at_earliest: + waiting = douyin_reservation_logic.handle_queue_full_wait_at_earliest( + analyser=self, + reservations=self.reservations, + room_pos=int(getattr(self, "room_pos", 0) or 0), + reservation_focus_until_ts_ref=focus_ref, + reservation_back_swipe_delay_s=float(self.reservation_back_swipe_delay or 0.6), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + if waiting: + self.queue_full_waiting_at_earliest = True + if focus_ref: + self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) + elapsed = time.time() - start_time + self._log_kv("流程", "run_once_basic完成(预约队列满等待)", elapsed_seconds=round(elapsed, 2)) + return True + + if getattr(self, "_waiting_for_lottery_result", False): + try: + self._log_kv("预约", "[预约] 正在等待开奖,跳过预约回退检查", waiting_for_lottery=True) + except Exception: + pass + elif getattr(self, "_current_attending_reservation_fudai", False): + try: + self._log_kv( + "预约", + "[预约] 正在参与预约福袋,跳过预约回退检查,避免被其他预约打断", + current_attending_reservation=True, + ) + except Exception: + pass + + if self.queue_full_waiting_at_earliest and not self.reservations: + try: + self._log_kv("预约", "[预约] 所有预约已完成,重置到第一个直播间") + except Exception: + pass + self.queue_full_waiting_at_earliest = False + self.reservation_focus_until_ts = 0.0 + try: + current_pos = int(getattr(self, "room_pos", 0) or 0) + back_times = min(abs(current_pos), 100) + if back_times > 0: + for _ in range(back_times): + _swipe_down_once() + self.operation.delay(0.6) + self.room_pos = 0 + if hasattr(self, "_swipe_times"): + self._swipe_times = 0 + try: + self._log_kv("预约", "[预约] 已回退到第一个直播间", back_times=back_times) + except Exception: + pass + except Exception: + pass + return True + + try: + needswitch_cfg = bool(getattr(self, "needswitch", True)) + except Exception: + needswitch_cfg = True + + _log_reservation_attend_check(self, needswitch_cfg) + + if needswitch_cfg: + try: + self._log_kv( + "预约", + "[预约] 多间模式:开始调用 process_reservation_attend_window", + reservations_count=(len(self.reservations) if self.reservations else 0), + room_pos=int(getattr(self, "room_pos", 0) or 0), + ) + except Exception: + pass + + preempted = douyin_reservation_logic.process_reservation_attend_window( + analyser=self, + reservations=self.reservations, + room_pos=int(getattr(self, "room_pos", 0) or 0), + reservation_focus_until_ts_ref=focus_ref, + reservation_after_action_pending_ref=after_action_ref, + reservation_back_swipe_delay_s=float(self.reservation_back_swipe_delay or 0.6), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + + try: + self._log_kv( + "预约", + "[预约] process_reservation_attend_window 返回结果", + preempted=preempted, + focus_until=(int(focus_ref[0]) if focus_ref and focus_ref[0] > 0 else 0), + ) + except Exception: + pass + if focus_ref: + self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) + if after_action_ref: + self.reservation_after_action_pending = bool(after_action_ref[0]) + if preempted: + self._current_attending_reservation_fudai = True + else: + try: + self._log_kv( + "预约", + "[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与", + reservations_count=(len(self.reservations) if self.reservations else 0), + ) + douyin_reservation_logic.cleanup_expired_reservations(self, self.reservations, _write_state) + except Exception as exc: + try: + self._log_kv("预约", "[预约] 单间模式下清理过期预约时出错", error=str(exc)) + except Exception: + pass + + return False + + +def _write_reservations_state(self: "fudai_analyse") -> None: + from datetime import datetime + + try: + now_ts = time.time() + last_ts = float(getattr(self, "_reservations_state_last_write_ts", 0.0) or 0.0) + if (now_ts - last_ts) < 1.0: + return + self._reservations_state_last_write_ts = now_ts + os.makedirs(os.path.dirname(self._reservations_state_path), exist_ok=True) + + items = [] + for r in self.reservations or []: + try: + ft = float(r.get("future_ts") or 0) + except Exception: + ft = 0.0 + try: + ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else "" + except Exception: + ft_str = str(r.get("future_str", "")) + items.append( + { + "prize_value_yuan": float(r.get("prize_value_yuan") or 0), + "content": str(r.get("content") or ""), + "future_ts": ft, + "future_str": ft_str, + "pos_seen": int(r.get("pos_seen") or 0), + "room_title": str(r.get("room_title", "") or ""), + "room_title_raw": str(r.get("room_title_raw", "") or ""), + "created_ts": float(r.get("created_ts") or 0), + } + ) + + data = { + "updated_ts": time.time(), + "reason": "process_reservation", + "room_pos": int(getattr(self, "room_pos", 0) or 0), + "current_room_title": str(getattr(self, "current_room_title", "") or ""), + "current_room_title_raw": str(getattr(self, "current_room_title_raw", "") or ""), + "reservations": items, + } + with open(self._reservations_state_path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + except Exception as exc: + try: + self._log_kv("预约", "写入预约队列状态文件失败", error=str(exc), error_type=type(exc).__name__) + except Exception: + pass + + +def _log_reservation_attend_check(self: "fudai_analyse", needswitch_cfg: bool) -> None: + try: + from datetime import datetime as _dt + + first_reservation_info = {} + if self.reservations and len(self.reservations) > 0: + first_r = self.reservations[0] + try: + ft = float(first_r.get("future_ts") or 0) + now_ts = time.time() + ft_str = _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + remain_seconds = int(ft - now_ts) if ft > 0 else 0 + first_reservation_info = { + "future_ts": int(ft) if ft > 0 else 0, + "future_str": ft_str, + "value": float(first_r.get("prize_value_yuan", 0)), + "pos_seen": int(first_r.get("pos_seen", 0)), + "remain_seconds": remain_seconds, + "current_room_pos": int(getattr(self, "room_pos", 0) or 0), + } + except Exception: + pass + + self._log_kv( + "预约", + "[预约] run_once_basic:检查预约回退条件", + needswitch_cfg=needswitch_cfg, + reservations_count=(len(self.reservations) if self.reservations else 0), + first_reservation=first_reservation_info, + ) + except Exception: + pass diff --git a/douyin/core/fudai_modules/run_once_basic_stage.py b/douyin/core/fudai_modules/run_once_basic_stage.py new file mode 100644 index 0000000..fbab095 --- /dev/null +++ b/douyin/core/fudai_modules/run_once_basic_stage.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_desktop_recovery(self: "fudai_analyse") -> bool: + """桌面检测自救:若不在抖音前台则恢复并重跑一次 run_once_basic。""" + from douyin.core import recovery as _recovery + + try: + top_pkg = "" + try: + top_pkg = self.operation.get_top_package(self.device_id) or "" + self._log_kv("自救", "桌面检测:获取前台包名", top_pkg=top_pkg) + except Exception as exc: + top_pkg = "" + self._log_kv("自救", "桌面检测:获取前台包名失败", error=str(exc)) + + if top_pkg and not _recovery.is_douyin_foreground(top_pkg): + self._log_kv("自救", "桌面检测:检测到不在抖音前台", top_pkg=top_pkg, is_douyin=False) + try: + self._log_kv("自救", "发现前台包不在抖音,尝试通过包名启动抖音", top_pkg=top_pkg) + _recovery.recover_to_douyin(self, log=lambda msg: self._log_kv("自救", msg)) + try: + self._log_kv("流程", "run_once_basic:自救完成,立即重新执行一次主流程") + except Exception: + pass + try: + self.operation.delay(0.5) + except Exception: + time.sleep(0.5) + self.run_once_basic() + return True + except Exception as exc2: + try: + self._log_kv("自救", "恢复失败", error=str(exc2), error_type=type(exc2).__name__) + except Exception: + pass + except Exception as exc: + try: + self._log_kv("自救", "桌面检测异常", error=str(exc), error_type=type(exc).__name__) + except Exception: + pass + return False + + +def screenshot_and_diagnose(self: "fudai_analyse", start_time: float): + """截图 + 阶段诊断;失败时返回 None。""" + screenshot_start = time.time() + max_screenshot_retries = 3 + ok = False + + for retry in range(max_screenshot_retries): + ok = self.operation.get_screenshot(self.device_id, use_service=False) + if ok: + break + if retry < max_screenshot_retries - 1: + self._log_kv( + "截图", + f"截图失败,重试中 ({retry + 1}/{max_screenshot_retries})", + retry=retry + 1, + max_retries=max_screenshot_retries, + ) + try: + self.operation.delay(1.0) + except Exception: + time.sleep(1.0) + + screenshot_elapsed = time.time() - screenshot_start + if not ok: + elapsed = time.time() - start_time + self._log_kv( + "截图", + "获取截图失败(多次重试后仍失败)", + ok=0, + retries=max_screenshot_retries, + elapsed_seconds=round(elapsed, 2), + screenshot_elapsed_seconds=round(screenshot_elapsed, 2), + reservation_after_action_pending=bool(getattr(self, "reservation_after_action_pending", False)), + reservation_focus_until_ts=float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0), + waiting_for_lottery=bool(getattr(self, "_waiting_for_lottery_result", False)), + room_pos=int(getattr(self, "room_pos", 0) or 0), + suggestion="检查设备连接状态和ADB服务", + ) + return None + + try: + self._log_kv( + "阶段诊断", + "调用阶段诊断-前置检查", + trigger_reason="run_once_basic_initial", + fudai_detail_task_count_from_stage=getattr(self, "_fudai_detail_task_count_from_stage", None), + screenshot_ready_for_ocr=bool(getattr(self, "_screenshot_ready_for_ocr", False)), + ) + except Exception: + pass + + stage, seen = self._diagnose_stage_from_current_screen(trigger_reason="run_once_basic_initial") + self._last_diag_stage = stage + self._last_diag_seen = seen + self._last_diag_ts = time.time() + elapsed = time.time() - start_time + self._log_kv( + "截图", + "截图+阶段诊断", + stage=stage, + seen=seen, + elapsed_seconds=round(elapsed, 2), + screenshot_elapsed_seconds=round(screenshot_elapsed, 2), + ) + return stage, seen + + +def handle_high_value_room_revisit(self: "fudai_analyse", start_time: float) -> bool: + """高价值房间重访检查。返回 True 表示重访成功并应结束本轮。""" + try: + revisit_enabled = bool(getattr(self, "high_value_room_revisit_enabled", False)) + only_current_run = bool(getattr(self, "high_value_room_revisit_only_current_run", False)) + if not revisit_enabled: + return False + + from douyin.other import douyin_high_value_room + + should_revisit = douyin_high_value_room.should_trigger_revisit( + analyser=self, + revisit_enabled=revisit_enabled, + only_current_run=only_current_run, + min_interval_seconds=getattr(self, "high_value_room_revisit_min_interval_seconds", 300), + max_revisit_per_run=getattr(self, "high_value_room_revisit_max_per_run", 5), + ) + if not should_revisit: + return False + + candidates = douyin_high_value_room.get_revisit_candidates( + analyser=self, + only_current_run=only_current_run, + min_prize_value=getattr(self, "high_value_room_revisit_min_prize_value", 0.0), + max_age_days=getattr(self, "high_value_room_revisit_max_age_days", 30), + ) + if not candidates: + return False + + target_room = candidates[0] + self._log_kv( + "高价值房间", + "[重访] 触发高价值房间重访", + target_room_title=target_room.get("room_title", "")[:30], + max_prize_value=target_room.get("max_prize_value_yuan", 0), + candidates_count=len(candidates), + ) + + revisit_success = douyin_high_value_room.execute_room_revisit(analyser=self, target_room=target_room) + if revisit_success: + elapsed = time.time() - start_time + self._log_kv("流程", "run_once_basic完成(高价值房间重访成功)", elapsed_seconds=round(elapsed, 2)) + return True + + self._log_kv("高价值房间", "[重访] 高价值房间重访失败,继续正常流程") + except Exception as exc: + try: + self._log_kv( + "高价值房间", + "[重访] 高价值房间重访检查异常", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + return False + diff --git a/douyin/core/fudai_modules/run_once_basic_waiting.py b/douyin/core/fudai_modules/run_once_basic_waiting.py new file mode 100644 index 0000000..3fc526d --- /dev/null +++ b/douyin/core/fudai_modules/run_once_basic_waiting.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..douyin_fudai import fudai_analyse + + +def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float) -> bool: + if not getattr(self, "_waiting_for_lottery_result", False): + return False + + wait_lottery_start = time.time() + try: + future_ts = getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0 + current_ts = time.time() + timeout_ts = future_ts + 10.0 + + if current_ts >= timeout_ts: + self._waiting_for_lottery_result = False + self._current_attending_reservation_fudai = False + timeout_seconds = int(current_ts - future_ts) + self._log_kv( + "参与", + f"等待开奖超时(超过开奖时间{timeout_seconds}秒),清除等待标志,继续执行其他操作", + 超时秒数=timeout_seconds, + 等待开奖总耗时=round(time.time() - wait_lottery_start, 2), + ) + return False + + wait_start_ts = getattr(self, "_lottery_wait_start_ts", future_ts) + passed_seconds = int(current_ts - wait_start_ts) + self._log_kv("参与", f"等待开奖结果中,持续OCR检测,已等待{passed_seconds}秒", 已等待秒数=passed_seconds) + + deadline_ts = timeout_ts + attempt = 0 + consecutive_none = 0 + interval = 0.5 + + while time.time() <= deadline_ts: + attempt += 1 + loop_start = time.time() + try: + try: + screenshot_start = time.time() + self.operation.get_screenshot(self.device_id) + self._log_kv("截图", "等待开奖期间截图", elapsed_seconds=round(time.time() - screenshot_start, 2)) + except Exception: + pass + ocr_start = time.time() + result = self._check_lottery_result_by_ocr() + self._log_kv("OCR", "等待开奖期间OCR检测", elapsed_seconds=round(time.time() - ocr_start, 2)) + except Exception as e: + result = None + try: + self._log_kv("参与", "等待开奖期间OCR检测出错,继续重试", error=str(e)) + except Exception: + pass + + if result: + self._waiting_for_lottery_result = False + self._current_attending_reservation_fudai = False + try: + self._log_kv("参与", "等待期间检测到开奖结果,开始处理", attempt=attempt, 等待开奖总耗时=round(time.time() - wait_lottery_start, 2)) + except Exception: + pass + self._handle_lottery_result_by_ocr(result) + elapsed = time.time() - start_time + try: + self._log_kv("流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2)) + except Exception: + pass + return True + + consecutive_none += 1 + now_ts_inner = time.time() + remain_to_deadline = int(max(0, deadline_ts - now_ts_inner)) + try: + self._log_kv("参与", "等待开奖连续检测:未识别到结果", attempt=attempt, remain_seconds=remain_to_deadline, 单次检测耗时=round(time.time() - loop_start, 2)) + except Exception: + pass + + spent = time.time() - loop_start + to_sleep = max(0.0, interval - spent) + if to_sleep > 0: + if time.time() + to_sleep > deadline_ts: + break + self.operation.delay(to_sleep) + + self._waiting_for_lottery_result = False + self._current_attending_reservation_fudai = False + try: + self._log_kv("参与", "等待开奖连续检测结束:未识别到开奖结果,清除等待标志", attempts=attempt, consecutive_none=consecutive_none, 等待开奖总耗时=round(time.time() - wait_lottery_start, 2)) + except Exception: + pass + + try: + needswitch = bool(getattr(self, "needswitch", True)) + except Exception: + needswitch = True + + if needswitch: + try: + self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋", color="RED") + except Exception: + pass + self.swipe_up_to_next_live() + + elapsed = time.time() - start_time + try: + self._log_kv("流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2)) + except Exception: + pass + return True + except Exception as exc: + self._log_kv("参与", "等待开奖检测时出错", error=str(exc)) + self._waiting_for_lottery_result = False + self._current_attending_reservation_fudai = False + return False + + +def handle_no_attend_timeout(self: "fudai_analyse", start_time: float) -> bool: + try: + last_attend_ts = float(getattr(self, "_last_successful_attend_ts", 0.0) or 0.0) + timeout_minutes = float(getattr(self, "_no_attend_timeout_minutes", 30.0) or 30.0) + current_ts = time.time() + run_start_ts = float(getattr(self, "_run_start_ts", current_ts) or current_ts) + + if last_attend_ts > 0: + elapsed_minutes = (current_ts - last_attend_ts) / 60.0 + if elapsed_minutes >= timeout_minutes: + try: + self._log_kv("超时", "30分钟未参与成功福袋,返回推荐页面重新进入直播间", last_attend_minutes_ago=round(elapsed_minutes, 1)) + except Exception: + pass + self._return_to_recommend_and_reenter_live() + try: + self._last_successful_attend_ts = current_ts + except Exception: + pass + elapsed = time.time() - start_time + self._log_kv("流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2)) + return True + else: + elapsed_minutes = (current_ts - run_start_ts) / 60.0 + if elapsed_minutes >= timeout_minutes: + try: + self._log_kv("超时", f"运行{round(elapsed_minutes, 1)}分钟仍未参与成功福袋,返回推荐页面重新进入直播间", run_minutes=round(elapsed_minutes, 1)) + except Exception: + pass + self._return_to_recommend_and_reenter_live() + elapsed = time.time() - start_time + self._log_kv("流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2)) + return True + except Exception as exc: + try: + self._log_kv("超时", "检查30分钟超时时出错", error=str(exc)) + except Exception: + pass + return False diff --git a/douyin/core/underlying_operations.py b/douyin/core/underlying_operations.py index d93a974..42f3b27 100644 --- a/douyin/core/underlying_operations.py +++ b/douyin/core/underlying_operations.py @@ -32,6 +32,7 @@ import contextlib import base64 from typing import Tuple, Optional, Any +from douyin.core import path_config # Pillow 版本兼容:使用 Image.Resampling 或回退到 Image 常量 try: @@ -90,6 +91,30 @@ from douyin.core.underlying_operations_pkg import ( _swipe_with_sendevent_improved as _impl_swipe_sendevent_improved, select_device as _impl_select_device, analyse_pic_digits as _impl_analyse_pic_digits, + paste_from_clipboard as _impl_paste_from_clipboard, + input_text as _impl_input_text, + paste_text as _impl_paste_text, + get_current_ime as _impl_get_current_ime, + list_imes as _impl_list_imes, + ensure_adbkeyboard_ime as _impl_ensure_adbkeyboard_ime, + restore_ime as _impl_restore_ime, + try_set_ime as _impl_try_set_ime, + _adbkeyboard_broadcast as _impl_adbkeyboard_broadcast, + _adbkeyboard_broadcast_int as _impl_adbkeyboard_broadcast_int, + keyevent as _impl_keyevent, + adbkeyboard_editor_action as _impl_adbkeyboard_editor_action, + confirm_from_keyboard as _impl_confirm_from_keyboard, + input_text_adbkeyboard as _impl_input_text_adbkeyboard, + paste_text_at as _impl_paste_text_at, + uiautomator_dump as _impl_uiautomator_dump, + tap_by_text as _impl_tap_by_text, + tap_close_icon as _impl_tap_close_icon, + get_top_package as _impl_get_top_package, + launch_package as _impl_launch_package, + is_douyin_foreground as _impl_is_douyin_foreground, +) +from douyin.core.underlying_operations_pkg.screenshot_pipeline import ( + get_screenshot as _impl_get_screenshot, ) class underlying_operations: """底层操作类""" @@ -104,6 +129,9 @@ class underlying_operations: # 线程安全锁 self._ocr_lock = threading.RLock() # 保护 OCR 初始化 self._ocr_coords_lock = threading.Lock() # 保护坐标缓存 + # 并行 OCR:每个工作线程使用独立实例,避免共享同一实例导致底层并发崩溃 + self._ocr_thread_local = threading.local() + self._ocr_instance_build_lock = threading.Lock() # 默认使用CPU模式(删除GPU检测) self._gpu_available = False @@ -213,202 +241,90 @@ class underlying_operations: self.ocr = None self.ocr_type = None + def _get_ocr_for_current_thread(self) -> tuple[Any, Any]: + """返回当前线程应使用的 OCR 实例。 + + 规则: + - 主线程/显式强制共享:复用 self.ocr; + - 并行工作线程:懒初始化线程私有 OCR 实例(仍保持并行执行)。 + """ + self._ensure_ocr() + if self.ocr is None: + return None, None + + try: + force_shared = str( + os.environ.get("OCR_PARALLEL_SHARE_INSTANCE", "0") + ).strip().lower() in ("1", "true", "yes", "on") + except Exception: + force_shared = False + + cur_thread = threading.current_thread() + if force_shared or cur_thread is threading.main_thread(): + return self.ocr, self.ocr_type + + tl = self._ocr_thread_local + ocr_obj = getattr(tl, "ocr", None) + ocr_type = getattr(tl, "ocr_type", None) + if ocr_obj is not None and ocr_type == self.ocr_type: + return ocr_obj, ocr_type + + with self._ocr_instance_build_lock: + # double-check:避免同线程重复初始化 + ocr_obj = getattr(tl, "ocr", None) + ocr_type = getattr(tl, "ocr_type", None) + if ocr_obj is not None and ocr_type == self.ocr_type: + return ocr_obj, ocr_type + + try: + from operations.ocr_operations import ( + _build_easyocr, # noqa: WPS433 + _build_paddle, # noqa: WPS433 + ) + except Exception: + _build_paddle = None + _build_easyocr = None + + try: + if self.ocr_type == "paddleocr" and _build_paddle is not None: + ocr_obj = _build_paddle() + ocr_type = "paddleocr" + elif self.ocr_type == "easyocr" and _build_easyocr is not None: + ocr_obj = _build_easyocr() + ocr_type = "easyocr" + elif _build_easyocr is not None: + # 主实例类型未知/不可用时,用 easyocr 兜底,保持线程可继续工作 + ocr_obj = _build_easyocr() + ocr_type = "easyocr" + else: + ocr_obj = self.ocr + ocr_type = self.ocr_type + except Exception as e: + _uo_log( + f"[OCR] 并行线程独立实例初始化失败,回退共享实例: {type(e).__name__}: {e}", + "WARNING", + ) + ocr_obj = self.ocr + ocr_type = self.ocr_type + + tl.ocr = ocr_obj + tl.ocr_type = ocr_type + try: + _uo_log( + f"[OCR] 并行线程OCR实例就绪 thread={cur_thread.name} type={ocr_type}", + "DEBUG", + ) + except Exception: + pass + return ocr_obj, ocr_type + def select_device(self): return _impl_select_device() def _find_pic_path(self, picname: str, for_reading: bool = True): return _impl_find_pic_path(picname, for_reading) def get_screenshot(self, device_id, path="pic", use_service: bool = False): - """截图(支持后台服务模式) - - 参数: - device_id: 设备ID - path: 路径(默认"pic") - use_service: 是否使用后台截图服务(默认False,强制使用直接截图) - - 返回: - 是否成功获取截图 - """ - start_ts = time_module.time() - # Diagnostic: record pre-call info including caller stack (top frames) - try: - import inspect, json, threading - - frames = [] - for fr in inspect.stack()[1:9]: - frame_info = { - "file": os.path.relpath(fr.filename, os.path.dirname(__file__)), - "line": fr.lineno, - "function": fr.function, - } - frames.append(frame_info) - - pre_record = { - "ts": datetime.now().isoformat(), - "device_id": device_id, - "use_service": bool(use_service), - "path": path, - "phase": "start", - "thread": threading.get_ident(), - "stack": frames, - } - # cache in memory - try: - if hasattr(self, "_screenshot_call_cache"): - try: - self._screenshot_call_cache.append(pre_record) - except Exception: - pass - except Exception: - pass - - # append JSON line to log file - try: - log_dir = os.path.join(os.path.dirname(__file__), "logs") - os.makedirs(log_dir, exist_ok=True) - with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: - _lf.write(json.dumps(pre_record, ensure_ascii=False) + "\n") - except Exception: - pass - except Exception: - pass - service_success = False - # 如果启用服务模式,使用后台截图服务;若服务不可用或返回 False,则回退到直接截图 - if use_service: - try: - from operations.screenshot_service import ScreenshotService - - service = ScreenshotService.get_instance() - - # 诊断:检查服务是否在运行 - service_running = getattr(service, "_running", False) - if not service_running: - logging.debug( - "[截图] 后台服务未运行,尝试启动 device=%s", device_id - ) - try: - service.start(device_id, interval=1.5) - # 等待一小段时间让服务完成第一次截图 - time_module.sleep(0.2) - except Exception as start_err: - logging.warning( - "[截图] 启动后台服务失败: %s,将使用直接截图", start_err - ) - - try: - if service.get_screenshot(device_id, force=False): - dur = (time_module.time() - start_ts) * 1000.0 - logging.info( - "[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id - ) - # 写结束记录 - try: - import json, threading - - end_record = { - "ts": datetime.now().isoformat(), - "device_id": device_id, - "use_service": True, - "path": path, - "phase": "end", - "result": True, - "duration_ms": dur, - "thread": threading.get_ident(), - } - try: - if hasattr(self, "_screenshot_call_cache"): - self._screenshot_call_cache.append(end_record) - except Exception: - pass - try: - with open( - self._screenshot_log_path, "a", encoding="utf-8" - ) as _lf: - _lf.write( - json.dumps(end_record, ensure_ascii=False) - + "\n" - ) - except Exception: - pass - except Exception: - pass - # do not return here; let final return at function end - service_success = True - else: - timetag = datetime.now().strftime("%H:%M:%S") - logging.info( - "[%s] [截图操作] 后台服务未提供有效截图,回退到直接截图", - timetag, - ) - # 不 return,这里继续走直接截图逻辑 - except Exception as e: - timetag = datetime.now().strftime("%H:%M:%S") - logging.warning( - "[%s] [截图操作] 调用后台服务异常,回退到直接截图: %s", - timetag, - e, - ) - service_success = False - except ImportError as e: - timetag = datetime.now().strftime("%H:%M:%S") - logging.warning( - "[%s] [截图操作] 无法导入截图服务模块,回退到直接截图: %s", - timetag, - e, - ) - service_success = False - except Exception as e: - timetag = datetime.now().strftime("%H:%M:%S") - logging.warning( - "[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e - ) - service_success = False - - # 原有的直接截图逻辑(保持向后兼容),测量其耗时 - try: - # If result already set by service branch, skip direct call - if service_success: - final_result = True - else: - final_result = self._get_screenshot_direct(device_id, path) - except Exception: - final_result = False - - dur = (time_module.time() - start_ts) * 1000.0 - logging.info( - "[截图] 总耗时(ms)=%.1f use_service=%s result=%s", - dur, - bool(use_service), - final_result, - ) - - # 写结束记录(包含持续时长与结果) - try: - import json, threading - - end_record = { - "ts": datetime.now().isoformat(), - "device_id": device_id, - "use_service": bool(use_service), - "path": path, - "phase": "end", - "result": bool(final_result), - "duration_ms": dur, - "thread": threading.get_ident(), - } - try: - if hasattr(self, "_screenshot_call_cache"): - self._screenshot_call_cache.append(end_record) - except Exception: - pass - try: - with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: - _lf.write(json.dumps(end_record, ensure_ascii=False) + "\n") - except Exception: - pass - except Exception: - pass - - return bool(final_result) + """截图(支持后台服务模式)。""" + return _impl_get_screenshot(self, device_id, path, use_service) def _get_screenshot_direct(self, device_id, path="pic"): """直接截图(不使用服务模式)。 @@ -716,44 +632,7 @@ class underlying_operations: return False, "" def get_top_package(self, device_id: str) -> str: - """尝试返回当前处于前台的包名(如 com.ss.android.ugc.aweme)。 - - 失败返回空字符串。实现采用 dumpsys 输出的多种字段进行解析,兼容不同 Android 版本。 - """ - try: - ok, out = self._run_adb_shell_capture( - device_id, "dumpsys window windows", timeout_seconds=4.0 - ) - if ok and out: - for ln in (out or "").splitlines(): - if ( - "mCurrentFocus" in ln - or "mFocusedApp" in ln - or "mFocusedWindow" in ln - ): - m = re.search(r"([A-Za-z0-9_\.]+)\/", ln) - if m: - return m.group(1) - # 兜底尝试:activity 栈里的 resumed activity - ok2, out2 = self._run_adb_shell_capture( - device_id, "dumpsys activity activities", timeout_seconds=4.0 - ) - if ok2 and out2: - for ln in (out2 or "").splitlines(): - if "mResumedActivity" in ln or "ResumedActivity" in ln: - m = re.search(r"([A-Za-z0-9_\.]+)\/", ln) - if m: - return m.group(1) - except Exception: - pass - return "" - - # 抖音常见包名(从主到 lite/极速版/海外版),launch_package 默认按此顺序尝试 - DOUYIN_PACKAGES = ( - "com.ss.android.ugc.aweme", # 抖音正式版 - "com.ss.android.ugc.aweme.lite", # 抖音极速版 - "com.zhiliaoapp.musically", # TikTok(兼容) - ) + return _impl_get_top_package(self, device_id) def launch_package( self, @@ -761,425 +640,76 @@ class underlying_operations: package_name: str = "", timeout_seconds: float = 5.0, ) -> Tuple[bool, str]: - """通过包名启动应用。 - - 策略:先用 `monkey -p -c android.intent.category.LAUNCHER 1` 启动主 launcher activity, - 失败时回退到 `am start -n /.`(按抖音常用 activity 列表尝试)。 - - 参数: - device_id: ADB 设备 ID - package_name: 要启动的包名;留空则按 DOUYIN_PACKAGES 顺序尝试 - timeout_seconds: 单次 adb shell 命令超时 - - 返回: - (success, used_package) — used_package 为实际成功启动的包名(失败返回 "") - """ - candidates = ( - [package_name] if package_name else list(self.DOUYIN_PACKAGES) - ) - for pkg in candidates: - pkg = (pkg or "").strip() - if not pkg: - continue - # 1) monkey 主入口 - cmd = f"monkey -p {pkg} -c android.intent.category.LAUNCHER 1" - ok, out = self._run_adb_shell_capture( - device_id, cmd, timeout_seconds=timeout_seconds - ) - # monkey 失败时输出会包含 "No activities found" 或 "monkey aborted" - if ok and "No activities found" not in (out or "") and "aborted" not in ( - out or "" - ).lower(): - return True, pkg - # 2) am start 主入口兜底 - for activity in ( - ".main.MainActivity", - ".splash.SplashActivity", - ".main.homepage.MainActivity", - ): - am_cmd = f"am start -n {pkg}/{activity}" - if self._run_adb_shell( - device_id, am_cmd, timeout_seconds=timeout_seconds - ): - return True, pkg - return False, "" + return _impl_launch_package(self, device_id, package_name, timeout_seconds) def is_douyin_foreground(self, device_id: str) -> bool: - """便捷判断:当前前台是否是抖音相关包。""" - top_pkg = self.get_top_package(device_id) or "" - return bool(top_pkg) and ( - "aweme" in top_pkg - or "douyin" in top_pkg - or "com.ss.android.ugc" in top_pkg - ) + return _impl_is_douyin_foreground(self, device_id) def set_clipboard_text(self, device_id: str, text: str) -> bool: return _impl_set_clipboard_text(device_id, text) def paste_from_clipboard(self, device_id: str) -> bool: - """尝试触发“粘贴”操作(需要输入框已获得焦点)。""" - # KEYCODE_PASTE=279(部分机型/系统可能不支持,但无副作用) - return self._run_adb_shell(device_id, "input keyevent 279", timeout_seconds=2.0) + return _impl_paste_from_clipboard(self, device_id) def input_text(self, device_id: str, text: str) -> bool: - """使用 adb input text 输入(对中文可能不稳定,仅兜底)。""" - t = str(text or "") - if not t: - return False - # 空格用 %s,避免被 shell 分词 - t = t.replace(" ", "%s") - # 完整转义所有 shell 特殊字符 - for ch in ['&', '<', '>', '|', ';', '$', '`', "'", '"', '\\', '(', ')', '{', '}', '[', ']', '!', '#', '*', '?']: - t = t.replace(ch, '\\' + ch) - try: - return ( - subprocess.run( - self._adb_args(device_id, "shell", "input", "text", t), - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=5.0, - check=False, - ).returncode - == 0 - ) - except Exception: - return False + return _impl_input_text(self, device_id, text) def paste_text(self, device_id: str, text: str) -> bool: - """优先走剪贴板粘贴,其次兜底 input text。""" - if self.set_clipboard_text(device_id, text): - self.paste_from_clipboard(device_id) - return True - return self.input_text(device_id, text) + return _impl_paste_text(self, device_id, text) # ===== ADBKeyboard (可选) ===== def get_current_ime(self, device_id: str) -> str: - ok, out = self._run_adb_shell_capture( - device_id, "settings get secure default_input_method", timeout_seconds=2.0 - ) - if not ok: - return "" - return (out or "").strip() + return _impl_get_current_ime(self, device_id) def list_imes(self, device_id: str) -> list[str]: - # 部分 ROM 会限制 `ime` shell 命令(报 WRITE_SECURE_SETTINGS),这里优先用 settings 查询。 - ok, out = self._run_adb_shell_capture( - device_id, "settings get secure enabled_input_methods", timeout_seconds=2.5 - ) - if ok and out: - raw = (out or "").strip() - # 形如:a/.A:b/.B:c/.C - parts = [p.strip() for p in raw.split(":") if p.strip()] - if parts: - return parts - - ok2, out2 = self._run_adb_shell_capture( - device_id, "ime list -s", timeout_seconds=2.5 - ) - if not ok2: - # 最后兜底:至少把当前默认输入法返回,避免上层无法判断 - cur = self.get_current_ime(device_id) - return [cur] if cur else [] - lines = [ln.strip() for ln in (out2 or "").splitlines() if ln.strip()] - return lines + return _impl_list_imes(self, device_id) @staticmethod # type: ignore[misc] def _pick_adbkeyboard_ime(imes: list[str]) -> str: return _impl_pick_adbkeyboard_ime(imes) def ensure_adbkeyboard_ime( - self, device_id: str, preferred_ime: str = "com.android.adbkeyboard/.AdbIME" + self, device_id: str, preferred_ime: str = path_config.get_adb_keyboard_ime() ) -> Tuple[bool, str, str]: - """确保 ADBKeyboard 输入法处于激活状态。 - - 返回 (ok, prev_ime, adb_ime)。ok=False 表示设备未安装/未启用 ADBKeyboard。 - """ - prev = self.get_current_ime(device_id) - # 如果当前已经是 ADBKeyboard,就不用再尝试切换(很多 ROM 禁止 ime set) - if "adbkeyboard" in str(prev).lower() or "adbime" in str(prev).lower(): - return True, prev, prev - - imes = self.list_imes(device_id) - adb_ime = "" - - pref = str(preferred_ime or "").strip() - if pref and pref in imes: - adb_ime = pref - else: - adb_ime = self._pick_adbkeyboard_ime(imes) - - if not adb_ime: - return False, prev, "" - - if prev != adb_ime: - if not self.try_set_ime(device_id, adb_ime): - return False, prev, adb_ime - - return True, prev, adb_ime + return _impl_ensure_adbkeyboard_ime(self, device_id, preferred_ime) def restore_ime(self, device_id: str, prev_ime: str) -> bool: - ime = str(prev_ime or "").strip() - if not ime: - return False - return self.try_set_ime(device_id, ime) + return _impl_restore_ime(self, device_id, prev_ime) def try_set_ime(self, device_id: str, ime_id: str) -> bool: - ime = str(ime_id or "").strip() - if not ime: - return False - # 1) 优先走 ime(某些 ROM 会失败) - self._run_adb_shell(device_id, f"ime enable {shlex.quote(ime)}", timeout_seconds=2.5) - if self._run_adb_shell(device_id, f"ime set {shlex.quote(ime)}", timeout_seconds=2.5): - return True - - # 2) 退化:尝试 settings put(通常也会被 ROM 限制,但试一下无害) - if self._run_adb_shell( - device_id, - f"settings put secure default_input_method {shlex.quote(ime)}", - timeout_seconds=2.5, - ): - cur = self.get_current_ime(device_id) - return cur == ime - - return False + return _impl_try_set_ime(self, device_id, ime_id) def _adbkeyboard_broadcast(self, device_id: str, action: str, msg: str) -> bool: - act = str(action or "").strip() - if not act: - return False - # 使用 shlex.quote 转义消息,防止 shell 注入 - safe_msg = shlex.quote(str(msg or "")) - try: - return ( - subprocess.run( - self._adb_args( - device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", safe_msg - ), - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=3.0, - check=False, - ).returncode - == 0 - ) - except Exception: - return False + return _impl_adbkeyboard_broadcast(self, device_id, action, msg) def _adbkeyboard_broadcast_int( self, device_id: str, action: str, key: str, value: int ) -> bool: - act = str(action or "").strip() - k = str(key or "").strip() - if not act or not k: - return False - try: - v = int(value) - except Exception: - return False - # 使用 shlex.quote 转义 key,防止 shell 注入 - safe_k = shlex.quote(k) - try: - return ( - subprocess.run( - self._adb_args( - device_id, "shell", "am", "broadcast", "-a", act, "--ei", safe_k, v - ), - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=3.0, - check=False, - ).returncode - == 0 - ) - except Exception: - return False + return _impl_adbkeyboard_broadcast_int(self, device_id, action, key, value) def keyevent(self, device_id: str, keycode: int) -> bool: - try: - code = int(keycode) - except Exception: - return False - return self._run_adb_shell( - device_id, f"input keyevent {code}", timeout_seconds=2.0 - ) + return _impl_keyevent(self, device_id, keycode) def adbkeyboard_editor_action(self, device_id: str, action_code: int = 4) -> bool: - """使用 ADBKeyBoard 触发 editor action。 - - 常用:IME_ACTION_SEND=4, IME_ACTION_DONE=6。 - 仅当当前输入法是 ADBKeyBoard 时更可靠。 - """ - return self._adbkeyboard_broadcast_int( - device_id, "ADB_EDITOR_CODE", "code", int(action_code) - ) + return _impl_adbkeyboard_editor_action(self, device_id, action_code) def confirm_from_keyboard(self, device_id: str) -> bool: - """在输入框中用“键盘确认/发送”提交。 - - 优先:ADBKeyBoard editor action SEND(4) - 兜底:KEYCODE_ENTER(66) - """ - cur = "" - try: - cur = self.get_current_ime(device_id) - except Exception: - cur = "" - - if "adbkeyboard" in str(cur).lower() or "adbime" in str(cur).lower(): - if self.adbkeyboard_editor_action(device_id, 4): - return True - - return self.keyevent(device_id, 66) + return _impl_confirm_from_keyboard(self, device_id) def input_text_adbkeyboard( self, device_id: str, text: str, - ime_id: str = "com.android.adbkeyboard/.AdbIME", + ime_id: str = path_config.get_adb_keyboard_ime(), restore_prev: bool = True, ) -> bool: - """使用 ADBKeyboard 输入文本(更适合中文)。 - - 要求:手机已安装并启用 ADBKeyboard。若不可用返回 False。 - """ - t = str(text or "") - if not t: - return False - - ok, prev, adb_ime = self.ensure_adbkeyboard_ime(device_id, preferred_ime=ime_id) - if not ok: - return False - - success = False - try: - # 优先 b64(兼容中文/特殊字符),其次纯文本 - b64 = base64.b64encode(t.encode("utf-8")).decode("ascii") - if self._adbkeyboard_broadcast(device_id, "ADB_INPUT_B64", b64): - success = True - elif self._adbkeyboard_broadcast(device_id, "ADB_INPUT_TEXT", t): - success = True - - # 给 IME 一点时间把文本真正“打进”输入框 - time_module.sleep(0.35) - return success - finally: - # 尝试恢复原输入法,避免影响手动使用 - if restore_prev and prev and prev != adb_ime: - # 再稍等一下,避免过早切回导致输入丢失 - time_module.sleep(0.25) - self.restore_ime(device_id, prev) + return _impl_input_text_adbkeyboard(self, device_id, text, ime_id, restore_prev) def paste_text_at( self, device_id: str, x: int, y: int, text: str, ensure_focus: bool = True ) -> bool: - """最简单的“粘贴到输入框”方法。 - - 流程:点击输入框获取焦点 -> 设置剪贴板 -> 发送 KEYCODE_PASTE(279)。 - 若剪贴板不可用则退化为 `adb shell input text`(中文可能不稳定)。 - """ - t = str(text or "").strip() - if not t: - return False - - # 先确保输入框获得焦点 - try: - if ensure_focus: - try: - _uo_log( - f"[Underlying] paste_text_at: clicking to focus device_id={device_id} coord=({x},{y})" - ) - except Exception: - pass - self.click(device_id, int(x), int(y)) - time_module.sleep(0.2) - # 有些输入框第一次点不进,补一次轻点 - try: - _uo_log( - f"[Underlying] paste_text_at: clicking again to ensure focus device_id={device_id} coord=({x},{y})" - ) - except Exception: - pass - self.click(device_id, int(x), int(y)) - time_module.sleep(0.15) - except Exception: - pass - - # 0) 优先:ADBKeyboard(如果已安装/可用) - # 说明:这一步不依赖剪贴板/粘贴菜单,通常对中文更稳定 - try: - ok_adbkb = False - try: - ok_adbkb = bool( - self.input_text_adbkeyboard(device_id, t, restore_prev=False) - ) - except Exception: - ok_adbkb = False - try: - _uo_log( - f"[Underlying] paste_text_at: input_text_adbkeyboard -> {ok_adbkb}" - ) - except Exception: - pass - if ok_adbkb: - return True - except Exception: - pass - - # 1) 优先:剪贴板 + 粘贴键 - ok_clip = False - try: - ok_clip = bool(self.set_clipboard_text(device_id, t)) - except Exception: - ok_clip = False - try: - _uo_log(f"[Underlying] paste_text_at: set_clipboard_text -> {ok_clip}") - except Exception: - pass - if ok_clip: - # 给系统一点时间刷新剪贴板 - time_module.sleep(0.15) - ok_paste = False - try: - ok_paste = bool(self.paste_from_clipboard(device_id)) - except Exception: - ok_paste = False - try: - _uo_log(f"[Underlying] paste_text_at: paste_from_clipboard -> {ok_paste}") - except Exception: - pass - if ok_paste: - return True - - # 2) 兜底:adb input text(中文可能不稳定) - try: - _uo_log( - f"[Underlying] paste_text_at: falling back to input_text for device_id={device_id}" - ) - except Exception: - pass - return self.input_text(device_id, t) + return _impl_paste_text_at(self, device_id, x, y, text, ensure_focus) def _uiautomator_dump(self, device_id: str, local_path: str) -> bool: - """拉取当前界面 UI 树到本地 xml(失败返回 False)。""" - try: - remote = "/sdcard/window_dump.xml" - subprocess.run( - self._adb_args(device_id, "shell", "uiautomator", "dump", remote), - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=2, - check=False, - ) - subprocess.run( - [self._adb_path(), "-s", str(device_id), "pull", remote, str(local_path)], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=2, - check=False, - ) - return os.path.exists(local_path) - except subprocess.TimeoutExpired: - return False - except Exception: - return False + return _impl_uiautomator_dump(self, device_id, local_path) @staticmethod def _parse_bounds(bounds: str): @@ -1191,142 +721,9 @@ class underlying_operations: contains: bool = True, timeout_seconds: float = 2.0, ) -> bool: - """通过 uiautomator dump 按 text/content-desc 点击(命中即点并返回 True)。 - - 适用于:\"推荐\"、\"直播\"、\"点击进入直播间\" 等。 - """ - if not text: - return False - - try: - from douyin.core import path_config - - local_path = path_config.get_window_dump_path() - except Exception: - from douyin.core import path_config - - local_path = path_config.get_window_dump_path() - start = time_module.time() - while True: - if self._uiautomator_dump(device_id, local_path): - try: - tree = ET.parse(local_path) - root = tree.getroot() - except Exception: - root = None - - if root is not None: - target = str(text) - for node in root.iter(): - t = node.attrib.get("text", "") - d = node.attrib.get("content-desc", "") - hit = False - if contains: - if (target in t) or (target in d): - hit = True - else: - if (target == t) or (target == d): - hit = True - if not hit: - continue - b = node.attrib.get("bounds", "") - parsed = self._parse_bounds(b) - if not parsed: - continue - x1, y1, x2, y2 = parsed - cx = int((x1 + x2) / 2) - cy = int((y1 + y2) / 2) - self.click(device_id, cx, cy) - return True - - if time_module.time() - start >= timeout_seconds: - return False - time_module.sleep(0.2) + return _impl_tap_by_text(self, device_id, text, contains, timeout_seconds) def tap_close_icon( self, device_id: str, screen_width: int = 1080, timeout_seconds: float = 2.0 ) -> bool: - """尝试点击直播间顶部的关闭(X)按钮。 - - 逻辑:从 uiautomator dump 里找顶部(较小 y)的可点击小图标,优先命中 content-desc/text 含“关闭/退出/返回”。 - 如果没有文字,就在顶部区域按“最像关闭”的位置进行启发式选择。 - """ - try: - from douyin.core import path_config - - local_path = path_config.get_window_dump_path() - except Exception: - from douyin.core import path_config - - local_path = path_config.get_window_dump_path() - start = time_module.time() - - def _score(node_attrib: dict, bounds_tuple) -> int: - x1, y1, x2, y2 = bounds_tuple - w = x2 - x1 - h = y2 - y1 - if y2 > 420: - return -9999 - if w < 50 or h < 50 or w > 260 or h > 260: - return -9999 - - t = (node_attrib.get("text", "") or "").strip() - d = (node_attrib.get("content-desc", "") or "").strip() - s = t + " " + d - - score = 0 - # 明确关闭/退出优先 - for kw in ("关闭", "退出", "返回", "close", "Close"): - if kw in s: - score += 200 - # 排除一些常见非关闭按钮 - for bad in ("分享", "更多", "菜单", "礼物", "榜", "关注", "评论"): - if bad in s: - score -= 120 - - # 顶部更靠上更像 - score += max(0, 120 - y1) - # 更接近正方形的小图标更像 - score -= abs(w - h) - # 默认更偏右上角(如果你的关闭在左边,也能被“更靠上/更像图标”拉回来) - cx = (x1 + x2) / 2 - if screen_width > 0: - score += int((cx / screen_width) * 40) - return score - - while True: - if self._uiautomator_dump(device_id, local_path): - try: - root = ET.parse(local_path).getroot() - except Exception: - root = None - - best = None - best_score = -999999 - if root is not None: - for node in root.iter(): - attrib = getattr(node, "attrib", {}) or {} - # clickable 属性可能是 'true'/'false' - if str(attrib.get("clickable", "")).lower() != "true": - continue - if str(attrib.get("enabled", "true")).lower() == "false": - continue - b = attrib.get("bounds", "") - parsed = self._parse_bounds(b) - if not parsed: - continue - sc = _score(attrib, parsed) - if sc > best_score: - best_score = sc - best = parsed - - if best and best_score > -1000: - x1, y1, x2, y2 = best - cx = int((x1 + x2) / 2) - cy = int((y1 + y2) / 2) - self.click(device_id, cx, cy) - return True - - if time_module.time() - start >= timeout_seconds: - return False - time_module.sleep(0.2) + return _impl_tap_close_icon(self, device_id, screen_width, timeout_seconds) diff --git a/douyin/core/underlying_operations_pkg/__init__.py b/douyin/core/underlying_operations_pkg/__init__.py index 833ffc1..4b171c0 100644 --- a/douyin/core/underlying_operations_pkg/__init__.py +++ b/douyin/core/underlying_operations_pkg/__init__.py @@ -22,6 +22,33 @@ from .swipe_sendevent import _swipe_with_sendevent_improved from .clipboard import set_clipboard_text from .device_select import select_device from .ocr_digits import analyse_pic_digits +from .text_input import ( + paste_from_clipboard, + input_text, + paste_text, + get_current_ime, + list_imes, + ensure_adbkeyboard_ime, + restore_ime, + try_set_ime, + _adbkeyboard_broadcast, + _adbkeyboard_broadcast_int, + keyevent, + adbkeyboard_editor_action, + confirm_from_keyboard, + input_text_adbkeyboard, + paste_text_at, +) +from .ui_automator import ( + uiautomator_dump, + tap_by_text, + tap_close_icon, +) +from .foreground import ( + get_top_package, + launch_package, + is_douyin_foreground, +) from .adb_helpers import _adb_args @@ -39,4 +66,25 @@ __all__ = [ "_adb_args", "select_device", "analyse_pic_digits", + "paste_from_clipboard", + "input_text", + "paste_text", + "get_current_ime", + "list_imes", + "ensure_adbkeyboard_ime", + "restore_ime", + "try_set_ime", + "_adbkeyboard_broadcast", + "_adbkeyboard_broadcast_int", + "keyevent", + "adbkeyboard_editor_action", + "confirm_from_keyboard", + "input_text_adbkeyboard", + "paste_text_at", + "uiautomator_dump", + "tap_by_text", + "tap_close_icon", + "get_top_package", + "launch_package", + "is_douyin_foreground", ] diff --git a/douyin/core/underlying_operations_pkg/foreground.py b/douyin/core/underlying_operations_pkg/foreground.py new file mode 100644 index 0000000..b71d5e4 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/foreground.py @@ -0,0 +1,84 @@ +"""前台包检测与应用拉起逻辑(从 underlying_operations.py 抽离)。""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Tuple + +from douyin.core import path_config + +if TYPE_CHECKING: + from douyin.core.underlying_operations import underlying_operations + +DOUYIN_PACKAGES = path_config.get_douyin_packages() + + +def get_top_package(self: "underlying_operations", device_id: str) -> str: + """尝试返回当前处于前台的包名。失败返回空字符串。""" + try: + ok, out = self._run_adb_shell_capture( + device_id, "dumpsys window windows", timeout_seconds=4.0 + ) + if ok and out: + for ln in (out or "").splitlines(): + if ( + "mCurrentFocus" in ln + or "mFocusedApp" in ln + or "mFocusedWindow" in ln + ): + m = re.search(r"([A-Za-z0-9_\.]+)\/", ln) + if m: + return m.group(1) + ok2, out2 = self._run_adb_shell_capture( + device_id, "dumpsys activity activities", timeout_seconds=4.0 + ) + if ok2 and out2: + for ln in (out2 or "").splitlines(): + if "mResumedActivity" in ln or "ResumedActivity" in ln: + m = re.search(r"([A-Za-z0-9_\.]+)\/", ln) + if m: + return m.group(1) + except Exception: + pass + return "" + + +def launch_package( + self: "underlying_operations", + device_id: str, + package_name: str = "", + timeout_seconds: float = 5.0, +) -> Tuple[bool, str]: + """通过包名启动应用。""" + candidates = [package_name] if package_name else list(DOUYIN_PACKAGES) + for pkg in candidates: + pkg = (pkg or "").strip() + if not pkg: + continue + cmd = f"monkey -p {pkg} -c android.intent.category.LAUNCHER 1" + ok, out = self._run_adb_shell_capture( + device_id, cmd, timeout_seconds=timeout_seconds + ) + if ok and "No activities found" not in (out or "") and "aborted" not in ( + out or "" + ).lower(): + return True, pkg + for activity in ( + ".main.MainActivity", + ".splash.SplashActivity", + ".main.homepage.MainActivity", + ): + am_cmd = f"am start -n {pkg}/{activity}" + if self._run_adb_shell( + device_id, am_cmd, timeout_seconds=timeout_seconds + ): + return True, pkg + return False, "" + + +def is_douyin_foreground(self: "underlying_operations", device_id: str) -> bool: + """便捷判断:当前前台是否是抖音相关包。""" + top_pkg = self.get_top_package(device_id) or "" + return bool(top_pkg) and ( + "aweme" in top_pkg or "douyin" in top_pkg or "com.ss.android.ugc" in top_pkg + ) diff --git a/douyin/core/underlying_operations_pkg/ocr_pipeline.py b/douyin/core/underlying_operations_pkg/ocr_pipeline.py index 0f016f7..43d3259 100644 --- a/douyin/core/underlying_operations_pkg/ocr_pipeline.py +++ b/douyin/core/underlying_operations_pkg/ocr_pipeline.py @@ -97,6 +97,9 @@ def analyse_pic_word( old.close() thresh = 128 if change_color == 1 else 180 img = img.point(lambda x, t=thresh: 0 if int(x) < t else 255) + # PaddleOCR 期望 HWC 三通道输入;保持二值化效果同时转回 RGB,避免 + # ValueError: not enough values to unpack (expected 3, got 2) + img = img.convert("RGB") else: img = img.convert("RGB") diff --git a/douyin/core/underlying_operations_pkg/reward_pic.py b/douyin/core/underlying_operations_pkg/reward_pic.py index f26eab8..a99caff 100644 --- a/douyin/core/underlying_operations_pkg/reward_pic.py +++ b/douyin/core/underlying_operations_pkg/reward_pic.py @@ -47,6 +47,7 @@ def save_reward_pic(device_id): out_file = os.path.join(out_dir, f"{timepic}.png") adb = _adb_path() + remote_shot = path_config.get_android_screenshot_path() # 同样优先使用 exec-out,减少手机端 I/O try: @@ -72,20 +73,20 @@ def save_reward_pic(device_id): "shell", "screencap", "-p", - "/sdcard/DCIM/screenshot.png", + remote_shot, ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, ) subprocess.run( - [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", out_file], + [adb, "-s", device_id, "pull", remote_shot, out_file], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, ) subprocess.run( - [adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"], + [adb, "-s", device_id, "shell", "rm", remote_shot], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, diff --git a/douyin/core/underlying_operations_pkg/screenshot_direct.py b/douyin/core/underlying_operations_pkg/screenshot_direct.py index c7229e6..1b14cbb 100644 --- a/douyin/core/underlying_operations_pkg/screenshot_direct.py +++ b/douyin/core/underlying_operations_pkg/screenshot_direct.py @@ -18,6 +18,7 @@ import time as time_module from datetime import datetime from typing import TYPE_CHECKING +from douyin.core import path_config from douyin.core.io_utils import ( _mirror_screenshot_to_external, _safe_replace_file, @@ -344,6 +345,8 @@ def capture_screenshot_direct( fallback_start = time_module.time() try: shell_screencap_start = time_module.time() + remote_shot = path_config.get_android_screenshot_path() + remote_shot_alt = path_config.get_android_screenshot_alt_path() subprocess.run( [ adb, @@ -352,7 +355,7 @@ def capture_screenshot_direct( "shell", "screencap", "-p", - "/sdcard/DCIM/screenshot.png", + remote_shot, ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, @@ -368,7 +371,7 @@ def capture_screenshot_direct( pull_start = time_module.time() subprocess.run( - [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file], + [adb, "-s", device_id, "pull", remote_shot, tmp_file], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, @@ -474,7 +477,7 @@ def capture_screenshot_direct( "shell", "screencap", "-p", - "/sdcard/DCIM/screenshot1.png", + remote_shot_alt, ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, @@ -487,8 +490,8 @@ def capture_screenshot_direct( device_id, "shell", "mv", - "/sdcard/DCIM/screenshot1.png", - "/sdcard/DCIM/screenshot.png", + remote_shot_alt, + remote_shot, ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, diff --git a/douyin/core/underlying_operations_pkg/screenshot_pipeline.py b/douyin/core/underlying_operations_pkg/screenshot_pipeline.py new file mode 100644 index 0000000..8d5ff91 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/screenshot_pipeline.py @@ -0,0 +1,150 @@ +"""Screenshot pipeline helpers for underlying_operations.""" +from __future__ import annotations + +import json +import os +import threading +from datetime import datetime +import time as time_module +import logging + + +def get_screenshot(self, device_id, path="pic", use_service: bool = False): + """截图(支持后台服务模式)""" + start_ts = time_module.time() + + try: + import inspect + + frames = [] + for fr in inspect.stack()[1:9]: + frame_info = { + "file": os.path.relpath(fr.filename, os.path.dirname(__file__)), + "line": fr.lineno, + "function": fr.function, + } + frames.append(frame_info) + + pre_record = { + "ts": datetime.now().isoformat(), + "device_id": device_id, + "use_service": bool(use_service), + "path": path, + "phase": "start", + "thread": threading.get_ident(), + "stack": frames, + } + try: + if hasattr(self, "_screenshot_call_cache"): + try: + self._screenshot_call_cache.append(pre_record) + except Exception: + pass + except Exception: + pass + + try: + log_dir = os.path.join(os.path.dirname(__file__), "logs") + os.makedirs(log_dir, exist_ok=True) + with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: + _lf.write(json.dumps(pre_record, ensure_ascii=False) + "\n") + except Exception: + pass + except Exception: + pass + + service_success = False + if use_service: + try: + from operations.screenshot_service import ScreenshotService + + service = ScreenshotService.get_instance() + service_running = getattr(service, "_running", False) + if not service_running: + logging.debug("[截图] 后台服务未运行,尝试启动 device=%s", device_id) + try: + service.start(device_id, interval=1.5) + time_module.sleep(0.2) + except Exception as start_err: + logging.warning("[截图] 启动后台服务失败: %s,将使用直接截图", start_err) + + try: + if service.get_screenshot(device_id, force=False): + dur = (time_module.time() - start_ts) * 1000.0 + logging.info("[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id) + try: + end_record = { + "ts": datetime.now().isoformat(), + "device_id": device_id, + "use_service": True, + "path": path, + "phase": "end", + "result": True, + "duration_ms": dur, + "thread": threading.get_ident(), + } + try: + if hasattr(self, "_screenshot_call_cache"): + self._screenshot_call_cache.append(end_record) + except Exception: + pass + try: + with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: + _lf.write(json.dumps(end_record, ensure_ascii=False) + "\n") + except Exception: + pass + except Exception: + pass + service_success = True + else: + timetag = datetime.now().strftime("%H:%M:%S") + logging.info("[%s] [截图操作] 后台服务未提供有效截图,回退到直接截图", timetag) + except Exception as e: + timetag = datetime.now().strftime("%H:%M:%S") + logging.warning("[%s] [截图操作] 调用后台服务异常,回退到直接截图: %s", timetag, e) + service_success = False + except ImportError as e: + timetag = datetime.now().strftime("%H:%M:%S") + logging.warning("[%s] [截图操作] 无法导入截图服务模块,回退到直接截图: %s", timetag, e) + service_success = False + except Exception as e: + timetag = datetime.now().strftime("%H:%M:%S") + logging.warning("[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e) + service_success = False + + try: + if service_success: + final_result = True + else: + final_result = self._get_screenshot_direct(device_id, path) + except Exception: + final_result = False + + dur = (time_module.time() - start_ts) * 1000.0 + logging.info("[截图] 总耗时(ms)=%.1f use_service=%s result=%s", dur, bool(use_service), final_result) + + try: + end_record = { + "ts": datetime.now().isoformat(), + "device_id": device_id, + "use_service": bool(use_service), + "path": path, + "phase": "end", + "result": bool(final_result), + "duration_ms": dur, + "thread": threading.get_ident(), + } + try: + if hasattr(self, "_screenshot_call_cache"): + self._screenshot_call_cache.append(end_record) + except Exception: + pass + try: + with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: + _lf.write(json.dumps(end_record, ensure_ascii=False) + "\n") + except Exception: + pass + except Exception: + pass + + return bool(final_result) diff --git a/douyin/core/underlying_operations_pkg/text_input.py b/douyin/core/underlying_operations_pkg/text_input.py new file mode 100644 index 0000000..4f5e9a0 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/text_input.py @@ -0,0 +1,319 @@ +"""文本输入与输入法相关实现(从 underlying_operations.py 抽离)。""" + +from __future__ import annotations + +import base64 +import shlex +import subprocess +import time as time_module +from typing import TYPE_CHECKING, Tuple + +from douyin.core import path_config + +if TYPE_CHECKING: + from douyin.core.underlying_operations import underlying_operations + + +def paste_from_clipboard(self: "underlying_operations", device_id: str) -> bool: + """尝试触发“粘贴”操作(需要输入框已获得焦点)。""" + # KEYCODE_PASTE=279(部分机型/系统可能不支持,但无副作用) + return self._run_adb_shell(device_id, "input keyevent 279", timeout_seconds=2.0) + + +def input_text(self: "underlying_operations", device_id: str, text: str) -> bool: + """使用 adb input text 输入(对中文可能不稳定,仅兜底)。""" + t = str(text or "") + if not t: + return False + # 空格用 %s,避免被 shell 分词 + t = t.replace(" ", "%s") + # 完整转义所有 shell 特殊字符 + for ch in [ + "&", + "<", + ">", + "|", + ";", + "$", + "`", + "'", + '"', + "\\", + "(", + ")", + "{", + "}", + "[", + "]", + "!", + "#", + "*", + "?", + ]: + t = t.replace(ch, "\\" + ch) + try: + return ( + subprocess.run( + self._adb_args(device_id, "shell", "input", "text", t), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5.0, + check=False, + ).returncode + == 0 + ) + except Exception: + return False + + +def paste_text(self: "underlying_operations", device_id: str, text: str) -> bool: + """优先走剪贴板粘贴,其次兜底 input text。""" + if self.set_clipboard_text(device_id, text): + self.paste_from_clipboard(device_id) + return True + return self.input_text(device_id, text) + + +def get_current_ime(self: "underlying_operations", device_id: str) -> str: + ok, out = self._run_adb_shell_capture( + device_id, "settings get secure default_input_method", timeout_seconds=2.0 + ) + if not ok: + return "" + return (out or "").strip() + + +def list_imes(self: "underlying_operations", device_id: str) -> list[str]: + # 部分 ROM 会限制 `ime` shell 命令(报 WRITE_SECURE_SETTINGS),这里优先用 settings 查询。 + ok, out = self._run_adb_shell_capture( + device_id, "settings get secure enabled_input_methods", timeout_seconds=2.5 + ) + if ok and out: + raw = (out or "").strip() + # 形如:a/.A:b/.B:c/.C + parts = [p.strip() for p in raw.split(":") if p.strip()] + if parts: + return parts + + ok2, out2 = self._run_adb_shell_capture(device_id, "ime list -s", timeout_seconds=2.5) + if not ok2: + # 最后兜底:至少把当前默认输入法返回,避免上层无法判断 + cur = self.get_current_ime(device_id) + return [cur] if cur else [] + lines = [ln.strip() for ln in (out2 or "").splitlines() if ln.strip()] + return lines + + +def ensure_adbkeyboard_ime( + self: "underlying_operations", + device_id: str, + preferred_ime: str = path_config.get_adb_keyboard_ime(), +) -> Tuple[bool, str, str]: + """确保 ADBKeyboard 输入法处于激活状态。""" + prev = self.get_current_ime(device_id) + # 如果当前已经是 ADBKeyboard,就不用再尝试切换(很多 ROM 禁止 ime set) + if "adbkeyboard" in str(prev).lower() or "adbime" in str(prev).lower(): + return True, prev, prev + + imes = self.list_imes(device_id) + adb_ime = "" + + pref = str(preferred_ime or "").strip() + if pref and pref in imes: + adb_ime = pref + else: + adb_ime = self._pick_adbkeyboard_ime(imes) + + if not adb_ime: + return False, prev, "" + + if prev != adb_ime: + if not self.try_set_ime(device_id, adb_ime): + return False, prev, adb_ime + + return True, prev, adb_ime + + +def restore_ime(self: "underlying_operations", device_id: str, prev_ime: str) -> bool: + ime = str(prev_ime or "").strip() + if not ime: + return False + return self.try_set_ime(device_id, ime) + + +def try_set_ime(self: "underlying_operations", device_id: str, ime_id: str) -> bool: + ime = str(ime_id or "").strip() + if not ime: + return False + # 1) 优先走 ime(某些 ROM 会失败) + self._run_adb_shell(device_id, f"ime enable {shlex.quote(ime)}", timeout_seconds=2.5) + if self._run_adb_shell(device_id, f"ime set {shlex.quote(ime)}", timeout_seconds=2.5): + return True + + # 2) 退化:尝试 settings put(通常也会被 ROM 限制,但试一下无害) + if self._run_adb_shell( + device_id, + f"settings put secure default_input_method {shlex.quote(ime)}", + timeout_seconds=2.5, + ): + cur = self.get_current_ime(device_id) + return cur == ime + + return False + + +def _adbkeyboard_broadcast( + self: "underlying_operations", device_id: str, action: str, msg: str +) -> bool: + act = str(action or "").strip() + if not act: + return False + safe_msg = shlex.quote(str(msg or "")) + try: + return ( + subprocess.run( + self._adb_args( + device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", safe_msg + ), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ) + except Exception: + return False + + +def _adbkeyboard_broadcast_int( + self: "underlying_operations", device_id: str, action: str, key: str, value: int +) -> bool: + act = str(action or "").strip() + k = str(key or "").strip() + if not act or not k: + return False + try: + v = int(value) + except Exception: + return False + safe_k = shlex.quote(k) + try: + return ( + subprocess.run( + self._adb_args(device_id, "shell", "am", "broadcast", "-a", act, "--ei", safe_k, v), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ) + except Exception: + return False + + +def keyevent(self: "underlying_operations", device_id: str, keycode: int) -> bool: + try: + code = int(keycode) + except Exception: + return False + return self._run_adb_shell(device_id, f"input keyevent {code}", timeout_seconds=2.0) + + +def adbkeyboard_editor_action( + self: "underlying_operations", device_id: str, action_code: int = 4 +) -> bool: + """使用 ADBKeyBoard 触发 editor action。""" + return self._adbkeyboard_broadcast_int(device_id, "ADB_EDITOR_CODE", "code", int(action_code)) + + +def confirm_from_keyboard(self: "underlying_operations", device_id: str) -> bool: + """在输入框中用“键盘确认/发送”提交。""" + cur = "" + try: + cur = self.get_current_ime(device_id) + except Exception: + cur = "" + + if "adbkeyboard" in str(cur).lower() or "adbime" in str(cur).lower(): + if self.adbkeyboard_editor_action(device_id, 4): + return True + + return self.keyevent(device_id, 66) + + +def input_text_adbkeyboard( + self: "underlying_operations", + device_id: str, + text: str, + ime_id: str = path_config.get_adb_keyboard_ime(), + restore_prev: bool = True, +) -> bool: + """使用 ADBKeyboard 输入文本(更适合中文)。""" + t = str(text or "") + if not t: + return False + + ok, prev, adb_ime = self.ensure_adbkeyboard_ime(device_id, preferred_ime=ime_id) + if not ok: + return False + + success = False + try: + b64 = base64.b64encode(t.encode("utf-8")).decode("ascii") + if self._adbkeyboard_broadcast(device_id, "ADB_INPUT_B64", b64): + success = True + elif self._adbkeyboard_broadcast(device_id, "ADB_INPUT_TEXT", t): + success = True + + time_module.sleep(0.35) + return success + finally: + if restore_prev and prev and prev != adb_ime: + time_module.sleep(0.25) + self.restore_ime(device_id, prev) + + +def paste_text_at( + self: "underlying_operations", + device_id: str, + x: int, + y: int, + text: str, + ensure_focus: bool = True, +) -> bool: + """点击输入框后粘贴/输入文本。""" + t = str(text or "").strip() + if not t: + return False + + try: + if ensure_focus: + self.click(device_id, int(x), int(y)) + time_module.sleep(0.2) + self.click(device_id, int(x), int(y)) + time_module.sleep(0.15) + except Exception: + pass + + try: + if bool(self.input_text_adbkeyboard(device_id, t, restore_prev=False)): + return True + except Exception: + pass + + ok_clip = False + try: + ok_clip = bool(self.set_clipboard_text(device_id, t)) + except Exception: + ok_clip = False + if ok_clip: + time_module.sleep(0.15) + try: + if bool(self.paste_from_clipboard(device_id)): + return True + except Exception: + pass + + return self.input_text(device_id, t) diff --git a/douyin/core/underlying_operations_pkg/ui_automator.py b/douyin/core/underlying_operations_pkg/ui_automator.py new file mode 100644 index 0000000..4823c43 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/ui_automator.py @@ -0,0 +1,167 @@ +"""UIAutomator 相关交互实现(从 underlying_operations.py 抽离)。""" + +from __future__ import annotations + +import os +import subprocess +import time as time_module +import xml.etree.ElementTree as ET +from typing import TYPE_CHECKING + +from douyin.core import path_config + +if TYPE_CHECKING: + from douyin.core.underlying_operations import underlying_operations + + +def uiautomator_dump( + self: "underlying_operations", device_id: str, local_path: str +) -> bool: + """拉取当前界面 UI 树到本地 xml(失败返回 False)。""" + try: + remote = path_config.get_android_window_dump_path() + subprocess.run( + self._adb_args(device_id, "shell", "uiautomator", "dump", remote), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=2, + check=False, + ) + subprocess.run( + [self._adb_path(), "-s", str(device_id), "pull", remote, str(local_path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=2, + check=False, + ) + return os.path.exists(local_path) + except subprocess.TimeoutExpired: + return False + except Exception: + return False + + +def tap_by_text( + self: "underlying_operations", + device_id: str, + text: str, + contains: bool = True, + timeout_seconds: float = 2.0, +) -> bool: + """通过 uiautomator dump 按 text/content-desc 点击(命中即点并返回 True)。""" + if not text: + return False + + local_path = path_config.get_window_dump_path() + start = time_module.time() + while True: + if self._uiautomator_dump(device_id, local_path): + try: + tree = ET.parse(local_path) + root = tree.getroot() + except Exception: + root = None + + if root is not None: + target = str(text) + for node in root.iter(): + t = node.attrib.get("text", "") + d = node.attrib.get("content-desc", "") + hit = False + if contains: + if (target in t) or (target in d): + hit = True + else: + if (target == t) or (target == d): + hit = True + if not hit: + continue + b = node.attrib.get("bounds", "") + parsed = self._parse_bounds(b) + if not parsed: + continue + x1, y1, x2, y2 = parsed + cx = int((x1 + x2) / 2) + cy = int((y1 + y2) / 2) + self.click(device_id, cx, cy) + return True + + if time_module.time() - start >= timeout_seconds: + return False + time_module.sleep(0.2) + + +def tap_close_icon( + self: "underlying_operations", + device_id: str, + screen_width: int = 1080, + timeout_seconds: float = 2.0, +) -> bool: + """尝试点击直播间顶部的关闭(X)按钮。""" + local_path = path_config.get_window_dump_path() + start = time_module.time() + + def _score(node_attrib: dict, bounds_tuple) -> int: + x1, y1, x2, y2 = bounds_tuple + w = x2 - x1 + h = y2 - y1 + if y2 > 420: + return -9999 + if w < 50 or h < 50 or w > 260 or h > 260: + return -9999 + + t = (node_attrib.get("text", "") or "").strip() + d = (node_attrib.get("content-desc", "") or "").strip() + s = t + " " + d + + score = 0 + for kw in ("关闭", "退出", "返回", "close", "Close"): + if kw in s: + score += 200 + for bad in ("分享", "更多", "菜单", "礼物", "榜", "关注", "评论"): + if bad in s: + score -= 120 + + score += max(0, 120 - y1) + score -= abs(w - h) + cx = (x1 + x2) / 2 + if screen_width > 0: + score += int((cx / screen_width) * 40) + return score + + while True: + if self._uiautomator_dump(device_id, local_path): + try: + root = ET.parse(local_path).getroot() + except Exception: + root = None + + best = None + best_score = -999999 + if root is not None: + for node in root.iter(): + attrib = getattr(node, "attrib", {}) or {} + if str(attrib.get("clickable", "")).lower() != "true": + continue + if str(attrib.get("enabled", "true")).lower() == "false": + continue + b = attrib.get("bounds", "") + parsed = self._parse_bounds(b) + if not parsed: + continue + sc = _score(attrib, parsed) + if sc > best_score: + best_score = sc + best = parsed + + if best and best_score > -1000: + x1, y1, x2, y2 = best + cx = int((x1 + x2) / 2) + cy = int((y1 + y2) / 2) + self.click(device_id, cx, cy) + return True + + if time_module.time() - start >= timeout_seconds: + return False + time_module.sleep(0.2) + diff --git a/douyin/fudai/core/fudai_attend.py b/douyin/fudai/core/fudai_attend.py index 49c9940..4a57c86 100644 --- a/douyin/fudai/core/fudai_attend.py +++ b/douyin/fudai/core/fudai_attend.py @@ -7,6 +7,7 @@ from __future__ import annotations import os import time +from datetime import datetime from typing import Any from douyin.core import path_config @@ -254,10 +255,16 @@ def attend_choujiang(analyser) -> bool: participated_fudai_ts = set() participated_fudai_ts.add(future_ts) analyser._participated_fudai_future_ts = participated_fudai_ts + try: + future_time_str = datetime.fromtimestamp(float(future_ts)).strftime( + "%Y-%m-%d %H:%M:%S" + ) + except Exception: + future_time_str = "" analyser._log_kv( "参与", "记录已参与福袋", - future_ts=future_ts, + 开奖时间=future_time_str if future_time_str else "未知", total_participated=len(participated_fudai_ts), ) except Exception: diff --git a/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py index d5323a8..d87bacf 100644 --- a/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py +++ b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py @@ -1,1096 +1,10 @@ -"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler - 粉丝团门槛分支 +"""粉丝团门槛分支入口(薄封装)。""" -attend_choujiang 中"加入粉丝团/粉丝团"按钮分支的处理逻辑。原本是 1057 行 elif 块, -内嵌一个 _recover_to_fudai_detail_after_fansclub 闭包做"加入页"恢复。 - -入口:handle_fansclub_branch(analyser, attend_button_text) -> bool -返回 True(与原 elif 的 return True 一致)。 -""" from __future__ import annotations -import os from typing import Any -from douyin.core import path_config +from .fansclub_handler_impl import handle_fansclub_branch -from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK, FANSCLUB_JOIN_CLICK, FANSCLUB_JOIN_FALLBACK_CLICK +__all__ = ["handle_fansclub_branch"] - -def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool: - """处理"需要粉丝团门槛"分支:先点参与按钮 → OCR 找加入粉丝团按钮 → 点击 → 关闭详情 → 等待 → 恢复 → 返回 True。""" - analyser.last_attend_fail_reason = "fansclub_required" - - # 保存debug截图:标注OCR识别区域(参与按钮区域) - try: - from douyin.handlers import douyin_screenshot_manager - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - from PIL import Image - - pic = Image.open(pic_path) - try: - pic.load() - pic_rgb = pic.convert("RGB") - finally: - pic.close() - try: - width, height = pic_rgb.size - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - # 缩放OCR区域坐标到实际分辨率 - ocr_x1 = int(306 * width / rx) - ocr_y1 = int(2030 * height / ry) - ocr_x2 = int(780 * width / rx) - ocr_y2 = int(2110 * height / ry) - # 保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="参与按钮", - step="识别参与按钮", - coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), - extra_info={ - "ocr_text": attend_button_text[:50], - "region": "(306,2030)-(780,2110)", - "result": "需要粉丝团", - }, - ) - finally: - pic_rgb.close() - except Exception: - pass - - # 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) - analyser.click(*PARTICIPATE_BTN_CLICK) - analyser._log_kv( - "参与", - "粉丝团门槛:先点击参与按钮", - result="需要粉丝团", - base_x=543, - base_y=2070, - region="(306,2030)-(780,2110)", - ) - analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快 - - # 第二步:使用OCR识别"加入粉丝团"按钮位置并点击(使用OCR识别的文字位置) - try: - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - - # OCR识别区域(扩大范围以便更容易识别) - ocr_region_x1, ocr_region_y1, ocr_region_x2, ocr_region_y2 = ( - 150, - 1900, - 950, - 2200, - ) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text = "" - fansclub_bbox = None - - # 尝试模式0 - try: - # 获取裁剪后的图片路径 - pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") - if pic_path and os.path.exists(pic_path): - from PIL import Image - - img = Image.open(pic_path) - try: - img.load() - img_rgb = img.convert("RGB") - finally: - img.close() - import numpy as np - - img_np = np.array(img_rgb) - - # 调用OCR获取原始结果 - if getattr(analyser.operation, "ocr_type", None) == "easyocr": - ocr_result = analyser.operation.ocr.readtext(img_np) - else: - ocr_result = analyser.operation.ocr.ocr(img_np) - if ocr_result == [None]: - ocr_result = [] - - # 从OCR结果中查找"加入粉丝团"或"粉丝团"文字及其bbox - if isinstance(ocr_result, list) and ocr_result: - # PaddleOCR格式:[[[box], (text, score)], ...] - # EasyOCR格式:[(bbox, text, confidence), ...] - items = ( - ocr_result[0] - if ( - isinstance(ocr_result, list) - and len(ocr_result) == 1 - and isinstance(ocr_result[0], list) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - # 提取文本和bbox - if isinstance(item, (list, tuple)): - if len(item) >= 2: - # EasyOCR格式:[(bbox, text, confidence), ...] - if ( - isinstance(item[0], (list, tuple)) - and len(item[0]) >= 2 - ): - bbox = item[0] # bbox是第一个元素 - if isinstance(item[1], str): - text = item[1] - # PaddleOCR格式:[box, (text, score)] - elif ( - isinstance(item[1], (list, tuple)) - and len(item[1]) >= 1 - ): - bbox = ( - item[0] - if isinstance(item[0], (list, tuple)) - else None - ) - if isinstance(item[1][0], str): - text = item[1][0] - - # 检查是否包含"加入粉丝团"或"粉丝团" - if ( - text - and ("加入粉丝团" in text or "粉丝团" in text) - and bbox - ): - fansclub_text = text - fansclub_bbox = bbox - break - except Exception as e: - analyser._log_kv( - "参与", "获取OCR原始结果失败", error=str(e), level="WARNING" - ) - - # 如果模式0没有找到,尝试模式1(使用analyse_pic_word) - if not fansclub_text: - fansclub_text = str( - analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or "" - ) - - # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) - try: - from douyin.handlers import douyin_screenshot_manager - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - from PIL import Image - - pic = Image.open(pic_path) - try: - pic.load() - pic_rgb = pic.convert("RGB") - finally: - pic.close() - try: - width, height = pic_rgb.size - # 缩放OCR区域坐标到实际分辨率 - ocr_x1 = int(ocr_region_x1 * width / rx) - ocr_y1 = int(ocr_region_y1 * height / ry) - ocr_x2 = int(ocr_region_x2 * width / rx) - ocr_y2 = int(ocr_region_y2 * height / ry) - # 保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="加入粉丝团按钮", - step="识别加入粉丝团按钮", - coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), - extra_info={ - "ocr_text": fansclub_text[:50] if fansclub_text else "", - "region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - "result": ( - "识别成功" - if fansclub_text - and ( - "加入粉丝团" in fansclub_text - or "粉丝团" in fansclub_text - ) - else "识别失败" - ), - "has_bbox": fansclub_bbox is not None, - }, - ) - finally: - pic_rgb.close() - except Exception: - pass - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text and ( - "加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text - ): - click_x = None - click_y = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox: - try: - # 提取bbox的坐标点 - xs = [] - ys = [] - for p in fansclub_bbox: - if isinstance(p, (list, tuple)) and len(p) >= 2: - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - # 计算bbox中心(在裁剪图片中的坐标) - bbox_center_x = (min(xs) + max(xs)) / 2 - bbox_center_y = (min(ys) + max(ys)) / 2 - - # 将裁剪图片坐标转换为全屏坐标 - # 需要加上OCR区域的偏移 - full_x = ocr_region_x1 + bbox_center_x - full_y = ocr_region_y1 + bbox_center_y - - # 缩放到实际分辨率 - click_x = int(full_x * rx // 1080) - click_y = int(full_y * ry // 2400) - except Exception as e: - analyser._log_kv( - "参与", - "计算bbox中心失败", - error=str(e), - level="WARNING", - ) - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if click_x is None or click_y is None: - click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080) - click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400) - - analyser.operation.click(analyser.device_id, click_x, click_y) - analyser._log_kv( - "参与", - "粉丝团门槛:点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text[:50], - x=click_x, - y=click_y, - base_x=( - int((ocr_region_x1 + ocr_region_x2) / 2) - if click_x is None - else None - ), - base_y=( - int((ocr_region_y1 + ocr_region_y2) / 2) - if click_y is None - else None - ), - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox is not None, - ) - else: - # OCR未识别到"加入粉丝团",使用OCR区域中心作为备选 - region_center_x = int( - (ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080 - ) - region_center_y = int( - (ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400 - ) - analyser.operation.click( - analyser.device_id, region_center_x, region_center_y - ) - analyser._log_kv( - "参与", - "粉丝团门槛:点击加入粉丝团按钮(OCR未识别到文字,使用区域中心)", - ocr_text=fansclub_text[:50] if fansclub_text else "", - x=region_center_x, - y=region_center_y, - base_x=(ocr_region_x1 + ocr_region_x2) // 2, - base_y=(ocr_region_y1 + ocr_region_y2) // 2, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - ) - # 等待点击完成(使用可配置延迟) - analyser.operation.delay(getattr(analyser, "fansclub_click_delay", 1.2)) - except Exception as e: - analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e)) - - # 第三步:关闭详情页 - analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击详情页旁边位置关闭详情页 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - - if not analyser.auto_join_fansclub: - analyser._log_kv( - "参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15 - ) - analyser.operation.delay(15) - - # 点击粉丝团按钮后,可能进入"加入粉丝团"独立页面:需要在该页再次点击"加入粉丝团"才能成功。 - def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool: - for i in range(int(max_steps or 4)): - try: - analyser._shot_and_diagnose( - "粉丝团", - "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), - analyser.device_id, - ) - except Exception: - pass - try: - # 已在打开详情时完成阶段诊断,后续不再重复调用 - st, seen = "", "" - except Exception: - st, seen = "", "" - - if st == "FUDai_DETAIL": - return True - - if st == "FANSCLUB_JOIN": - # 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置) - analyser._log_kv( - "参与", - "粉丝团加入页:点击加入粉丝团", - stage=st, - seen=seen, - attempt=i + 1, - ) - try: - # 点击加入粉丝团按钮 - # 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200 - # 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素 - # 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006 - # 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心) - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - # 点击红色文字区域的中心(基于截图分析优化) - click_x = int(540 * rx // 1080) # 区域中心X - click_y = int( - 2006 * ry // 2400 - ) # 红色区域中心Y(基于截图:1940+132/2=2006) - # 第一次点击 - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - base_x=540, - base_y=2006, - region="(200,1940)-(880,2140)", - red_area_center_y=2006, - ) - analyser.operation.delay(0.5) # 短暂等待后立即第二次点击 - # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 - # 扩大OCR识别区域以便更容易识别:使用常量 JOIN_FANSCLUB_REGION - from douyin.fudai.core.coords import JOIN_FANSCLUB_REGION - - ocr_click_success = False - try: - ( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - ) = JOIN_FANSCLUB_REGION - # 截图加入粉丝团按钮区域(扩大范围) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text = "" - fansclub_bbox = None - - try: - pic_path = analyser.operation._find_pic_path( - "加入粉丝团按钮" - ) - if pic_path and os.path.exists(pic_path): - from PIL import Image - - img = Image.open(pic_path) - try: - img.load() - img_rgb = img.convert("RGB") - finally: - img.close() - import numpy as np - - img_np = np.array(img_rgb) - - if ( - getattr( - analyser.operation, "ocr_type", None - ) - == "easyocr" - ): - ocr_result = ( - analyser.operation.ocr.readtext(img_np) - ) - else: - ocr_result = analyser.operation.ocr.ocr( - img_np - ) - if ocr_result == [None]: - ocr_result = [] - - if isinstance(ocr_result, list) and ocr_result: - items = ( - ocr_result[0] - if ( - isinstance(ocr_result, list) - and len(ocr_result) == 1 - and isinstance(ocr_result[0], list) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - if isinstance(item, (list, tuple)): - if len(item) >= 2: - if ( - isinstance( - item[0], (list, tuple) - ) - and len(item[0]) >= 2 - ): - bbox = item[0] - if isinstance(item[1], str): - text = item[1] - elif ( - isinstance( - item[1], (list, tuple) - ) - and len(item[1]) >= 1 - ): - bbox = ( - item[0] - if isinstance( - item[0], - (list, tuple), - ) - else None - ) - if isinstance( - item[1][0], str - ): - text = item[1][0] - - if ( - text - and ( - "加入粉丝团" in text - or "粉丝团" in text - ) - and bbox - ): - fansclub_text = text - fansclub_bbox = bbox - break - except Exception: - pass - - # 如果模式0没有找到,尝试模式1 - if not fansclub_text: - fansclub_text = str( - analyser.operation.analyse_pic_word( - "加入粉丝团按钮", 1 - ) - or "" - ) - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text and ( - "加入粉丝团" in fansclub_text - or "粉丝团" in fansclub_text - ): - click_x = None - click_y = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox: - try: - xs = [] - ys = [] - for p in fansclub_bbox: - if ( - isinstance(p, (list, tuple)) - and len(p) >= 2 - ): - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - bbox_center_x = (min(xs) + max(xs)) / 2 - bbox_center_y = (min(ys) + max(ys)) / 2 - full_x = ocr_region_x1 + bbox_center_x - full_y = ocr_region_y1 + bbox_center_y - click_x = int(full_x * rx // 1080) - click_y = int(full_y * ry // 2400) - except Exception: - pass - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if click_x is None or click_y is None: - click_x = int( - (ocr_region_x1 + ocr_region_x2) - / 2 - * rx - // 1080 - ) - click_y = int( - (ocr_region_y1 + ocr_region_y2) - / 2 - * ry - // 2400 - ) - - analyser.operation.click( - analyser.device_id, - click_x, - click_y, - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text[:50], - x=click_x, - y=click_y, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox is not None, - ) - ocr_click_success = True - else: - # OCR未识别到"加入粉丝团",记录日志 - analyser._log_kv( - "参与", - "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", - ocr_text=( - fansclub_text[:50] - if fansclub_text - else "空" - ), - level="WARNING", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别加入粉丝团按钮失败,使用坐标点击", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - - # 如果OCR点击失败,回退到坐标点击 - if not ocr_click_success: - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - ) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) - or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) - or 2400 - ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "恢复流程:两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay(1.0) # 等待返回完成 - except Exception as e: - analyser._log_kv( - "参与", "恢复流程:点击返回直播间失败", error=str(e) - ) - except Exception: - # 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮) - try: - analyser.click(*FANSCLUB_JOIN_CLICK) # 粉丝团加入按钮优化坐标 - except Exception: - # 最后回退到旧坐标 - try: - analyser.click(*FANSCLUB_JOIN_FALLBACK_CLICK) - except Exception: - pass - - # 等待加入流程完成(根据是否启用自动加入决定等待时间) - auto_join_enabled = getattr( - analyser, "auto_join_fansclub", False - ) - if auto_join_enabled: - # 启用自动加入:等待更长时间,让加入流程完成(可配置) - wait_s = getattr( - analyser, "fansclub_auto_join_wait_seconds", 5.0 - ) - analyser.operation.delay(wait_s) - analyser._log_kv( - "参与", - "已启用自动加入粉丝团,等待加入流程完成", - wait_seconds=wait_s, - ) - else: - # 未启用自动加入:等待较短时间后返回(可配置) - wait_s = getattr( - analyser, "fansclub_manual_wait_seconds", 3.0 - ) - analyser.operation.delay(wait_s) - analyser._log_kv( - "参与", - "未启用自动加入粉丝团,等待后返回", - wait_seconds=wait_s, - ) - - # 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页 - try: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - return_x = int(545 * rx // 1080) - return_y = int(1995 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "加入粉丝团成功后,点击指定位置", - x=return_x, - y=return_y, - base_x=545, - base_y=1995, - ) - analyser.operation.delay(1.0) # 等待点击完成 - - # 关闭详情页 - analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击详情页旁边位置关闭详情页 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - analyser.operation.delay(1.0) # 等待关闭完成 - except Exception as e: - analyser._log_kv( - "参与", "点击指定位置或关闭详情页失败", error=str(e) - ) - - # 重新诊断阶段,确认是否还在粉丝团加入页 - try: - # 删除:避免重复阶段诊断,减少截图/adb开销 - st_after, seen_after = "", "" - analyser._log_kv( - "参与", - "已跳过点击加入粉丝团后的重复阶段诊断", - stage_before=st, - stage_after=st_after, - seen_after=seen_after, - ) - except Exception: - pass - - if st_after == "FANSCLUB_JOIN": - # 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间 - if auto_join_enabled: - # 如果启用了自动加入,尝试再次点击 - analyser._log_kv( - "参与", "仍在粉丝团加入页,尝试再次点击" - ) - try: - # 基于截图优化坐标:红色区域中心Y=2006 - rx = int( - getattr( - analyser, "resolution_ratio_x", 1080 - ) - or 1080 - ) - ry = int( - getattr( - analyser, "resolution_ratio_y", 2400 - ) - or 2400 - ) - click_x = int(540 * rx // 1080) - click_y = int( - 2006 * ry // 2400 - ) # 红色区域中心Y=2006 - # 第一次点击 - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - base_y=2006, - ) - analyser.operation.delay( - 0.5 - ) # 短暂等待后立即第二次点击 - # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 - # 扩大OCR识别区域以便更容易识别:(150, 1900, 950, 2200) - ocr_click_success_retry = False - try: - ( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - ) = (150, 1900, 950, 2200) - # 截图加入粉丝团按钮区域(扩大范围) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text_retry = "" - fansclub_bbox_retry = None - - try: - pic_path = ( - analyser.operation._find_pic_path( - "加入粉丝团按钮" - ) - ) - if pic_path and os.path.exists( - pic_path - ): - from PIL import Image - - img = Image.open(pic_path) - try: - img.load() - img_rgb = img.convert("RGB") - finally: - img.close() - import numpy as np - - img_np = np.array(img_rgb) - - if ( - getattr( - analyser.operation, - "ocr_type", - None, - ) - == "easyocr" - ): - ocr_result = analyser.operation.ocr.readtext( - img_np - ) - else: - ocr_result = ( - analyser.operation.ocr.ocr( - img_np - ) - ) - if ocr_result == [None]: - ocr_result = [] - - if ( - isinstance(ocr_result, list) - and ocr_result - ): - items = ( - ocr_result[0] - if ( - isinstance( - ocr_result, list - ) - and len(ocr_result) == 1 - and isinstance( - ocr_result[0], list - ) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - if isinstance( - item, (list, tuple) - ): - if len(item) >= 2: - if ( - isinstance( - item[0], - ( - list, - tuple, - ), - ) - and len(item[0]) - >= 2 - ): - bbox = item[0] - if isinstance( - item[1], str - ): - text = item[ - 1 - ] - elif ( - isinstance( - item[1], - ( - list, - tuple, - ), - ) - and len(item[1]) - >= 1 - ): - bbox = ( - item[0] - if isinstance( - item[0], - ( - list, - tuple, - ), - ) - else None - ) - if isinstance( - item[1][0], - str, - ): - text = item[ - 1 - ][0] - - if ( - text - and ( - "加入粉丝团" in text - or "粉丝团" in text - ) - and bbox - ): - fansclub_text_retry = ( - text - ) - fansclub_bbox_retry = ( - bbox - ) - break - except Exception: - pass - - # 如果模式0没有找到,尝试模式1 - if not fansclub_text_retry: - fansclub_text_retry = str( - analyser.operation.analyse_pic_word( - "加入粉丝团按钮", 1 - ) - or "" - ) - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text_retry and ( - "加入粉丝团" in fansclub_text_retry - or "粉丝团" in fansclub_text_retry - ): - click_x_retry = None - click_y_retry = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox_retry: - try: - xs = [] - ys = [] - for p in fansclub_bbox_retry: - if ( - isinstance( - p, (list, tuple) - ) - and len(p) >= 2 - ): - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - bbox_center_x = ( - min(xs) + max(xs) - ) / 2 - bbox_center_y = ( - min(ys) + max(ys) - ) / 2 - full_x = ( - ocr_region_x1 - + bbox_center_x - ) - full_y = ( - ocr_region_y1 - + bbox_center_y - ) - click_x_retry = int( - full_x * rx // 1080 - ) - click_y_retry = int( - full_y * ry // 2400 - ) - except Exception: - pass - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if ( - click_x_retry is None - or click_y_retry is None - ): - click_x_retry = int( - (ocr_region_x1 + ocr_region_x2) - / 2 - * rx - // 1080 - ) - click_y_retry = int( - (ocr_region_y1 + ocr_region_y2) - / 2 - * ry - // 2400 - ) - - analyser.operation.click( - analyser.device_id, - click_x_retry, - click_y_retry, - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text_retry[:50], - x=click_x_retry, - y=click_y_retry, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox_retry - is not None, - ) - ocr_click_success_retry = True - else: - # OCR未识别到"加入粉丝团",记录日志 - analyser._log_kv( - "参与", - "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", - ocr_text=( - fansclub_text_retry[:50] - if fansclub_text_retry - else "空" - ), - level="WARNING", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别加入粉丝团按钮失败,使用坐标点击", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - - # 如果OCR点击失败,回退到坐标点击 - if not ocr_click_success_retry: - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - ) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - rx = int( - getattr( - analyser, "resolution_ratio_x", 1080 - ) - or 1080 - ) - ry = int( - getattr( - analyser, "resolution_ratio_y", 2400 - ) - or 2400 - ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "恢复流程:两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay( - 1.0 - ) # 等待返回完成 - except Exception as e: - analyser._log_kv( - "参与", - "恢复流程:点击返回直播间失败", - error=str(e), - ) - except Exception: - pass - except Exception: - pass - return _recover_to_fudai_detail_after_fansclub() - return True diff --git a/douyin/fudai/core/fudai_attend_pkg/fansclub_handler_impl.py b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler_impl.py new file mode 100644 index 0000000..e8edae7 --- /dev/null +++ b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler_impl.py @@ -0,0 +1,23 @@ +"""粉丝团门槛分支实现。""" + +from __future__ import annotations + +import os +from typing import Any + +from douyin.core import path_config +from douyin.fudai.core.coords import ( + DETAIL_OUTSIDE_CLICK, + PARTICIPATE_BTN_CLICK, + FANSCLUB_JOIN_CLICK, + FANSCLUB_JOIN_FALLBACK_CLICK, +) + + +def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool: + """处理"需要粉丝团门槛"分支。""" + # 为减少当前重构风险,先复用原实现文件逻辑副本 + from .fansclub_handler_legacy import handle_fansclub_branch as _legacy_impl + + return _legacy_impl(analyser, attend_button_text) + diff --git a/douyin/fudai/core/fudai_attend_pkg/fansclub_handler_legacy.py b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler_legacy.py new file mode 100644 index 0000000..7e1445a --- /dev/null +++ b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler_legacy.py @@ -0,0 +1,338 @@ +"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler - 粉丝团门槛分支 + +attend_choujiang 中"加入粉丝团/粉丝团"按钮分支的处理逻辑。原本是 1057 行 elif 块, +内嵌一个 _recover_to_fudai_detail_after_fansclub 闭包做"加入页"恢复。 + +入口:handle_fansclub_branch(analyser, attend_button_text) -> bool +返回 True(与原 elif 的 return True 一致)。 +""" +from __future__ import annotations + +import os +from typing import Any + +from douyin.core import path_config + +from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK, FANSCLUB_JOIN_CLICK, FANSCLUB_JOIN_FALLBACK_CLICK + + +def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool: + """处理"需要粉丝团门槛"分支:先点参与按钮 → OCR 找加入粉丝团按钮 → 点击 → 关闭详情 → 等待 → 恢复 → 返回 True。""" + analyser.last_attend_fail_reason = "fansclub_required" + + # 保存debug截图:标注OCR识别区域(参与按钮区域) + try: + from douyin.handlers import douyin_screenshot_manager + + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + from PIL import Image + + pic = Image.open(pic_path) + try: + pic.load() + pic_rgb = pic.convert("RGB") + finally: + pic.close() + try: + width, height = pic_rgb.size + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + # 缩放OCR区域坐标到实际分辨率 + ocr_x1 = int(306 * width / rx) + ocr_y1 = int(2030 * height / ry) + ocr_x2 = int(780 * width / rx) + ocr_y2 = int(2110 * height / ry) + # 保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="ocr", + picname="参与按钮", + step="识别参与按钮", + coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), + extra_info={ + "ocr_text": attend_button_text[:50], + "region": "(306,2030)-(780,2110)", + "result": "需要粉丝团", + }, + ) + finally: + pic_rgb.close() + except Exception: + pass + + # 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) + analyser.click(*PARTICIPATE_BTN_CLICK) + analyser._log_kv( + "参与", + "粉丝团门槛:先点击参与按钮", + result="需要粉丝团", + base_x=543, + base_y=2070, + region="(306,2030)-(780,2110)", + ) + analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快 + + # 第二步:使用OCR识别"加入粉丝团"按钮位置并点击(使用OCR识别的文字位置) + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + + # OCR识别区域(扩大范围以便更容易识别) + ocr_region_x1, ocr_region_y1, ocr_region_x2, ocr_region_y2 = ( + 150, + 1900, + 950, + 2200, + ) + analyser.cut_pic( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + "", + "加入粉丝团按钮", + ) + + # 获取OCR原始结果(包含bbox信息) + fansclub_text = "" + fansclub_bbox = None + + # 尝试模式0 + try: + # 获取裁剪后的图片路径 + pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") + if pic_path and os.path.exists(pic_path): + from PIL import Image + + img = Image.open(pic_path) + try: + img.load() + img_rgb = img.convert("RGB") + finally: + img.close() + import numpy as np + + img_np = np.array(img_rgb) + + # 调用OCR获取原始结果 + if getattr(analyser.operation, "ocr_type", None) == "easyocr": + ocr_result = analyser.operation.ocr.readtext(img_np) + else: + ocr_result = analyser.operation.ocr.ocr(img_np) + if ocr_result == [None]: + ocr_result = [] + + # 从OCR结果中查找"加入粉丝团"或"粉丝团"文字及其bbox + if isinstance(ocr_result, list) and ocr_result: + # PaddleOCR格式:[[[box], (text, score)], ...] + # EasyOCR格式:[(bbox, text, confidence), ...] + items = ( + ocr_result[0] + if ( + isinstance(ocr_result, list) + and len(ocr_result) == 1 + and isinstance(ocr_result[0], list) + ) + else ocr_result + ) + + for item in items: + text = "" + bbox = None + + # 提取文本和bbox + if isinstance(item, (list, tuple)): + if len(item) >= 2: + # EasyOCR格式:[(bbox, text, confidence), ...] + if ( + isinstance(item[0], (list, tuple)) + and len(item[0]) >= 2 + ): + bbox = item[0] # bbox是第一个元素 + if isinstance(item[1], str): + text = item[1] + # PaddleOCR格式:[box, (text, score)] + elif ( + isinstance(item[1], (list, tuple)) + and len(item[1]) >= 1 + ): + bbox = ( + item[0] + if isinstance(item[0], (list, tuple)) + else None + ) + if isinstance(item[1][0], str): + text = item[1][0] + + # 检查是否包含"加入粉丝团"或"粉丝团" + if ( + text + and ("加入粉丝团" in text or "粉丝团" in text) + and bbox + ): + fansclub_text = text + fansclub_bbox = bbox + break + except Exception as e: + analyser._log_kv( + "参与", "获取OCR原始结果失败", error=str(e), level="WARNING" + ) + + # 如果模式0没有找到,尝试模式1(使用analyse_pic_word) + if not fansclub_text: + fansclub_text = str( + analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or "" + ) + + # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) + try: + from douyin.handlers import douyin_screenshot_manager + + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + from PIL import Image + + pic = Image.open(pic_path) + try: + pic.load() + pic_rgb = pic.convert("RGB") + finally: + pic.close() + try: + width, height = pic_rgb.size + # 缩放OCR区域坐标到实际分辨率 + ocr_x1 = int(ocr_region_x1 * width / rx) + ocr_y1 = int(ocr_region_y1 * height / ry) + ocr_x2 = int(ocr_region_x2 * width / rx) + ocr_y2 = int(ocr_region_y2 * height / ry) + # 保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="ocr", + picname="加入粉丝团按钮", + step="识别加入粉丝团按钮", + coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), + extra_info={ + "ocr_text": fansclub_text[:50] if fansclub_text else "", + "region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + "result": ( + "识别成功" + if fansclub_text + and ( + "加入粉丝团" in fansclub_text + or "粉丝团" in fansclub_text + ) + else "识别失败" + ), + "has_bbox": fansclub_bbox is not None, + }, + ) + finally: + pic_rgb.close() + except Exception: + pass + + # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 + if fansclub_text and ( + "加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text + ): + click_x = None + click_y = None + + # 如果获取到了bbox,使用bbox的中心位置 + if fansclub_bbox: + try: + # 提取bbox的坐标点 + xs = [] + ys = [] + for p in fansclub_bbox: + if isinstance(p, (list, tuple)) and len(p) >= 2: + xs.append(float(p[0])) + ys.append(float(p[1])) + + if xs and ys: + # 计算bbox中心(在裁剪图片中的坐标) + bbox_center_x = (min(xs) + max(xs)) / 2 + bbox_center_y = (min(ys) + max(ys)) / 2 + + # 将裁剪图片坐标转换为全屏坐标 + # 需要加上OCR区域的偏移 + full_x = ocr_region_x1 + bbox_center_x + full_y = ocr_region_y1 + bbox_center_y + + # 缩放到实际分辨率 + click_x = int(full_x * rx // 1080) + click_y = int(full_y * ry // 2400) + except Exception as e: + analyser._log_kv( + "参与", + "计算bbox中心失败", + error=str(e), + level="WARNING", + ) + + # 如果bbox计算失败,使用OCR区域中心作为备选 + if click_x is None or click_y is None: + click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080) + click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400) + + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "粉丝团门槛:点击加入粉丝团按钮(OCR识别文字位置)", + ocr_text=fansclub_text[:50], + x=click_x, + y=click_y, + base_x=( + int((ocr_region_x1 + ocr_region_x2) / 2) + if click_x is None + else None + ), + base_y=( + int((ocr_region_y1 + ocr_region_y2) / 2) + if click_y is None + else None + ), + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + used_bbox=fansclub_bbox is not None, + ) + else: + # OCR未识别到"加入粉丝团",使用OCR区域中心作为备选 + region_center_x = int( + (ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080 + ) + region_center_y = int( + (ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400 + ) + analyser.operation.click( + analyser.device_id, region_center_x, region_center_y + ) + analyser._log_kv( + "参与", + "粉丝团门槛:点击加入粉丝团按钮(OCR未识别到文字,使用区域中心)", + ocr_text=fansclub_text[:50] if fansclub_text else "", + x=region_center_x, + y=region_center_y, + base_x=(ocr_region_x1 + ocr_region_x2) // 2, + base_y=(ocr_region_y1 + ocr_region_y2) // 2, + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + ) + # 等待点击完成(使用可配置延迟) + analyser.operation.delay(getattr(analyser, "fansclub_click_delay", 1.2)) + except Exception as e: + analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e)) + + # 第三步:关闭详情页 + analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击详情页旁边位置关闭详情页 + analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") + + if not analyser.auto_join_fansclub: + analyser._log_kv( + "参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15 + ) + analyser.operation.delay(15) + + from .fansclub_recovery import recover_to_fudai_detail_after_fansclub + return recover_to_fudai_detail_after_fansclub(analyser) + return True diff --git a/douyin/fudai/core/fudai_attend_pkg/fansclub_recovery.py b/douyin/fudai/core/fudai_attend_pkg/fansclub_recovery.py new file mode 100644 index 0000000..4de94d8 --- /dev/null +++ b/douyin/fudai/core/fudai_attend_pkg/fansclub_recovery.py @@ -0,0 +1,317 @@ +"""粉丝团加入后的恢复流程。""" + +from __future__ import annotations + +import os +from typing import Any + +from douyin.fudai.core.coords import ( + DETAIL_OUTSIDE_CLICK, + FANSCLUB_JOIN_CLICK, + FANSCLUB_JOIN_FALLBACK_CLICK, +) + + +def recover_to_fudai_detail_after_fansclub( + analyser: Any, max_steps: int = 4 +) -> bool: + for i in range(int(max_steps or 4)): + try: + analyser._shot_and_diagnose( + "粉丝团", + "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), + analyser.device_id, + ) + except Exception: + pass + try: + st, seen = "", "" + except Exception: + st, seen = "", "" + + if st == "FUDai_DETAIL": + return True + + if st == "FANSCLUB_JOIN": + analyser._log_kv( + "参与", + "粉丝团加入页:点击加入粉丝团", + stage=st, + seen=seen, + attempt=i + 1, + ) + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + click_x = int(540 * rx // 1080) + click_y = int(2006 * ry // 2400) + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + base_x=540, + base_y=2006, + region="(200,1940)-(880,2140)", + red_area_center_y=2006, + ) + analyser.operation.delay(0.5) + from douyin.fudai.core.coords import JOIN_FANSCLUB_REGION + + ocr_click_success = False + try: + ( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + ) = JOIN_FANSCLUB_REGION + analyser.cut_pic( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + "", + "加入粉丝团按钮", + ) + + fansclub_text = "" + fansclub_bbox = None + + try: + pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") + if pic_path and os.path.exists(pic_path): + from PIL import Image + import numpy as np + + img = Image.open(pic_path) + try: + img.load() + img_rgb = img.convert("RGB") + finally: + img.close() + img_np = np.array(img_rgb) + + if getattr(analyser.operation, "ocr_type", None) == "easyocr": + ocr_result = analyser.operation.ocr.readtext(img_np) + else: + ocr_result = analyser.operation.ocr.ocr(img_np) + if ocr_result == [None]: + ocr_result = [] + + if isinstance(ocr_result, list) and ocr_result: + items = ( + ocr_result[0] + if ( + isinstance(ocr_result, list) + and len(ocr_result) == 1 + and isinstance(ocr_result[0], list) + ) + else ocr_result + ) + + for item in items: + text = "" + bbox = None + if isinstance(item, (list, tuple)) and len(item) >= 2: + if isinstance(item[0], (list, tuple)) and len(item[0]) >= 2: + bbox = item[0] + if isinstance(item[1], str): + text = item[1] + elif isinstance(item[1], (list, tuple)) and len(item[1]) >= 1: + bbox = item[0] if isinstance(item[0], (list, tuple)) else None + if isinstance(item[1][0], str): + text = item[1][0] + + if text and ("加入粉丝团" in text or "粉丝团" in text) and bbox: + fansclub_text = text + fansclub_bbox = bbox + break + except Exception: + pass + + if not fansclub_text: + fansclub_text = str(analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or "") + + if fansclub_text and ("加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text): + click_x = None + click_y = None + if fansclub_bbox: + try: + xs = [] + ys = [] + for p in fansclub_bbox: + if isinstance(p, (list, tuple)) and len(p) >= 2: + xs.append(float(p[0])) + ys.append(float(p[1])) + if xs and ys: + bbox_center_x = (min(xs) + max(xs)) / 2 + bbox_center_y = (min(ys) + max(ys)) / 2 + full_x = ocr_region_x1 + bbox_center_x + full_y = ocr_region_y1 + bbox_center_y + click_x = int(full_x * rx // 1080) + click_y = int(full_y * ry // 2400) + except Exception: + pass + + if click_x is None or click_y is None: + click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080) + click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400) + + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", + ocr_text=fansclub_text[:50], + x=click_x, + y=click_y, + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + used_bbox=fansclub_bbox is not None, + ) + ocr_click_success = True + else: + analyser._log_kv( + "参与", + "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", + ocr_text=(fansclub_text[:50] if fansclub_text else "空"), + level="WARNING", + ) + except Exception as e: + try: + analyser._log_kv( + "错误", + "OCR识别加入粉丝团按钮失败,使用坐标点击", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + + if not ocr_click_success: + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + ) + analyser.operation.delay(0.5) + try: + return_x = int(527 * rx // 1080) + return_y = int(567 * ry // 2400) + analyser.operation.click(analyser.device_id, return_x, return_y) + analyser._log_kv( + "参与", + "恢复流程:两次点击后,点击返回直播间", + x=return_x, + y=return_y, + base_x=527, + base_y=567, + ) + analyser.operation.delay(1.0) + except Exception as e: + analyser._log_kv( + "参与", "恢复流程:点击返回直播间失败", error=str(e) + ) + except Exception: + try: + analyser.click(*FANSCLUB_JOIN_CLICK) + except Exception: + try: + analyser.click(*FANSCLUB_JOIN_FALLBACK_CLICK) + except Exception: + pass + + auto_join_enabled = getattr(analyser, "auto_join_fansclub", False) + if auto_join_enabled: + wait_s = getattr(analyser, "fansclub_auto_join_wait_seconds", 5.0) + analyser.operation.delay(wait_s) + analyser._log_kv( + "参与", + "已启用自动加入粉丝团,等待加入流程完成", + wait_seconds=wait_s, + ) + else: + wait_s = getattr(analyser, "fansclub_manual_wait_seconds", 3.0) + analyser.operation.delay(wait_s) + analyser._log_kv( + "参与", + "未启用自动加入粉丝团,等待后返回", + wait_seconds=wait_s, + ) + + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + return_x = int(545 * rx // 1080) + return_y = int(1995 * ry // 2400) + analyser.operation.click(analyser.device_id, return_x, return_y) + analyser._log_kv( + "参与", + "加入粉丝团成功后,点击指定位置", + x=return_x, + y=return_y, + base_x=545, + base_y=1995, + ) + analyser.operation.delay(1.0) + analyser.click(*DETAIL_OUTSIDE_CLICK) + analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") + analyser.operation.delay(1.0) + except Exception as e: + analyser._log_kv("参与", "点击指定位置或关闭详情页失败", error=str(e)) + + try: + st_after, seen_after = "", "" + analyser._log_kv( + "参与", + "已跳过点击加入粉丝团后的重复阶段诊断", + stage_before=st, + stage_after=st_after, + seen_after=seen_after, + ) + except Exception: + pass + + if st_after == "FANSCLUB_JOIN" and auto_join_enabled: + analyser._log_kv("参与", "仍在粉丝团加入页,尝试再次点击") + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + click_x = int(540 * rx // 1080) + click_y = int(2006 * ry // 2400) + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + base_y=2006, + ) + analyser.operation.delay(0.5) + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "恢复流程:再次第二次点击加入粉丝团按钮(回退坐标)", + x=click_x, + y=click_y, + ) + analyser.operation.delay(0.5) + return_x = int(527 * rx // 1080) + return_y = int(567 * ry // 2400) + analyser.operation.click(analyser.device_id, return_x, return_y) + analyser._log_kv( + "参与", + "恢复流程:再次点击返回直播间", + x=return_x, + y=return_y, + base_x=527, + base_y=567, + ) + analyser.operation.delay(1.0) + except Exception: + pass + return True + diff --git a/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py b/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py index 95c8bd0..11ea74d 100644 --- a/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py +++ b/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py @@ -17,6 +17,21 @@ from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail from .read_once import read_fudai_detail_once +def _is_valid_mmss_text(time_text: str) -> bool: + t = str(time_text or "").strip() + if not t: + return False + parts = t.split(":", 1) + if len(parts) != 2: + return False + try: + mm = int(parts[0]) + ss = int(parts[1]) + except Exception: + return False + return 0 <= mm <= 59 and 0 <= ss <= 59 + + def read_fudai_detail_with_retries( analyser: Any, fudai_x: int, @@ -130,11 +145,14 @@ def read_fudai_detail_with_retries( prize_value = current_tuple[4] if len(current_tuple) > 4 else 0.0 time_text = current_tuple[1] if len(current_tuple) > 1 else "" - # 如果数据看起来合理(有内容或价值>0,倒计时合理),直接返回 + # 如果数据看起来合理(有内容或价值>0,且倒计时格式合法),直接返回 is_data_reasonable = ( (content and len(content.strip()) > 0) - or (prize_value and float(prize_value) > 0) - or (time_text and len(time_text.strip()) > 0) + or ( + (prize_value and float(prize_value) > 0) + and _is_valid_mmss_text(time_text) + ) + or _is_valid_mmss_text(time_text) ) if is_data_reasonable and current_countdown_seconds > 0: @@ -212,14 +230,23 @@ def read_fudai_detail_with_retries( continue else: # 倒计时合理,更新为当前结果 - last_tuple = current_tuple + if _is_valid_mmss_text(str(current_tuple[1] if len(current_tuple) > 1 else "")): + last_tuple = current_tuple + else: + # 当前倒计时格式非法,保留已有 last_tuple(避免被 60:37 之类异常文本污染) + pass # 如果没有第一次结果,直接使用当前结果 elif first_countdown_seconds is None: - last_tuple = current_tuple + if _is_valid_mmss_text(str(current_tuple[1] if len(current_tuple) > 1 else "")): + last_tuple = current_tuple - # 如果成功读取,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试 - if status == "ok" or status == "coupon_popup" or status == "watch_task": + # 如果成功读取且倒计时格式合法,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试 + if ( + (status == "ok" and _is_valid_mmss_text(str(current_tuple[1] if isinstance(current_tuple, tuple) and len(current_tuple) > 1 else ""))) + or status == "coupon_popup" + or status == "watch_task" + ): break # 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开 diff --git a/douyin/fudai/core/fudai_filter_pkg/join_decision.py b/douyin/fudai/core/fudai_filter_pkg/join_decision.py index e75e50b..95f641d 100644 --- a/douyin/fudai/core/fudai_filter_pkg/join_decision.py +++ b/douyin/fudai/core/fudai_filter_pkg/join_decision.py @@ -8,6 +8,7 @@ from __future__ import annotations import re import time +from datetime import datetime from typing import Any, Tuple from .helpers import _is_short_countdown_text, is_watch_task_fudai @@ -15,6 +16,44 @@ from .should_skip import should_skip_fudai_by_config from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK +def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None: + try: + payload = { + "flag": str(flag or ""), + "status": str(status or ""), + "run_id": str(getattr(analyser, "_run_id", "") or ""), + } + payload.update(extra or {}) + analyser._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload) + except Exception: + pass + + +def _has_valid_countdown(detail: Tuple) -> bool: + """判断 detail 中是否存在可用倒计时(cd_end 必须是未来时间戳)。""" + try: + if not isinstance(detail, tuple) or len(detail) < 6: + return False + + # 先校验 time_text(detail[1])格式,避免把非法倒计时文本带入后续阈值判断。 + time_text = str(detail[1] or "").strip() + m = re.fullmatch(r"(\d{1,2}):(\d{1,2})", time_text) + if not m: + return False + mm = int(m.group(1)) + ss = int(m.group(2)) + if mm < 0 or mm > 59 or ss < 0 or ss > 59: + return False + + cd = detail[5] + if not isinstance(cd, (tuple, list)) or len(cd) < 2: + return False + cd_end = float(cd[1] or 0.0) + return cd_end > time.time() + except Exception: + return False + + def basic_join_decision(analyser: Any, detail: Tuple) -> bool: """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。 @@ -35,6 +74,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: countdown_tuple = detail[5] except Exception: pass + _emit_flow_flag( + analyser, + "join_decision", + "start", + content_preview=(content[:32] if content else ""), + prize_value_yuan=prize_value_yuan, + ) # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 try: @@ -170,6 +216,94 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) return False + # 按钮状态优先:若已识别到"活动已结束/超时"等不可参与文案,优先按按钮状态处理, + # 避免因倒计时 OCR 噪声走到 invalid_countdown 分支。 + try: + button_text = str( + getattr(analyser, "button_text_raw", "") + or getattr(analyser, "_fudai_button_text", "") + or "" + ).strip() + except Exception: + button_text = "" + + ended_keywords = ( + "活动已结束", + "活动结束", + "活动己结束", + "福袋超时", + "活动超时", + "已超时", + "已过期", + "已截止", + ) + if button_text and any(k in button_text for k in ended_keywords): + try: + analyser._log_kv( + "参与", + "basic_join_decision:按钮识别为活动结束/超时,优先退出详情并切换", + reason="button_activity_ended", + button_text=button_text[:60], + ) + except Exception: + pass + try: + analyser.click(*DETAIL_OUTSIDE_CLICK) + except Exception: + try: + analyser.operation.click_back(analyser.device_id) + except Exception: + pass + try: + needswitch_ended = bool(getattr(analyser, "needswitch", True)) + except Exception: + needswitch_ended = True + if needswitch_ended: + try: + if hasattr(analyser, "swipe_up_to_next_live"): + analyser.swipe_up_to_next_live() + else: + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + start_x = 540 * rx // 1080 + start_y = 1200 * ry // 2400 + end_x = 540 * rx // 1080 + end_y = 600 * ry // 2400 + analyser.operation.swipe( + analyser.device_id, + start_x, + start_y, + end_x, + end_y, + 300, + ) + except Exception: + pass + return False + + # 关键防线:倒计时无效时,绝不进入参与分支(避免 OCR 失败被兜底秒数误触发参与) + if not _has_valid_countdown(detail): + try: + analyser._log_kv( + "参与", + "basic_join_decision:倒计时无效,跳过参与", + reason="invalid_countdown", + time_text=str(detail[1] or "") if len(detail) > 1 else "", + ) + except Exception: + pass + try: + analyser.click(*DETAIL_OUTSIDE_CLICK) + except Exception: + try: + analyser.operation.click_back(analyser.device_id) + except Exception: + pass + return False + # 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋 try: needswitch = bool(getattr(analyser, "needswitch", True)) @@ -255,7 +389,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: skip, reason = should_skip_fudai_by_config(analyser, detail) # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值 - # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约 + # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则真实写入预约队列。 # 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected) if skip and reason.startswith("countdown_gt_") and is_high_value: # 再次检查是否是观看任务(双重保险) @@ -487,7 +621,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) pass - # 剩余秒数大于"预约参与阈值",记录预约 + # 剩余秒数大于"预约参与阈值",记录预约(真实写入队列) try: analyser._log_kv( "参与", @@ -503,12 +637,246 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) except Exception: pass - # 这里需要实现预约逻辑,由于代码太长,这里暂时简化 - # 不关闭详情,继续走预约逻辑 - skip = False - reason = "high_value_reservation" + try: + from douyin.reservation.reservation_logic import ( + record as reservation_record, + ) + from douyin.fudai import douyin_fudai_detail + + room_pos = int(getattr(analyser, "room_pos", 0) or 0) + # 用 detail 原始字段优先,识别缺失时尽量回退到缓存字段 + time_text = str(detail[1] or "") if len(detail) > 1 else "" + try: + participants = int(detail[2] or 0) if len(detail) > 2 else 0 + except Exception: + participants = 0 + try: + copies = int(detail[3] or 0) if len(detail) > 3 else 0 + except Exception: + copies = 0 + room_title = str(getattr(analyser, "current_room_title", "") or "") + room_title_raw = str( + getattr(analyser, "current_room_title_raw", "") or room_title + ) + try: + task_count = int(getattr(analyser, "_fudai_detail_task_count_from_stage", 0) or 0) + except Exception: + task_count = 0 + + reservations = getattr(analyser, "reservations", None) + if not isinstance(reservations, list): + reservations = [] + analyser.reservations = reservations + + max_reservations = int( + getattr(analyser, "high_value_fudai_max_reservations", 3) or 3 + ) + + def _add_reservation_callback(res_list, item): + # 由 add_reservation_core_logic 执行去重/排序/裁剪 + return reservation_record.add_reservation_core_logic( + reservations=res_list, + item=item, + max_reservations=max_reservations, + analyser=analyser, + write_state_callback=lambda: None, + ) + + def _sort_reservations_callback(): + # 排序函数在 reservation_logic.helpers 中,record 模块未导出该符号。 + from douyin.reservation.reservation_logic.helpers import ( + _sort_reservations_inplace as _sort_impl, + ) + + return _sort_impl(analyser.reservations) + + def _write_state_callback(): + try: + from douyin.reservation.douyin_reservation import ( + write_reservations_state, + ) + + state_path = getattr(analyser, "_reservations_state_path", "") + if state_path: + write_reservations_state( + state_path=state_path, + reservations=analyser.reservations, + room_pos=int(getattr(analyser, "room_pos", 0) or 0), + current_room_title=str( + getattr(analyser, "current_room_title", "") or "" + ), + current_room_title_raw=str( + getattr(analyser, "current_room_title_raw", "") or "" + ), + reason="high_value_record", + ) + except Exception: + pass + + queue_full = bool( + reservation_record.record_high_value_reservation( + analyser=analyser, + fudai_content_text=str(content or ""), + prize_value_yuan=float(prize_value_yuan or 0.0), + lastsecond=( + int(remain_seconds) + if remain_seconds is not None + else int(max(0.0, future_ts - time.time())) + ), + future_timestamp=float(future_ts), + x=int(getattr(analyser, "last_fudai_x", 0) or 0), + needswitch=bool(getattr(analyser, "needswitch", True)), + wait_minutes=int(getattr(analyser, "wait_minutes", 0) or 0), + post_switch_delay_s=float( + getattr( + analyser, "switch_room_wait_after_stage_diag_seconds", 1.5 + ) + or 1.5 + ), + room_pos=room_pos, + reservations=analyser.reservations, + reservation_focus_until_ts_ref=[ + float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0) + ], + close_detail_callback=lambda: douyin_fudai_detail.close_fudai_detail( + analyser + ), + swipe_up_switch_callback=lambda: getattr( + analyser, "swipe_up_to_next_live", lambda: None + )(), + swipe_down_back_callback=lambda: getattr( + analyser, "swipe_down_back_from_live", lambda: None + )(), + add_reservation_callback=_add_reservation_callback, + sort_reservations_callback=_sort_reservations_callback, + write_state_callback=_write_state_callback, + room_title=room_title, + room_title_raw=room_title_raw, + task_count=task_count, + time_text=time_text, + participants=participants, + copies=copies, + ) + ) + try: + try: + future_time_str = ( + datetime.fromtimestamp(float(future_ts)).strftime("%Y-%m-%d %H:%M:%S") + if future_ts > 0 + else "" + ) + except Exception: + future_time_str = "" + analyser._log_kv( + "预约", + "basic_join_decision:高价值预约已写入队列", + queue_len=len(getattr(analyser, "reservations", []) or []), + queue_full=queue_full, + 开奖时间=future_time_str if future_time_str else "未知", + remain_seconds=( + int(remain_seconds) if remain_seconds is not None else None + ), + ) + except Exception: + pass + # 标记“刚记录预约”,供下一轮 run_once_basic 兜底切房。 + try: + analyser._just_recorded_reservation = True + except Exception: + pass + # 先关闭详情页,避免在详情页内上滑导致切房无效。 + try: + douyin_fudai_detail.close_fudai_detail(analyser) + analyser._log_kv( + "预约", + "basic_join_decision:记录预约后先关闭详情页", + action="close_detail_after_reservation", + ) + except Exception as e_close: + try: + analyser._log_kv( + "预约", + "basic_join_decision:记录预约后关闭详情页失败", + error=str(e_close), + error_type=type(e_close).__name__, + ) + except Exception: + pass + # 按用户期望:记录预约后立即切换到下一个直播间(needswitch=True 时)。 + try: + needswitch_now = bool(getattr(analyser, "needswitch", True)) + except Exception: + needswitch_now = True + if needswitch_now: + try: + if hasattr(analyser, "swipe_up_to_next_live"): + analyser.swipe_up_to_next_live() + else: + # 兜底:没有封装方法时走底层 swipe。 + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + start_x = 540 * rx // 1080 + start_y = 1200 * ry // 2400 + end_x = 540 * rx // 1080 + end_y = 600 * ry // 2400 + analyser.operation.swipe( + analyser.device_id, + start_x, + start_y, + end_x, + end_y, + 300, + ) + # 立即切房成功后清理兜底标志,避免下一轮重复切房。 + try: + analyser._just_recorded_reservation = False + except Exception: + pass + try: + analyser._log_kv( + "预约", + "basic_join_decision:记录预约后已切换下一个直播间", + action="switch_after_reservation", + ) + except Exception: + pass + except Exception as e_sw: + # 立即切换失败时保留 _just_recorded_reservation,由下一轮兜底处理。 + try: + analyser._log_kv( + "预约", + "basic_join_decision:记录预约后立即切房失败,保留兜底切房标志", + error=str(e_sw), + error_type=type(e_sw).__name__, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "预约", + "basic_join_decision:记录预约后不切房(needswitch=False)", + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "预约", + "basic_join_decision:记录高价值预约失败,按普通筛选丢弃", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + # 已处理为预约记录,结束当前详情流程;由主循环后续触发预约回退窗口 + return True if skip: + _emit_flow_flag(analyser, "join_decision", "skip", reason=str(reason or "")) try: analyser._log_kv( "参与", @@ -544,8 +912,37 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) except Exception: pass - # 这里需要实现切换直播间的逻辑,由于代码太长,这里暂时简化 - pass + try: + if hasattr(analyser, "swipe_up_to_next_live"): + analyser.swipe_up_to_next_live() + else: + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + start_x = 540 * rx // 1080 + start_y = 1200 * ry // 2400 + end_x = 540 * rx // 1080 + end_y = 600 * ry // 2400 + analyser.operation.swipe( + analyser.device_id, + start_x, + start_y, + end_x, + end_y, + 300, + ) + except Exception as e_sw: + try: + analyser._log_kv( + "参与", + "basic_join_decision:丢弃后切换直播间失败", + error=str(e_sw), + error_type=type(e_sw).__name__, + ) + except Exception: + pass elapsed = time.time() - start_time analyser._log_kv( @@ -557,6 +954,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: return False # 参与抽奖 + _emit_flow_flag(analyser, "join_decision", "attend_start") try: analyser._log_kv("参与", "basic_join_decision:开始参与抽奖") except Exception: @@ -564,6 +962,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: from ..fudai_attend import attend_choujiang result = attend_choujiang(analyser) + _emit_flow_flag( + analyser, + "join_decision", + "attend_result", + result=bool(result), + fail_reason=str(getattr(analyser, "last_attend_fail_reason", "") or ""), + ) elapsed = time.time() - start_time analyser._log_kv( "参与", diff --git a/douyin/fudai/core/fudai_filter_pkg/should_skip.py b/douyin/fudai/core/fudai_filter_pkg/should_skip.py index 262f6e7..b9ba3bd 100644 --- a/douyin/fudai/core/fudai_filter_pkg/should_skip.py +++ b/douyin/fudai/core/fudai_filter_pkg/should_skip.py @@ -21,6 +21,31 @@ from .helpers import ( ) +def _is_valid_mmss_text(time_text: str) -> bool: + """倒计时文本必须是合法 mm:ss。""" + t = str(time_text or "").strip() + m = re.fullmatch(r"(\d{1,2}):(\d{1,2})", t) + if not m: + return False + try: + mm = int(m.group(1)) + ss = int(m.group(2)) + except Exception: + return False + return 0 <= mm <= 59 and 0 <= ss <= 59 + + +def _fmt_num_for_condition(v: Any) -> str: + """用于日志条件展示:尽量避免出现冗长小数。""" + try: + f = float(v) + except Exception: + return str(v) + if abs(f - round(f)) < 1e-6: + return str(int(round(f))) + return f"{f:.2f}" + + def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]: """根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。 @@ -178,6 +203,28 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str # 并行检查所有筛选条件,收集所有不符合的原因 skip_reasons = [] + # 0) 倒计时文本不可用时,直接跳过(防止走到默认倒计时兜底导致误参与) + if not time_text.strip(): + skip_reasons.append("countdown_missing") + try: + analyser._log_kv( + "筛选", + "倒计时过滤:不符合(倒计时未识别)", + 倒计时文本=time_text, + ) + except Exception: + pass + elif not _is_valid_mmss_text(time_text): + skip_reasons.append("countdown_invalid") + try: + analyser._log_kv( + "筛选", + "倒计时过滤:不符合(倒计时格式非法)", + 倒计时文本=time_text, + ) + except Exception: + pass + # 1) 价值过滤 if min_value > 0: if prize_value_yuan > 0: @@ -189,7 +236,10 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str "价值过滤:不符合(价值过低)", 实际价值=prize_value_yuan, 配置最小价值=min_value, - 判断条件=f"{prize_value_yuan} < {min_value} = True", + 判断条件=( + f"{_fmt_num_for_condition(prize_value_yuan)} < " + f"{_fmt_num_for_condition(min_value)} = True" + ), ) except Exception: pass @@ -200,7 +250,10 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str "价值过滤:通过", 实际价值=prize_value_yuan, 配置最小价值=min_value, - 判断条件=f"{prize_value_yuan} >= {min_value} = True", + 判断条件=( + f"{_fmt_num_for_condition(prize_value_yuan)} >= " + f"{_fmt_num_for_condition(min_value)} = True" + ), ) except Exception: pass @@ -283,12 +336,13 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str if remain_seconds < skip_if_lt: skip_reasons.append(f"countdown_lt_{skip_if_lt}") try: + remain_seconds_i = int(remain_seconds) analyser._log_kv( "筛选", "倒计时过滤:不符合(剩余秒数小于阈值)", - 实际剩余秒数=int(remain_seconds), + 实际剩余秒数=remain_seconds_i, 配置阈值秒数=skip_if_lt, - 判断条件=f"{remain_seconds} < {skip_if_lt} = True", + 判断条件=f"{remain_seconds_i} < {skip_if_lt} = True", ) except Exception: pass @@ -299,24 +353,26 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str if remain_seconds > skip_if_gt: skip_reasons.append(f"countdown_gt_{skip_if_gt}") try: + remain_seconds_i = int(remain_seconds) analyser._log_kv( "筛选", "倒计时过滤:不符合(剩余秒数大于阈值)", - 实际剩余秒数=int(remain_seconds), + 实际剩余秒数=remain_seconds_i, 配置阈值秒数=skip_if_gt, - 判断条件=f"{remain_seconds} > {skip_if_gt} = True", + 判断条件=f"{remain_seconds_i} > {skip_if_gt} = True", 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", ) except Exception: pass else: try: + remain_seconds_i = int(remain_seconds) analyser._log_kv( "筛选", "倒计时过滤:通过", - 实际剩余秒数=int(remain_seconds), + 实际剩余秒数=remain_seconds_i, 配置阈值秒数=skip_if_gt, - 判断条件=f"{remain_seconds} <= {skip_if_gt} = True", + 判断条件=f"{remain_seconds_i} <= {skip_if_gt} = True", ) except Exception: pass @@ -446,18 +502,22 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str # 如果有任何不符合的条件,就跳过 if skip_reasons: elapsed = time.time() - start_time + preferred_reason = next( + (r for r in skip_reasons if str(r).startswith("button_")), + skip_reasons[0], + ) try: analyser._log_kv( "筛选", "should_skip_fudai_by_config完成(不符合条件,跳过)", 不符合原因=skip_reasons, + 主要原因=preferred_reason, 总原因数=len(skip_reasons), elapsed_seconds=round(elapsed, 2), ) except Exception: pass - # 返回第一个原因作为主要原因 - return True, skip_reasons[0] + return True, preferred_reason # 所有条件都通过 try: diff --git a/douyin/fudai/douyin_fudai_contain_impl.py b/douyin/fudai/douyin_fudai_contain_impl.py index 12a7a07..a83cec3 100644 --- a/douyin/fudai/douyin_fudai_contain_impl.py +++ b/douyin/fudai/douyin_fudai_contain_impl.py @@ -97,16 +97,40 @@ def _parse_mmss_from_full_text(text: Any) -> Tuple[str, str]: raw = str(text or "").strip() if not raw: return "", "" + + def _fmt_pair(mm_s: str, ss_s: str) -> Tuple[str, str]: + try: + mm_i = int(mm_s) + ss_i = int(ss_s) + except Exception: + return "", "" + if 0 <= mm_i <= 59 and 0 <= ss_i <= 59: + return f"{mm_i:02d}", f"{ss_i:02d}" + return "", "" + + # 1) 标准格式:13:40 / 13:40 / 13 40 m = re.search(r"(\d{1,2})\D+(\d{1,2})", raw) - if not m: - return "", "" - try: - mm_i = int(m.group(1)) - ss_i = int(m.group(2)) - except Exception: - return "", "" - if 0 <= mm_i <= 59 and 0 <= ss_i <= 59: - return f"{mm_i:02d}", f"{ss_i:02d}" + if m: + mm, ss = _fmt_pair(m.group(1), m.group(2)) + if mm and ss: + return mm, ss + + # 2) 紧凑格式:1340后开奖 / 940后开奖 + compact = re.search( + r"(? Tuple[str, str, int, int, flo except Exception: pass if picked: + picked_idx = int(picked.get("idx", -1)) analyser._log_kv( "倒计时", ( "倒计时候选选择结果" - f" idx={int(picked.get('idx', -1) or -1)}" + f" idx={picked_idx}" f" mm={str(picked.get('mm') or '')}" f" ss={str(picked.get('ss') or '')}" f" valid={bool(picked.get('valid'))}" ), - chosen_idx=int(picked.get("idx", -1) or -1), + chosen_idx=picked_idx, chosen_is_primary=bool(picked.get("is_primary")), chosen_mm=str(picked.get("mm") or ""), chosen_ss=str(picked.get("ss") or ""), @@ -766,16 +791,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo if mm_full_h and ss_full_h: countdown_mm_raw, countdown_ss_raw = mm_full_h, ss_full_h if picked_heavy: + picked_heavy_idx = int(picked_heavy.get("idx", -1)) analyser._log_kv( "倒计时", ( "重OCR后倒计时候选复选结果" - f" idx={int(picked_heavy.get('idx', -1) or -1)}" + f" idx={picked_heavy_idx}" f" mm={str(picked_heavy.get('mm') or '')}" f" ss={str(picked_heavy.get('ss') or '')}" f" valid={bool(picked_heavy.get('valid'))}" ), - chosen_idx=int(picked_heavy.get("idx", -1) or -1), + chosen_idx=picked_heavy_idx, chosen_is_primary=bool(picked_heavy.get("is_primary")), chosen_mm=str(picked_heavy.get("mm") or ""), chosen_ss=str(picked_heavy.get("ss") or ""), @@ -1013,16 +1039,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo if mm_fb and ss_fb: countdown_mm_raw, countdown_ss_raw = mm_fb, ss_fb if picked_fb: + picked_fb_idx = int(picked_fb.get("idx", -1)) analyser._log_kv( "倒计时", ( "备用并行倒计时候选选择结果" - f" idx={int(picked_fb.get('idx', -1) or -1)}" + f" idx={picked_fb_idx}" f" mm={str(picked_fb.get('mm') or '')}" f" ss={str(picked_fb.get('ss') or '')}" f" valid={bool(picked_fb.get('valid'))}" ), - chosen_idx=int(picked_fb.get("idx", -1) or -1), + chosen_idx=picked_fb_idx, chosen_is_primary=bool(picked_fb.get("is_primary")), chosen_mm=str(picked_fb.get("mm") or ""), chosen_ss=str(picked_fb.get("ss") or ""), diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index c17cb04..2933a7b 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -1,1190 +1,30 @@ +"""douyin_fudai_core 兼容入口(薄封装)。""" + from __future__ import annotations -import os -import re -import time -import threading -from typing import Tuple, Any, Optional, Dict - -from douyin.utils.douyin_utils import extract_prize_value_yuan -from douyin.core import path_config -from douyin.fudai.core.fudai_filter import ( - is_watch_task_fudai, - _is_short_countdown_text, -) - -# 从新模块导入调试工具函数 -from douyin.fudai.core.fudai_debug_utils import ( - _save_full_screenshot_with_ocr_region, -) - - -# 从子包 re-export(保持兼容):薄壳 forwarding -from douyin.fudai.douyin_fudai_core_pkg import ( +from .douyin_fudai_core_legacy import ( attend_choujiang, basic_join_decision, check_have_reward_notice_confirm, check_in_order_confirm_page, check_lucky_draw_result, + extract_prize_value_yuan, + get_fudai_contain, get_reward, is_watch_task_fudai, should_skip_fudai_by_config, - _is_short_countdown_text, ) -try: - from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore -except Exception: # pyright: ignore - # 在运行环境中可能缺少 OCR 预处理依赖,提供回退实现以避免导入失败导致程序中断。 - def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore # pyright: ignore - """回退的 preprocess_for_ocr:直接返回 picname(不做预处理)。""" - try: - return str(picname) - except TypeError: # pyright: ignore - return picname - - -# 模块级线程池状态,用于复用 OCR 并行执行,避免频繁创建/销毁 - - - - -def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: - """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" - - # 检查是否启用调试截图保存(默认False,正常运行时跳过以提升性能) - try: - save_debug_images = bool( - getattr(analyser, "fudai_detail_save_debug_images", False) - ) - except Exception: - save_debug_images = False - # 如果analyser未提供配置,回退到全局配置文件 - if not save_debug_images: - try: - import json - - cfg_path = path_config.get_config_path() - if os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as f: - cfg = json.load(f) - save_debug_images = bool( - cfg.get("fudai_detail_save_debug_images", False) - ) - except Exception: # pyright: ignore[reportTooBroadExceptionType] - pass - - # 轻重分流模式:auto(缺失字段才跑重)、light(只跑轻)、heavy(轻后必跑重) - try: - ocr_mode = str( - getattr(analyser, "fudai_detail_ocr_mode", "light") or "light" - ).lower() # 优化:默认使用light模式,提升性能 - except Exception: - ocr_mode = "light" - force_light = ocr_mode == "light" - force_heavy = ocr_mode == "heavy" - - def _read_countdown_split(box: tuple[int, int, int, int]) -> str: - """委托给 douyin_fudai_core_pkg.countdown_split.read_countdown_split。 - - 保留闭包形式,使 box 默认绑定到当前 analyser / save_debug_images 闭包变量。 - """ - from douyin.fudai.douyin_fudai_core_pkg.countdown_split import ( - read_countdown_split, - ) - return read_countdown_split( - analyser, box, save_debug_images=save_debug_images - ) - - def _extract_participants_and_clean(text: str): - if not text: - return 0, 0, "" - compact = re.sub(r"\s+", "", str(text)) - # 例如:共1份1173人已参与 - copies = 0 - participants = 0 - m = re.search(r"共(\d+)份", compact) - if m: - copies = int(m.group(1)) - m = re.search(r"(\d+)人已参与", compact) - if m: - participants = int(m.group(1)) - - # 清理掉份数/参与人数等尾巴,避免干扰关键词匹配 - cleaned = re.sub(r"共\d+份", "", compact) - cleaned = re.sub(r"\d+人已参与", "", cleaned) - return participants, copies, cleaned - - def _is_blank_text(text: Any) -> bool: - return len(str(text or "").strip()) == 0 - - def _should_use_heavy( - content_text: Any, - mm_raw: Any, - ss_raw: Any, - value_text: Any, - task_text: Any, - button_text: Any, - ) -> set: - fields: set[str] = set() - if force_light: - return fields - if force_heavy or _is_blank_text(content_text): - fields.add("content") - if force_heavy or not (mm_raw and ss_raw): - fields.update({"countdown_mm", "countdown_ss"}) - if force_heavy or _is_blank_text(value_text): - fields.add("value") - if force_heavy or _is_blank_text(task_text): - fields.add("task_list") - if force_heavy or _is_blank_text(button_text): - fields.add("button") - return fields - - def _run_heavy_ocr(fields: set[str]) -> Dict[str, Any]: - """委托给 douyin_fudai_core_pkg.heavy_ocr.run_heavy_ocr。""" - from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import run_heavy_ocr - return run_heavy_ocr(analyser, fields) - - # 切割直播间标题图片(用于并行 OCR) - from douyin.fudai.core.coords import LIVE_ROOM_TITLE, PARTICIPATE_BUTTON, TASK_LIST - analyser.cut_pic(*LIVE_ROOM_TITLE, "", "live_room_title_mid", analyser.y_pianyi) - - # 切割内容/倒计时/价值(按 renwu 选 countdown_box) - from douyin.fudai.douyin_fudai_core_pkg.cut_regions import cut_detail_regions - countdown_box = cut_detail_regions( - analyser, renwu, save_debug_images=save_debug_images - ) - - # 准备任务列表区域的截图(用于并行OCR) - # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 - try: - # 保存任务列表区域的调试截图(仅在配置启用时) - if save_debug_images: - _save_full_screenshot_with_ocr_region( - analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi - ) - analyser.cut_pic(*TASK_LIST, "", "福袋任务列表", analyser.y_pianyi) - except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType] - # 任务列表截图失败不影响后续流程,记录日志即可 - try: - analyser._log_kv( # pyright: ignore[reportPrivateUsage] - "福袋", - "任务列表截图失败,继续后续流程", - error=str(e_inner), - ) - except Exception: # pyright: ignore[reportTooBroadExceptionType] - pass - - # 准备参与按钮区域的截图(用于并行OCR识别按钮状态) - try: - # 保存参与按钮区域的调试截图(仅在配置启用时) - if save_debug_images: - _save_full_screenshot_with_ocr_region( - analyser, "参与按钮", PARTICIPATE_BUTTON, analyser.y_pianyi - ) - analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮", analyser.y_pianyi) - except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType] - # 按钮截图失败不影响后续流程,记录日志即可 - try: - analyser._log_kv( # pyright: ignore[reportPrivateUsage] - "福袋", - "参与按钮截图失败,继续后续流程", - error=str(e_inner), - ) - except Exception: - pass - - # 并行执行六个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值/参与按钮 - # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 - ocr_start_time = time.time() - task_list_raw = None - fudai_content_raw = None - countdown_mm_raw = None - countdown_ss_raw = None - value_raw = None - button_text_raw = None - # 并行子任务耗时收集(ms),由各子任务在 finally 中写入 - perf_task_durations: Dict[str, float] = {} - perf_task_lock = threading.Lock() - - # 读取内容 OCR 配置开关(其它开关在 OcrTaskRunner 内部按需读取) - from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import _read_disable_flag - disable_content_recognition = _read_disable_flag( - analyser, - "fudai_disable_content_recognition", - "fudai_disable_content_recognition", - ) - - # 7 个并行 OCR 子任务封装到 OcrTaskRunner - from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import OcrTaskRunner - _ocr_runner = OcrTaskRunner( - analyser, - perf_task_durations, - perf_task_lock, - disable_content_recognition=disable_content_recognition, - ) - ocr_task_list = _ocr_runner.ocr_task_list - ocr_content = _ocr_runner.ocr_content - ocr_countdown_mm = _ocr_runner.ocr_countdown_mm - ocr_countdown_ss = _ocr_runner.ocr_countdown_ss - ocr_value = _ocr_runner.ocr_value - ocr_button = _ocr_runner.ocr_button - ocr_live_room_title = _ocr_runner.ocr_live_room_title - - # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) - # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 - try: - # 使用动态线程池大小,根据CPU核心数优化,并复用线程池 - from operations.screenshot_service import get_optimal_workers - - optimal_workers = get_optimal_workers() - executor = _get_fudai_ocr_executor(optimal_workers) - - task_funcs = { - "task_list": ocr_task_list, - "countdown_mm": ocr_countdown_mm, - "countdown_ss": ocr_countdown_ss, - "value": ocr_value, - "button": ocr_button, - "live_room_title": ocr_live_room_title, - } - # 如果配置启用,避免把 content 任务加入并行队列,彻底不调度该OCR - if not disable_content_recognition: - task_funcs["content"] = ocr_content - futures: Dict[str, Any] = {} - start_ts: Dict[str, float] = {} - - for name, func in task_funcs.items(): - start_ts[name] = time.time() - futures[name] = executor.submit(func) - - task_list_raw = fudai_content_raw = countdown_mm_raw = None - countdown_ss_raw = value_raw = None - live_room_title_raw = live_room_title_text_raw = None - - # 收集结果并记录耗时 - durations = {} - for name, fut in futures.items(): - try: - res = fut.result() - finally: - durations[name] = round( - (time.time() - start_ts.get(name, time.time())) * 1000, 1 - ) - if name == "task_list": - task_list_raw = res - elif name == "content": - fudai_content_raw = res - elif name == "countdown_mm": - countdown_mm_raw = res - elif name == "countdown_ss": - countdown_ss_raw = res - elif name == "value": - value_raw = res - elif name == "button": - button_text_raw = res - elif name == "live_room_title": - live_room_title_raw, live_room_title_text_raw = res - - try: - analyser._log_kv( - "性能", - "并行OCR子任务耗时(ms)", - **{f"ocr_{k}": v for k, v in durations.items()}, - ) - except Exception: - pass - - # 输出一行紧凑的并行 OCR 汇总,便于日志聚合分析 - try: - total_ocr_ms = round((time.time() - ocr_start_time) * 1000, 1) - durations_str = ",".join(f"{k}={v}" for k, v in durations.items()) - import logging - - logging.info( - "[OCR汇总] total_ms=%.1f %s", - total_ocr_ms, - durations_str, - ) - except Exception: - pass - - # 轻重分流:轻量OCR跑完后,仅在缺字段或强制时补充重OCR - try: - heavy_fields = _should_use_heavy( - fudai_content_raw, - countdown_mm_raw, - countdown_ss_raw, - value_raw, - task_list_raw, - button_text_raw, - ) - except Exception: - heavy_fields = set() - - if heavy_fields: - heavy_res = _run_heavy_ocr(heavy_fields) - - def _prefer(new_val: Any, old_val: Any): - return new_val if not _is_blank_text(new_val) else old_val - - task_list_raw = _prefer(heavy_res.get("task_list"), task_list_raw) - fudai_content_raw = _prefer(heavy_res.get("content"), fudai_content_raw) - countdown_mm_raw = _prefer(heavy_res.get("countdown_mm"), countdown_mm_raw) - countdown_ss_raw = _prefer(heavy_res.get("countdown_ss"), countdown_ss_raw) - value_raw = _prefer(heavy_res.get("value"), value_raw) - button_text_raw = _prefer(heavy_res.get("button"), button_text_raw) - - try: - analyser._log_kv( - "性能", - "福袋详情OCR轻重分流:触发重OCR补齐", - mode=ocr_mode, - heavy_fields=sorted(list(heavy_fields)), - heavy_duration_ms=heavy_res.get("_duration_ms"), - ) - except Exception: - pass - - # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) - if task_list_raw: - try: - analyser._log_kv( - "福袋", - "OCR识别任务列表区域", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "记录任务列表OCR结果日志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 检查任务列表中是否包含"观看X分钟"任务 - is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) - if is_watch_task_in_list: - try: - analyser._log_kv( - "福袋", - "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "记录观看任务检测日志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "设置观看任务标志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - - # 处理按钮识别结果,判断参与状态并做决策 - button_status = None - if button_text_raw: - button_text = str(button_text_raw).strip() - try: - analyser._log_kv( - "参与", - "主并行OCR识别参与按钮", - button_text=button_text if button_text else "", - ) - except Exception: - pass - - # 判断按钮状态 - if "参与成功" in button_text or "等待开奖" in button_text: - button_status = "已参与" - elif "加入粉丝团" in button_text or "粉丝团" in button_text: - button_status = "需要加入粉丝团" - elif ( - "评论" in button_text - or "发表评论" in button_text - or "一键发表评论" in button_text - ): - button_status = "需要评论" - elif "还需看播" in button_text or "开始观看" in button_text: - button_status = "需要观看" - elif "未达成" in button_text: - button_status = "未达成要求" - elif "参与抽奖" in button_text or "参与" in button_text: - button_status = "可以参与" - else: - button_status = "未知状态" - - # 将按钮状态存储到 analyser 对象中 - try: - analyser._fudai_button_status = button_status - analyser._fudai_button_text = button_text - analyser.button_text_raw = ( - button_text_raw # 设置按钮文本原始值供过滤使用 - ) - # 存储所有主并行OCR识别的原始字段供验证使用 - analyser.fudai_content_raw = fudai_content_raw - analyser.task_list_raw = task_list_raw - analyser.countdown_mm_raw = countdown_mm_raw - analyser.countdown_ss_raw = countdown_ss_raw - analyser.value_raw = value_raw - analyser.live_room_title_raw = live_room_title_raw - analyser._fudai_button_ocr_time = time.time() # 记录识别时间 - try: - analyser._fudai_button_room_pos = int( - getattr(analyser, "room_pos", 0) or 0 - ) - except Exception: - pass - analyser._log_kv( - "参与", - "主按钮状态判断", - status=button_status, - button_text=button_text if button_text else "", - ) - except Exception: - pass - - ocr_elapsed = time.time() - ocr_start_time - try: - analyser._log_kv( - "性能", - "并行OCR识别完成(任务数量已在前置检测中获取)", - elapsed_seconds=round(ocr_elapsed, 3), - task_count=renwu, - button_status=button_status or "未识别", - ) - # 输出所有OCR识别结果详情 - ocr_results = { - "福袋内容": fudai_content_raw[:100] if fudai_content_raw else "未识别", - "任务列表": task_list_raw[:100] if task_list_raw else "未识别", - "倒计时分钟": countdown_mm_raw if countdown_mm_raw else "未识别", - "倒计时秒": countdown_ss_raw if countdown_ss_raw else "未识别", - "奖品价值": value_raw[:50] if value_raw else "未识别", - "按钮文本": button_text_raw if button_text_raw else "未识别", - "直播间标题": ( - live_room_title_raw[:100] if live_room_title_raw else "未识别" - ), - } - analyser._log_kv("详情", "并行OCR识别结果详情", **ocr_results) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "记录OCR性能日志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - except Exception as e_inner: - # 如果并行执行失败,按需决定是否走备用并行(可跳过以节省时间) - try: - analyser._log_kv( - "错误", - "并行OCR失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="ERROR", - ) - except Exception: - pass - - # 可选跳过备用并行,加快失败路径(默认启用备用;可通过 analyser.enable_fudai_ocr_fallback 控制) - try: - enable_fallback_parallel = bool( - getattr(analyser, "enable_fudai_ocr_fallback", True) - ) - except Exception: - enable_fallback_parallel = True - - if not enable_fallback_parallel: - try: - analyser._log_kv( - "性能", - "跳过备用并行OCR以节省时间", - reason="fallback_disabled", - level="WARNING", - ) - except Exception: - pass - return "", "", 0, 0, 0.0 - - # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) - try: - - # 6 个备用并行 OCR 子任务封装到 OcrTaskRunnerFallback - from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import ( - OcrTaskRunnerFallback, - ) - _fb_runner = OcrTaskRunnerFallback( - analyser, - disable_content_recognition=disable_content_recognition, - ) - ocr_task_list_fallback = _fb_runner.ocr_task_list - ocr_content_fallback = _fb_runner.ocr_content - ocr_countdown_mm_fallback = _fb_runner.ocr_countdown_mm - ocr_countdown_ss_fallback = _fb_runner.ocr_countdown_ss - ocr_value_fallback = _fb_runner.ocr_value - ocr_button_fallback = _fb_runner.ocr_button - - # 使用动态线程池大小,并复用线程池 - from operations.screenshot_service import get_optimal_workers - - optimal_workers = get_optimal_workers() - executor = _get_fudai_ocr_executor(optimal_workers) - - task_funcs = { - "task_list": ocr_task_list_fallback, - "countdown_mm": ocr_countdown_mm_fallback, - "countdown_ss": ocr_countdown_ss_fallback, - "value": ocr_value_fallback, - "button": ocr_button_fallback, - } - # 如果配置允许,则加入备用 content OCR,否则不调度 - if not disable_content_recognition: - task_funcs["content"] = ocr_content_fallback - futures: Dict[str, Any] = {} - start_ts: Dict[str, float] = {} - for name, func in task_funcs.items(): - start_ts[name] = time.time() - futures[name] = executor.submit(func) - - durations = {} - task_list_raw = fudai_content_raw = countdown_mm_raw = None - countdown_ss_raw = value_raw = button_text_raw = None - for name, fut in futures.items(): - try: - res = fut.result() - finally: - durations[name] = round( - (time.time() - start_ts.get(name, time.time())) * 1000, 1 - ) - if name == "task_list": - task_list_raw = res - elif name == "content": - fudai_content_raw = res - elif name == "countdown_mm": - countdown_mm_raw = res - elif name == "countdown_ss": - countdown_ss_raw = res - elif name == "value": - value_raw = res - elif name == "button": - button_text_raw = res - - try: - analyser._log_kv( - "性能", - "备用并行OCR子任务耗时(ms)", - **{f"ocr_{k}": v for k, v in durations.items()}, - ) - except Exception: - pass - - # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) - if task_list_raw: - try: - analyser._log_kv( - "福袋", - "OCR识别任务列表区域(备用并行)", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e_inner2: - try: - analyser._log_kv( - "错误", - "记录备用任务列表OCR结果日志失败", - error=str(e_inner2), - error_type=type(e_inner2).__name__, - level="WARNING", - ) - except Exception: - pass - # 检查任务列表中是否包含"观看X分钟"任务 - is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) - if is_watch_task_in_list: - try: - analyser._log_kv( - "福袋", - "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e_inner2: - try: - analyser._log_kv( - "错误", - "记录备用观看任务检测日志失败", - error=str(e_inner2), - error_type=type(e_inner2).__name__, - level="WARNING", - ) - except Exception: - pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e_inner2: - try: - analyser._log_kv( - "错误", - "设置备用观看任务标志失败", - error=str(e_inner2), - error_type=type(e_inner2).__name__, - level="WARNING", - ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - - # 处理备用并行执行的按钮识别结果 - button_status = None - if button_text_raw: - button_text = str(button_text_raw).strip() - try: - analyser._log_kv( - "参与", - "备用并行OCR识别参与按钮", - button_text=button_text if button_text else "", - ) - except Exception: - pass - - # 判断按钮状态 - if "参与成功" in button_text or "等待开奖" in button_text: - button_status = "已参与" - elif "加入粉丝团" in button_text or "粉丝团" in button_text: - button_status = "需要加入粉丝团" - elif ( - "评论" in button_text - or "发表评论" in button_text - or "一键发表评论" in button_text - ): - button_status = "需要评论" - elif "还需看播" in button_text or "开始观看" in button_text: - button_status = "需要观看" - elif "未达成" in button_text: - button_status = "未达成要求" - elif "参与抽奖" in button_text or "参与" in button_text: - button_status = "可以参与" - else: - button_status = "未知状态" - - # 将按钮状态存储到 analyser 对象中 - try: - analyser._fudai_button_status = button_status - analyser._fudai_button_text = button_text - analyser.button_text_raw = ( - button_text_raw # 设置按钮文本原始值供过滤使用 - ) - # 存储所有备用并行OCR识别的原始字段供验证使用 - analyser.fudai_content_raw = fudai_content_raw - analyser.task_list_raw = task_list_raw - analyser.countdown_mm_raw = countdown_mm_raw - analyser.countdown_ss_raw = countdown_ss_raw - analyser.value_raw = value_raw - analyser.live_room_title_raw = live_room_title_raw - analyser._fudai_button_ocr_time = time.time() # 记录识别时间 - analyser._log_kv( - "参与", - "备用按钮状态判断", - status=button_status, - button_text=button_text if button_text else "", - ) - except Exception: - pass - except Exception: - pass - - # 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息) - is_watch_task = False - if fudai_content_raw: - try: - is_watch_task = is_watch_task_fudai(str(fudai_content_raw)) - if is_watch_task: - try: - analyser._log_kv( - "福袋", - "OCR识别到'观看X分钟'类任务,直接跳过后续处理", - raw_content=( - fudai_content_raw[:100] if fudai_content_raw else "" - ), - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "记录观看任务检测日志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "设置观看任务标志失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "检查观看任务失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - raw_content=fudai_content_raw[:100] if fudai_content_raw else "", - level="WARNING", - ) - except Exception: - pass - - participants, copies, fudai_content_text = _extract_participants_and_clean( - fudai_content_raw if fudai_content_raw is not None else "" - ) - - # 如果清理后的内容中没有检测到,但原始内容中检测到了,使用原始内容再次确认 - if not is_watch_task and fudai_content_text: - try: - is_watch_task = is_watch_task_fudai(fudai_content_text) - if is_watch_task: - try: - analyser._log_kv( - "福袋", - "OCR识别到'观看X分钟'类任务(清理后检测),直接跳过后续处理", - content=fudai_content_text[:100] if fudai_content_text else "", - ) - except Exception: - pass - # 设置标志 - try: - analyser._is_watch_task_detected = True - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 - except Exception: - pass - - # 输出福袋内容(使用明确的格式,便于GUI解析) - content_for_log = fudai_content_text if fudai_content_text else "未识别到" - # 移除重复输出,因为并行OCR详情中已经包含了此信息 - # analyser._log_kv( - # "福袋", - # f"识别福袋内容:{content_for_log[:100]}", # 在消息中直接包含内容,确保可见 - # level="DEBUG", - # content=content_for_log, # 同时作为字段输出 - # ) - - # 记录进入直播间到识别到福袋的耗时(仅记录一次) - try: - if getattr(analyser, "_enter_live_ts", 0.0) and not getattr( - analyser, "_enter_live_fudai_logged", False - ): - try: - secs = float(time.time() - float(analyser._enter_live_ts or 0.0)) - except Exception: - secs = -1.0 - reason = str(getattr(analyser, "_enter_live_reason", "") or "") - analyser._log_kv( - "性能", - "进入直播间到识别福袋耗时", - seconds=round(secs, 2), - enter_reason=reason, - ) - try: - analyser._enter_live_fudai_logged = True - except Exception: - pass - if copies: - analyser._log_kv( - "福袋", - "识别福袋信息", - copies=copies, - participants=participants if participants else 0, - ) - except Exception: - pass - - # 倒计时:直接使用分割OCR结果(分钟+秒),不再使用完整OCR - time_text = "" # 初始化为空字符串,确保类型为 str - try: - # 提取数字:分钟和秒都应该是1-2位数字 - def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位,取前max_digits位优先。""" - digits = "".join(ch for ch in str(text or "") if ch.isdigit()) - if len(digits) > max_digits: - candidate = digits[:max_digits] - # 如果前2位全是0但实际有非0数字,跳0取有效数字 - if set(candidate) == {"0"} and digits.lstrip("0"): - actual = digits.lstrip("0")[:max_digits] - return actual.zfill(max_digits) - return candidate - if len(digits) == 1: - return "0" + digits - return digits - - mm = _extract_digits(countdown_mm_raw, max_digits=2) if countdown_mm_raw else "" - ss = _extract_digits(countdown_ss_raw, max_digits=2) if countdown_ss_raw else "" - - # OCR结果验证:检查倒计时识别结果是否为空 - if not countdown_mm_raw and not countdown_ss_raw: - try: - analyser._log_kv( - "验证", - "倒计时OCR结果完全为空", - level="WARNING", - ) - except Exception: - pass - elif not mm or not ss: - try: - analyser._log_kv( - "验证", - "倒计时OCR结果不完整", - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - mm_extracted=mm, - ss_extracted=ss, - level="WARNING", - ) - except Exception: - pass - - # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果) - try: - mm_int = int(mm) if mm else 0 - ss_int = int(ss) if ss else 0 - - # 数值范围验证 - if mm_int < 0 or mm_int >= 60: - try: - analyser._log_kv( - "验证", - "倒计时分钟数值超出合理范围", - mm=mm_int, - mm_raw=countdown_mm_raw, - level="WARNING", - ) - except Exception: - pass - - if ss_int >= 60: - try: - analyser._log_kv( - "验证", - "倒计时秒数>=60(可能是识别错误)", - mm=mm_int, - ss=ss_int, - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - level="WARNING", - ) - except Exception: - pass - elif ss_int < 0: - try: - analyser._log_kv( - "验证", - "倒计时秒数<0(可能是识别错误)", - ss=ss_int, - ss_raw=countdown_ss_raw, - level="WARNING", - ) - except Exception: - pass - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "验证倒计时数值失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - mm=mm, - ss=ss, - level="WARNING", - ) - except Exception: - pass - - if mm and ss: - time_text = f"{mm}:{ss}" - # 移除重复输出,因为并行OCR详情中已经包含了倒计时信息 - # try: - # analyser._log_kv( - # "福袋倒计时", - # "分割识别成功", - # mm_raw=countdown_mm_raw, - # ss_raw=countdown_ss_raw, - # result=time_text, - # ) - # except Exception: - # pass - else: - # 识别失败,time_text 保持为空字符串 - try: - analyser._log_kv( - "福袋倒计时", - "分割识别失败(分钟或秒为空)", - mm_raw=countdown_mm_raw, - ss_raw=countdown_ss_raw, - ) - except Exception: - pass - except Exception as e_inner: - # 异常时,time_text 保持为空字符串 - try: - analyser._log_kv( - "福袋倒计时", - "分割识别异常", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - # 移除重复输出,因为并行OCR详情中已经包含了倒计时信息 - # analyser._log_kv( - # "福袋", "识别倒计时", countdown=time_text if time_text else "未识别到" - # ) - - prize_value_yuan = extract_prize_value_yuan( - value_raw if value_raw is not None else "" - ) - - # OCR结果验证:检查价值识别结果 - if not value_raw: - try: - analyser._log_kv( - "验证", - "价值OCR结果为空", - level="WARNING", - ) - except Exception: - pass - elif prize_value_yuan: - # 验证价值数值是否合理 - try: - value_float = float(prize_value_yuan) - if value_float < 0: - try: - analyser._log_kv( - "验证", - "价值数值<0(可能是识别错误)", - value_yuan=prize_value_yuan, - value_raw=value_raw[:50] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - elif value_float > 100000: # 价值超过10万可能不合理 - try: - analyser._log_kv( - "验证", - "价值数值异常大(可能是识别错误)", - value_yuan=prize_value_yuan, - value_raw=value_raw[:50] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "验证价值数值失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - value_raw=value_raw[:50] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - - if float(prize_value_yuan).is_integer(): - show_value = int(prize_value_yuan) - else: - show_value = prize_value_yuan - # 移除重复输出,因为并行OCR详情中已经包含了奖品价值信息 - # analyser._log_kv("福袋", "识别奖品价值", value_yuan=show_value) - else: - # value_raw不为空但提取失败 - try: - analyser._log_kv( - "验证", - "价值OCR结果无法解析", - value_raw=value_raw[:100] if value_raw else "", - level="WARNING", - ) - except Exception: - pass - - # 处理直播间标题结果 - if live_room_title_raw or live_room_title_text_raw: - try: - analyser.current_room_title = live_room_title_raw - analyser.current_room_title_raw = live_room_title_text_raw - # 移除重复输出,因为并行OCR详情中已经包含了直播间标题信息 - # analyser._log_kv( - # "直播间标题", - # "OCR识别直播间标题", - # title=live_room_title_raw, - # raw_text=live_room_title_text_raw, - # log_type="INFO", - # ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "设置直播间标题结果失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - level="WARNING", - ) - except Exception: - pass - - # 在有福袋的情况下,记录完整OCR详情到映射表(即使标题未识别) - try: - room_pos = int(getattr(analyser, "room_pos", 0) or 0) - room_pos_map = getattr(analyser, "_room_pos_to_title_map", {}) - - # 兼容旧格式:若已有旧元组格式,先转为 dict - existing_info = room_pos_map.get(room_pos, {}) - base_info = {} - if isinstance(existing_info, dict): - base_info = dict(existing_info) - elif existing_info: - try: - base_info = { - "title": existing_info[0] if len(existing_info) > 0 else "", - "title_raw": existing_info[1] if len(existing_info) > 1 else "", - } - except Exception: - base_info = {} - - title_for_map = ( - live_room_title_raw - or base_info.get("title") - or str(getattr(analyser, "current_room_title", "") or "") - ) - title_raw_for_map = ( - live_room_title_text_raw - or base_info.get("title_raw") - or str(getattr(analyser, "current_room_title_raw", "") or "") - ) - - button_text_for_map = str(button_text_raw or "") or str( - getattr(analyser, "button_text_raw", "") or "" - ) - - room_info = dict(base_info) - room_info.update( - { - "title": title_for_map or "", - "title_raw": title_raw_for_map or "", - "has_fudai": True, - "fudai_content": fudai_content_text, - "fudai_detail": { - "content": fudai_content_text, - "task_list": str(task_list_raw or ""), - "countdown_mm": str(countdown_mm_raw or ""), - "countdown_ss": str(countdown_ss_raw or ""), - "time_text": time_text, - "participants": participants, - "copies": copies, - "prize_value_yuan": prize_value_yuan, - "value_raw": str(value_raw or ""), - "button_text": button_text_for_map, - "button_text_raw": str(button_text_raw or ""), - "live_room_title": str(live_room_title_raw or title_for_map or ""), - "live_room_title_raw": str( - live_room_title_text_raw or title_raw_for_map or "" - ), - "timestamp": time.time(), - }, - "timestamp": time.time(), - } - ) - - # 并行OCR 已生成完整的 fudai_detail,写入运行时映射表并落盘 - try: - room_pos_map[room_pos] = room_info - try: - analyser._room_pos_to_title_map = room_pos_map - except Exception: - pass - try: - from douyin.reservation import douyin_reservation_handler - - douyin_reservation_handler._dump_room_pos_map_to_state(analyser) - except Exception: - pass - try: - analyser._log_kv( - "预约", - "[预约] 并行OCR完成(已写入映射表并写盘)", - room_pos=room_pos, - title=(title_for_map[:30] if title_for_map else ""), - fudai_content=( - fudai_content_text[:30] if fudai_content_text else "" - ), - prize_value_yuan=prize_value_yuan, - log_type="DEBUG", - ) - except Exception: - pass - except Exception: - pass - - except Exception as e_update: - try: - analyser._log_kv( - "错误", - "并行OCR完成后记录映射表信息失败", - error=str(e_update), - level="WARNING", - ) - except Exception: - pass - - return fudai_content_text, time_text, participants, copies, prize_value_yuan - - -# check_contain 已迁移到 douyin.fudai.core.fudai_filter(顶部导入)。 -# 此处保留模块级名称以兼容历史 from douyin_fudai_core import check_contain。 - +__all__ = [ + "attend_choujiang", + "basic_join_decision", + "check_have_reward_notice_confirm", + "check_in_order_confirm_page", + "check_lucky_draw_result", + "extract_prize_value_yuan", + "get_fudai_contain", + "get_reward", + "is_watch_task_fudai", + "should_skip_fudai_by_config", +] diff --git a/douyin/fudai/douyin_fudai_core_legacy.py b/douyin/fudai/douyin_fudai_core_legacy.py new file mode 100644 index 0000000..02216da --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_legacy.py @@ -0,0 +1,30 @@ +"""douyin_fudai_core_legacy 兼容壳。""" + +from __future__ import annotations + +from .douyin_fudai_contain_impl import ( + attend_choujiang, + basic_join_decision, + check_have_reward_notice_confirm, + check_in_order_confirm_page, + check_lucky_draw_result, + extract_prize_value_yuan, + get_fudai_contain, + get_reward, + is_watch_task_fudai, + should_skip_fudai_by_config, +) + +__all__ = [ + "attend_choujiang", + "basic_join_decision", + "check_have_reward_notice_confirm", + "check_in_order_confirm_page", + "check_lucky_draw_result", + "extract_prize_value_yuan", + "get_fudai_contain", + "get_reward", + "is_watch_task_fudai", + "should_skip_fudai_by_config", +] + diff --git a/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py b/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py new file mode 100644 index 0000000..7a080d5 --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py @@ -0,0 +1,73 @@ +"""get_fudai_contain 的公共 helper。""" + +from __future__ import annotations + +import re +from typing import Any, Dict + + +def read_countdown_split(analyser, box: tuple[int, int, int, int], save_debug_images: bool) -> str: + """读取倒计时分片 OCR。""" + from douyin.fudai.douyin_fudai_core_pkg.countdown_split import ( + read_countdown_split as _impl, + ) + + return _impl(analyser, box, save_debug_images=save_debug_images) + + +def extract_participants_and_clean(text: str): + """从 OCR 文本提取参与人数/份数,并返回清洗后的文本。""" + if not text: + return 0, 0, "" + compact = re.sub(r"\s+", "", str(text)) + copies = 0 + participants = 0 + m = re.search(r"共(\d+)份", compact) + if m: + copies = int(m.group(1)) + m = re.search(r"(\d+)人已参与", compact) + if m: + participants = int(m.group(1)) + + cleaned = re.sub(r"共\d+份", "", compact) + cleaned = re.sub(r"\d+人已参与", "", cleaned) + return participants, copies, cleaned + + +def is_blank_text(text: Any) -> bool: + return len(str(text or "").strip()) == 0 + + +def should_use_heavy( + force_light: bool, + force_heavy: bool, + content_text: Any, + mm_raw: Any, + ss_raw: Any, + value_text: Any, + task_text: Any, + button_text: Any, +) -> set[str]: + """根据轻重模式与轻 OCR 结果决定是否触发重 OCR。""" + fields: set[str] = set() + if force_light: + return fields + if force_heavy or is_blank_text(content_text): + fields.add("content") + if force_heavy or not (mm_raw and ss_raw): + fields.update({"countdown_mm", "countdown_ss"}) + if force_heavy or is_blank_text(value_text): + fields.add("value") + if force_heavy or is_blank_text(task_text): + fields.add("task_list") + if force_heavy or is_blank_text(button_text): + fields.add("button") + return fields + + +def run_heavy_ocr(analyser, fields: set[str]) -> Dict[str, Any]: + """执行重 OCR。""" + from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import run_heavy_ocr as _impl + + return _impl(analyser, fields) + diff --git a/douyin/fudai/douyin_fudai_core_pkg/contain_postprocess.py b/douyin/fudai/douyin_fudai_core_pkg/contain_postprocess.py new file mode 100644 index 0000000..5952106 --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_pkg/contain_postprocess.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import time + + +def log_enter_live_latency(analyser, copies, participants) -> None: + try: + if getattr(analyser, "_enter_live_ts", 0.0) and not getattr( + analyser, "_enter_live_fudai_logged", False + ): + try: + secs = float(time.time() - float(analyser._enter_live_ts or 0.0)) + except Exception: + secs = -1.0 + reason = str(getattr(analyser, "_enter_live_reason", "") or "") + analyser._log_kv( + "性能", + "进入直播间到识别福袋耗时", + seconds=round(secs, 2), + enter_reason=reason, + ) + try: + analyser._enter_live_fudai_logged = True + except Exception: + pass + if copies: + analyser._log_kv( + "福袋", + "识别福袋信息", + copies=copies, + participants=participants if participants else 0, + ) + except Exception: + pass + + +def validate_value_ocr(analyser, value_raw, prize_value_yuan) -> None: + if not value_raw: + try: + analyser._log_kv("验证", "价值OCR结果为空", level="WARNING") + except Exception: + pass + return + + if prize_value_yuan: + try: + value_float = float(prize_value_yuan) + if value_float < 0: + try: + analyser._log_kv( + "验证", + "价值数值<0(可能是识别错误)", + value_yuan=prize_value_yuan, + value_raw=value_raw[:50] if value_raw else "", + level="WARNING", + ) + except Exception: + pass + elif value_float > 100000: + try: + analyser._log_kv( + "验证", + "价值数值异常大(可能是识别错误)", + value_yuan=prize_value_yuan, + value_raw=value_raw[:50] if value_raw else "", + level="WARNING", + ) + except Exception: + pass + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + "验证价值数值失败", + error=str(e_inner), + error_type=type(e_inner).__name__, + value_raw=value_raw[:50] if value_raw else "", + level="WARNING", + ) + except Exception: + pass + return + + try: + analyser._log_kv( + "验证", + "价值OCR结果无法解析", + value_raw=value_raw[:100] if value_raw else "", + level="WARNING", + ) + except Exception: + pass + + +def update_live_room_title(analyser, live_room_title_raw, live_room_title_text_raw) -> None: + if not (live_room_title_raw or live_room_title_text_raw): + return + try: + analyser.current_room_title = live_room_title_raw + analyser.current_room_title_raw = live_room_title_text_raw + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + "设置直播间标题结果失败", + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + + +def persist_room_detail_map( + analyser, + fudai_content_text, + task_list_raw, + countdown_mm_raw, + countdown_ss_raw, + time_text, + participants, + copies, + prize_value_yuan, + value_raw, + button_text_raw, + live_room_title_raw, + live_room_title_text_raw, +) -> None: + try: + room_pos = int(getattr(analyser, "room_pos", 0) or 0) + room_pos_map = getattr(analyser, "_room_pos_to_title_map", {}) + existing_info = room_pos_map.get(room_pos, {}) + base_info = {} + if isinstance(existing_info, dict): + base_info = dict(existing_info) + elif existing_info: + try: + base_info = { + "title": existing_info[0] if len(existing_info) > 0 else "", + "title_raw": existing_info[1] if len(existing_info) > 1 else "", + } + except Exception: + base_info = {} + + title_for_map = ( + live_room_title_raw + or base_info.get("title") + or str(getattr(analyser, "current_room_title", "") or "") + ) + title_raw_for_map = ( + live_room_title_text_raw + or base_info.get("title_raw") + or str(getattr(analyser, "current_room_title_raw", "") or "") + ) + button_text_for_map = str(button_text_raw or "") or str( + getattr(analyser, "button_text_raw", "") or "" + ) + + now_ts = time.time() + room_info = dict(base_info) + room_info.update( + { + "title": title_for_map or "", + "title_raw": title_raw_for_map or "", + "has_fudai": True, + "fudai_content": fudai_content_text, + "fudai_detail": { + "content": fudai_content_text, + "task_list": str(task_list_raw or ""), + "countdown_mm": str(countdown_mm_raw or ""), + "countdown_ss": str(countdown_ss_raw or ""), + "time_text": time_text, + "participants": participants, + "copies": copies, + "prize_value_yuan": prize_value_yuan, + "value_raw": str(value_raw or ""), + "button_text": button_text_for_map, + "button_text_raw": str(button_text_raw or ""), + "live_room_title": str(live_room_title_raw or title_for_map or ""), + "live_room_title_raw": str( + live_room_title_text_raw or title_raw_for_map or "" + ), + "timestamp": now_ts, + }, + "timestamp": now_ts, + } + ) + + try: + room_pos_map[room_pos] = room_info + try: + analyser._room_pos_to_title_map = room_pos_map + except Exception: + pass + try: + from douyin.reservation import douyin_reservation_handler + + douyin_reservation_handler._dump_room_pos_map_to_state(analyser) + except Exception: + pass + try: + analyser._log_kv( + "预约", + "[预约] 并行OCR完成(已写入映射表并写盘)", + room_pos=room_pos, + title=(title_for_map[:30] if title_for_map else ""), + fudai_content=(fudai_content_text[:30] if fudai_content_text else ""), + prize_value_yuan=prize_value_yuan, + log_type="DEBUG", + ) + except Exception: + pass + except Exception: + pass + except Exception as e_update: + try: + analyser._log_kv( + "错误", + "并行OCR完成后记录映射表信息失败", + error=str(e_update), + level="WARNING", + ) + except Exception: + pass diff --git a/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py b/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py index 2209eb6..c1aa81c 100644 --- a/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py +++ b/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py @@ -70,6 +70,10 @@ def cut_detail_regions( # 2. 倒计时区域分割(与候选切图保持一致,避免分钟框吃到前缀噪声) x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) + h = max(1, int(y2 - y1)) + # 纵向只取数字行:上方常有“超级福袋”等标题,容易让分钟误识别成 601。 + digit_y1 = min(y2 - 2, y1 + max(1, int(h * 0.34))) + digit_y2 = min(y2, max(digit_y1 + 2, y1 + max(2, int(h * 0.92)))) mm_x1 = x1 mm_x2 = min(x2, x1 + max(1, int(w * 0.26))) ss_x1 = min(x2 - 1, x1 + max(1, int(w * 0.38))) @@ -80,13 +84,19 @@ def cut_detail_regions( _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_分钟", - (mm_x1, y1, mm_x2, y2), + (mm_x1, digit_y1, mm_x2, digit_y2), analyser.y_pianyi, ) except Exception: pass analyser.cut_pic( - mm_x1, y1, mm_x2, y2, "", "福袋倒计时_分钟", analyser.y_pianyi + mm_x1, + digit_y1, + mm_x2, + digit_y2, + "", + "福袋倒计时_分钟", + analyser.y_pianyi, ) if save_debug_images and _save_full_screenshot_with_ocr_region is not None: @@ -94,13 +104,19 @@ def cut_detail_regions( _save_full_screenshot_with_ocr_region( analyser, "福袋倒计时_秒", - (ss_x1, y1, ss_x2, y2), + (ss_x1, digit_y1, ss_x2, digit_y2), analyser.y_pianyi, ) except Exception: pass analyser.cut_pic( - ss_x1, y1, ss_x2, y2, "", "福袋倒计时_秒", analyser.y_pianyi + ss_x1, + digit_y1, + ss_x2, + digit_y2, + "", + "福袋倒计时_秒", + analyser.y_pianyi, ) # 3. 福袋价值 diff --git a/douyin/fudai/douyin_fudai_core_pkg/parallel_exec.py b/douyin/fudai/douyin_fudai_core_pkg/parallel_exec.py new file mode 100644 index 0000000..55cb03e --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_pkg/parallel_exec.py @@ -0,0 +1,30 @@ +"""并行 OCR 任务提交与结果收集工具。""" + +from __future__ import annotations + +import time +from typing import Any, Callable, Dict, Tuple + + +def run_parallel_tasks( + task_funcs: Dict[str, Callable[[], Any]], + executor, +) -> Tuple[Dict[str, Any], Dict[str, float]]: + """提交并行任务并收集结果与耗时。""" + futures: Dict[str, Any] = {} + start_ts: Dict[str, float] = {} + for name, func in task_funcs.items(): + start_ts[name] = time.time() + futures[name] = executor.submit(func) + + results: Dict[str, Any] = {} + durations: Dict[str, float] = {} + for name, fut in futures.items(): + try: + results[name] = fut.result() + finally: + durations[name] = round( + (time.time() - start_ts.get(name, time.time())) * 1000, 1 + ) + return results, durations + diff --git a/douyin/fudai/douyin_fudai_core_pkg/watch_task.py b/douyin/fudai/douyin_fudai_core_pkg/watch_task.py new file mode 100644 index 0000000..e5a942d --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_pkg/watch_task.py @@ -0,0 +1,121 @@ +"""观看任务检测相关 helper。""" + +from __future__ import annotations + +from douyin.fudai.core.fudai_filter import is_watch_task_fudai + + +def handle_task_list_watch_task(analyser, task_list_raw, *, fallback: bool = False) -> bool: + """检查任务列表是否为观看任务;命中时写日志并设置标志。""" + if not task_list_raw: + return False + + area_msg = "OCR识别任务列表区域(备用并行)" if fallback else "OCR识别任务列表区域" + fail_msg = "记录备用任务列表OCR结果日志失败" if fallback else "记录任务列表OCR结果日志失败" + hit_fail_msg = "记录备用观看任务检测日志失败" if fallback else "记录观看任务检测日志失败" + set_fail_msg = "设置备用观看任务标志失败" if fallback else "设置观看任务标志失败" + + try: + analyser._log_kv( + "福袋", + area_msg, + task_list_text=task_list_raw[:200] if task_list_raw else "", + ) + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + fail_msg, + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + + if not is_watch_task_fudai(str(task_list_raw)): + return False + + try: + analyser._log_kv( + "福袋", + "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", + task_list_text=task_list_raw[:200] if task_list_raw else "", + ) + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + hit_fail_msg, + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + + try: + analyser._is_watch_task_detected = True + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + set_fail_msg, + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + return True + + +def handle_content_watch_task(analyser, content_text, *, cleaned: bool = False) -> bool: + """检查内容文本是否为观看任务;命中时写日志并设置标志。""" + if not content_text: + return False + + if not is_watch_task_fudai(str(content_text)): + return False + + msg = ( + "OCR识别到'观看X分钟'类任务(清理后检测),直接跳过后续处理" + if cleaned + else "OCR识别到'观看X分钟'类任务,直接跳过后续处理" + ) + detail_key = "content" if cleaned else "raw_content" + fail_msg = "记录观看任务检测日志失败" + set_fail_msg = "设置观看任务标志失败" + + try: + analyser._log_kv( + "福袋", + msg, + **{detail_key: str(content_text)[:100]}, + ) + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + fail_msg, + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + + try: + analyser._is_watch_task_detected = True + except Exception as e_inner: + try: + analyser._log_kv( + "错误", + set_fail_msg, + error=str(e_inner), + error_type=type(e_inner).__name__, + level="WARNING", + ) + except Exception: + pass + return True diff --git a/douyin/fudai/douyin_fudai_finder_pkg/detector.py b/douyin/fudai/douyin_fudai_finder_pkg/detector.py index c2889d4..bd295e9 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/detector.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/detector.py @@ -14,6 +14,11 @@ from typing import Any, Dict, Optional, Tuple from PIL import Image from .detect_by_template import detect_by_template as _impl_detect_by_template +from .detector_helpers import ( + build_confirm_region, + is_template_match_enabled, + should_trust_pixel_when_template_fails, +) from douyin.core import path_config @@ -471,13 +476,7 @@ class FudaiDetector: """ overall_start = time.time() - # 检查是否启用模板匹配 - try: - template_match_enabled = bool( - getattr(self.analyser, "fudai_template_match_enabled", False) - ) - except Exception: - template_match_enabled = False # 默认关闭模板匹配 + template_match_enabled = is_template_match_enabled(self.analyser) # 按优先级搜索 regions_checked = [] @@ -507,29 +506,9 @@ class FudaiDetector: # 在整个检测区域内进行模板匹配,而不是只在检测位置附近 # 这样可以处理像素检测位置偏差的情况 try: - width, height = pic.size - - # 确定Y范围(与检测区域相同) - if "y_top" in region and "y_bottom" in region: - confirm_y_top = max(0, min(int(region.get("y_top", 0)), height)) - confirm_y_bottom = max( - 0, min(int(region.get("y_bottom", height)), height) - ) - else: - scan_y = region.get("y", 0) - y_range = region.get("y_range", 7) - confirm_y_top = max(0, scan_y - y_range // 2) - confirm_y_bottom = min(height, scan_y + y_range // 2 + 1) - - # 使用整个检测区域进行模板匹配确认(而不是只在检测位置附近) - # 这样可以处理像素检测位置偏差的情况 - confirm_region = { - "name": f"{region['name']}-模板确认", - "x1": max(0, min(region.get("x1", 0), width)), - "x2": max(0, min(region.get("x2", width), width)), - "y_top": confirm_y_top, - "y_bottom": confirm_y_bottom, - } + confirm_region = build_confirm_region(pic.size, region) + confirm_y_top = confirm_region["y_top"] + confirm_y_bottom = confirm_region["y_bottom"] # 进行模板匹配确认(在整个检测区域内搜索) template_confirmed_x = self.detect_by_template(pic, confirm_region) @@ -554,16 +533,7 @@ class FudaiDetector: else: # 模板匹配未确认,检查是否应该信任像素检测结果 # 检查配置:是否允许在模板匹配失败时信任像素检测 - try: - trust_pixel_when_template_fails = bool( - getattr( - self.analyser, - "fudai_trust_pixel_when_template_fails", - True, - ) - ) - except Exception: - trust_pixel_when_template_fails = True # 默认信任 + trust_pixel_when_template_fails = should_trust_pixel_when_template_fails(self.analyser) # 如果配置允许,且像素检测在可信区域命中,信任像素检测 if trust_pixel_when_template_fails: diff --git a/douyin/fudai/douyin_fudai_finder_pkg/detector_helpers.py b/douyin/fudai/douyin_fudai_finder_pkg/detector_helpers.py new file mode 100644 index 0000000..f3d4282 --- /dev/null +++ b/douyin/fudai/douyin_fudai_finder_pkg/detector_helpers.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from typing import Any, Dict + + +def is_template_match_enabled(analyser: Any) -> bool: + try: + return bool(getattr(analyser, "fudai_template_match_enabled", False)) + except Exception: + return False + + +def should_trust_pixel_when_template_fails(analyser: Any) -> bool: + try: + return bool(getattr(analyser, "fudai_trust_pixel_when_template_fails", True)) + except Exception: + return True + + +def build_confirm_region(pic_size: tuple[int, int], region: Dict) -> Dict: + width, height = pic_size + if "y_top" in region and "y_bottom" in region: + confirm_y_top = max(0, min(int(region.get("y_top", 0)), height)) + confirm_y_bottom = max(0, min(int(region.get("y_bottom", height)), height)) + else: + scan_y = region.get("y", 0) + y_range = region.get("y_range", 7) + confirm_y_top = max(0, scan_y - y_range // 2) + confirm_y_bottom = min(height, scan_y + y_range // 2 + 1) + return { + "name": f"{region['name']}-模板确认", + "x1": max(0, min(region.get("x1", 0), width)), + "x2": max(0, min(region.get("x2", width), width)), + "y_top": confirm_y_top, + "y_bottom": confirm_y_bottom, + } diff --git a/douyin/handlers/douyin_screenshot_handler.py b/douyin/handlers/douyin_screenshot_handler.py index 84f14f0..24053a4 100644 --- a/douyin/handlers/douyin_screenshot_handler.py +++ b/douyin/handlers/douyin_screenshot_handler.py @@ -12,6 +12,7 @@ from __future__ import annotations import os import shutil +import time from typing import Any, Tuple @@ -124,3 +125,197 @@ class ScreenshotHandler: pass except Exception: pass + + @staticmethod # type: ignore[misc] + def capture_roi_screenshot( + analyser: Any, label: str, sx: int, sy: int, size: int, screenshot_path: str = None + ) -> str: + """捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。""" + try: + from douyin.core import path_config + from PIL import Image, UnidentifiedImageError # type: ignore[import] + import io + + if screenshot_path is None: + try: + analyser.operation.get_screenshot(analyser.device_id, use_service=False) + except Exception: + pass + pic_path = path_config.get_screenshot_path() + else: + pic_path = screenshot_path + if not os.path.exists(pic_path): + return "" + + half = int(size // 2) + left = int(max(0, sx - half)) + top = int(max(0, sy - half)) + right = int(sx + half) + bottom = int(sy + half) + + data = None + for _attempt in range(6): + try: + try: + analyser.operation.get_screenshot(analyser.device_id, use_service=False) + except Exception: + pass + if not os.path.exists(pic_path): + time.sleep(0.08) + continue + if os.path.getsize(pic_path) < 1024: + time.sleep(0.08) + continue + with open(pic_path, "rb") as f: + data = f.read() + if not data or not data.startswith(b"\x89PNG") or b"IEND" not in data[-512:]: + data = None + time.sleep(0.08) + continue + try: + img_test = Image.open(io.BytesIO(data)) + img_test.verify() + except Exception: + data = None + time.sleep(0.08) + continue + break + except Exception: + data = None + time.sleep(0.08) + if not data: + return "" + + try: + img = Image.open(io.BytesIO(data)) + img.load() + except UnidentifiedImageError: + return "" + except Exception: + try: + try: + analyser.operation.get_screenshot(analyser.device_id, use_service=False) + except Exception: + pass + with open(pic_path, "rb") as f: + data2 = f.read() + if not (data2 and data2.startswith(b"\x89PNG") and b"IEND" in data2[-512:]): + return "" + img = Image.open(io.BytesIO(data2)) + img.load() + except Exception: + return "" + + w, h = img.size + left = max(0, min(left, w - 1)) + top = max(0, min(top, h - 1)) + right = max(1, min(right, w)) + bottom = max(1, min(bottom, h)) + + roi = img.crop((left, top, right, bottom)) + img.close() + out_dir = path_config.get_pic_dir() + os.makedirs(out_dir, exist_ok=True) + fname = f"roi_{label}_{getattr(analyser, '_run_id', 'run')}_{int(time.time())}.png" + out_path = os.path.join(out_dir, fname) + roi.save(out_path) + return out_path + except Exception: + try: + analyser._log_kv( + "截图", + "_capture_roi_screenshot 失败", + label=label, + sx=sx, + sy=sy, + size=size, + ) + except Exception: + pass + return "" + + @staticmethod # type: ignore[misc] + def match_icon_template( + analyser: Any, roi_path: str, template_path: str, threshold: float | None = None + ) -> Tuple[bool, float]: + """对比 ROI 与模板,返回 (detected, score)。""" + try: + if not roi_path or not os.path.exists(roi_path): + return False, 0.0 + if not template_path or not os.path.exists(template_path): + return False, 0.0 + + from PIL import Image # type: ignore[import] + import numpy as np # type: ignore[import] + + _roi_raw = Image.open(roi_path) + _tpl_raw = Image.open(template_path) + try: + roi_img = _roi_raw.convert("RGB") + tpl_img = _tpl_raw.convert("RGB") + finally: + _roi_raw.close() + _tpl_raw.close() + + rw, rh = roi_img.size + tw, th = tpl_img.size + if tw > rw or th > rh: + scale = min(rw / tw, rh / th, 1.0) + tpl_img = tpl_img.resize((max(1, int(tw * scale)), max(1, int(th * scale))), Image.Resampling.LANCZOS) + + roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32) + tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32) + + if roi_gray.shape == tpl_gray.shape: + A = roi_gray.flatten() - roi_gray.flatten().mean() + B = tpl_gray.flatten() - tpl_gray.flatten().mean() + denom = np.linalg.norm(A) * np.linalg.norm(B) + if denom <= 1e-6: + return False, 0.0 + score = float(np.dot(A, B) / denom) + used_thr = float(threshold) if threshold is not None else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70) + return bool(score >= used_thr), float(score) + + ih, iw = roi_gray.shape + th, tw = tpl_gray.shape + if ih >= th and iw >= tw: + cy = max(0, min(ih // 2 - th // 2, ih - th)) + cx = max(0, min(iw // 2 - tw // 2, iw - tw)) + window = roi_gray[cy:cy + th, cx:cx + tw] + a = window.flatten() - window.flatten().mean() + b = tpl_gray.flatten() - tpl_gray.flatten().mean() + denom = np.linalg.norm(a) * np.linalg.norm(b) + score = float(np.dot(a, b) / denom) if denom > 1e-6 else -1.0 + if score >= 0.55: + used_thr = float(threshold) if threshold is not None else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70) + return bool(score >= used_thr), float(score) + + best = -1.0 + step_y = max(1, th // 6) + step_x = max(1, tw // 6) + for y in range(0, ih - th + 1, step_y): + for x in range(0, iw - tw + 1, step_x): + window = roi_gray[y:y + th, x:x + tw] + a = window.flatten() - window.flatten().mean() + b = tpl_gray.flatten() - tpl_gray.flatten().mean() + denom = np.linalg.norm(a) * np.linalg.norm(b) + if denom <= 1e-6: + continue + score = float(np.dot(a, b) / denom) + if score > best: + best = score + if best < -0.5: + return False, 0.0 + used_thr = float(threshold) if threshold is not None else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70) + return bool(best >= used_thr), float(best) + except Exception: + try: + analyser._log_kv( + "检测", + "_match_icon_template 异常", + roi_path=roi_path, + template_path=template_path, + ) + except Exception: + pass + return False, 0.0 diff --git a/douyin/handlers/screenshot_manager/save_image.py b/douyin/handlers/screenshot_manager/save_image.py index 93f3f5c..f3ae5b9 100644 --- a/douyin/handlers/screenshot_manager/save_image.py +++ b/douyin/handlers/screenshot_manager/save_image.py @@ -6,75 +6,38 @@ from __future__ import annotations (按 picname/operation_type/category 写入调试图像,支持异步队列)。 """ -import json import os import time -from datetime import datetime from typing import Optional, Tuple import logging -from PIL import Image, ImageDraw, ImageFont +from PIL import Image -from douyin.core import path_config +from .save_image_helpers import ( + annotate_debug_image, + build_debug_filename, + is_debug_captures_enabled, + maybe_auto_cleanup, + resolve_background_flag, + save_image_with_retry, + sanitize_filename_part as _sanitize_filename_part_impl, +) from ._common import ( _debug_save_queue, _mgr_log, _SKIP_DEBUG_SAVE_IN_HOTLOOPS, ) -from .cleanup import ( - _OPERATION_TYPE_CN, - _PICNAME_CN, - _STEP_CN, - _EXTRA_INFO_KEY_CN, - cleanup_debug_captures, - count_debug_captures_files, -) +from .cleanup import _EXTRA_INFO_KEY_CN, _OPERATION_TYPE_CN, _PICNAME_CN, _STEP_CN from .paths import ( ensure_debug_captures_dir, get_debug_captures_dir, - get_debug_captures_base_dir, ) from .async_save import _ensure_debug_save_worker_started def _sanitize_filename_part(text: str) -> str: - """清理文件名部分,移除Windows不允许的字符 - - 参数: - text: 要清理的文本 - - 返回: - 清理后的文本 - """ - if not text: - return "" - - # Windows文件名不允许的字符: < > : " / \ | ? * - # 同时移除路径分隔符和空格(用下划线替换) - invalid_chars = '<>:"/\\|?*' - sanitized = str(text) - - # 如果是路径,只保留文件名部分 - if os.sep in sanitized or "/" in sanitized: - sanitized = os.path.basename(sanitized) - - # 移除所有无效字符 - for char in invalid_chars: - sanitized = sanitized.replace(char, "_") - - # 移除连续的下划线,替换为单个下划线 - while "__" in sanitized: - sanitized = sanitized.replace("__", "_") - - # 移除首尾的下划线和空格 - sanitized = sanitized.strip("_").strip() - - # 如果清理后为空,返回默认值 - if not sanitized: - sanitized = "unknown" - - return sanitized + return _sanitize_filename_part_impl(text) @@ -108,213 +71,15 @@ def save_debug_image( # type: ignore 保存的文件路径,失败返回None """ try: - # 从配置读取是否启用调试图像保存;默认关闭 - try: - import json - - enabled = False - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - dbg_cfg = config.get("debug_captures") - if isinstance(dbg_cfg, dict): - enabled = bool(dbg_cfg.get("enabled", False)) - if not enabled: - return None - except Exception: - # 配置读取异常时,为安全起见直接跳过保存调试图像 + if not is_debug_captures_enabled(): return None - # 自动清理旧目录(仅在每天第一次保存时执行) - if auto_cleanup: - try: - # 检查今天是否已经清理过(使用简单的标记文件) - debug_base_dir = get_debug_captures_base_dir() - cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker") - from datetime import datetime - - today_str = datetime.now().strftime("%Y-%m-%d") - - # 读取标记文件,检查今天是否已清理 - need_cleanup = True - if os.path.exists(cleanup_marker): - try: - with open(cleanup_marker, "r", encoding="utf-8") as f: - last_cleanup_date = f.read().strip() - if last_cleanup_date == today_str: - need_cleanup = False - except Exception: - pass - - if need_cleanup: - # 从配置读取保留天数、最大文件数和自动清理设置 - keep_days = 7 # 默认7天 - max_files = 2000 # 默认2000个文件 - cleanup_enabled = True - try: - import json - - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - if "debug_captures" in config and isinstance( - config["debug_captures"], dict - ): - cleanup_enabled = config["debug_captures"].get( - "auto_cleanup", True - ) - keep_days = int( - config["debug_captures"].get("keep_days", 7) - ) - max_files = int( - config["debug_captures"].get("max_files", 2000) - ) - except Exception: - pass - - # 如果启用自动清理,执行清理 - if cleanup_enabled: - cleanup_debug_captures(keep_days=keep_days, max_files=max_files) - - # 更新标记文件(仅在执行清理后更新) - try: - with open(cleanup_marker, "w", encoding="utf-8") as f: - f.write(today_str) - except Exception: - pass - else: - # 即使今天已经清理过,也要检查文件数量是否超过限制 - # 如果超过,立即清理(不更新标记文件,避免频繁清理) - try: - import json - - config_path = path_config.get_config_path() - max_files = 2000 - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - if "debug_captures" in config and isinstance( - config["debug_captures"], dict - ): - max_files = int( - config["debug_captures"].get("max_files", 2000) - ) - - # 检查当前文件数量 - current_count = count_debug_captures_files() - if current_count > max_files: - # 文件数量超过限制,立即清理 - try: - _mgr_log( - f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理" - ) - except Exception: - pass - cleanup_debug_captures( - keep_days=999, max_files=max_files - ) # keep_days设为999表示只按文件数量清理 - except Exception: - pass - except Exception: - # 清理失败不影响保存操作 - pass + maybe_auto_cleanup(auto_cleanup, _mgr_log) ensure_debug_captures_dir() debug_dir = get_debug_captures_dir() - # 生成文件名 - from datetime import datetime - - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - - parts = [] - if operation_type: - # 转换为中文 - operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type) - parts.append(_sanitize_filename_part(operation_type_cn)) - if picname: - # 转换为中文 - picname_cn = _PICNAME_CN.get(picname, picname) - parts.append(_sanitize_filename_part(picname_cn)) - if step: - # 转换为中文 - step_cn = _STEP_CN.get(step, step) - parts.append(_sanitize_filename_part(step_cn)) - if coords: - parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") - if extra_info: - for key, value in extra_info.items(): - # 将键名转换为中文 - key_cn = _EXTRA_INFO_KEY_CN.get(key, key) - # 清理键名和值 - clean_key = _sanitize_filename_part(str(key_cn)) - # 处理值的转换(布尔值转为中文) - if isinstance(value, bool): - clean_value = "是" if value else "否" - else: - clean_value = _sanitize_filename_part(str(value)) - # 限制值的长度,避免文件名过长 - # 对于 text_preview 等长文本,限制更短(20字符) - if key == "text_preview" or key == "content": - if len(clean_value) > 20: - clean_value = clean_value[:20] - else: - if len(clean_value) > 30: - clean_value = clean_value[:30] - parts.append(f"{clean_key}_{clean_value}") - - filename_parts = [timestamp] + parts - filename = "_".join(str(p) for p in filename_parts if p) + ".png" - - # Windows文件名长度限制(260字符),自动截断 - # 考虑完整路径长度,文件名部分限制更严格 - max_len = 180 # 留更多余量,考虑目录路径长度 - if len(filename) > max_len: - # 保留时间戳和关键信息,截断其他部分 - # 优先保留:时间戳、操作类型、图片名、步骤 - base_parts = [timestamp] - if operation_type: - # 转换为中文 - operation_type_cn = _OPERATION_TYPE_CN.get( - operation_type, operation_type - ) - base_parts.append(_sanitize_filename_part(operation_type_cn)) - if picname: - # 转换为中文 - picname_cn = _PICNAME_CN.get(picname, picname) - base_parts.append(_sanitize_filename_part(picname_cn)) - if step: - # 转换为中文 - step_cn = _STEP_CN.get(step, step) - base_parts.append(_sanitize_filename_part(step_cn)) - - base = "_".join(base_parts) - - # 如果还有空间,添加最重要的额外信息(排除长文本) - remaining = max_len - len(base) - 10 # 留10字符余量 - if remaining > 20 and extra_info: - important_keys = ["mode", "size", "used_img2", "avg_confidence"] - for key in important_keys: - if key in extra_info and remaining > 0: - # 将键名转换为中文 - key_cn = _EXTRA_INFO_KEY_CN.get(key, key) - clean_key = _sanitize_filename_part(str(key_cn)) - # 处理值的转换(布尔值转为中文) - value = extra_info[key] - if isinstance(value, bool): - clean_value = "是" if value else "否" - else: - clean_value = _sanitize_filename_part(str(value)) - if len(clean_value) > 15: - clean_value = clean_value[:15] - part = f"{clean_key}_{clean_value}" - if len(part) <= remaining: - base += f"_{part}" - remaining -= len(part) + 1 - - filename = base[:max_len] + ".png" + filename = build_debug_filename(operation_type, picname, step, coords, extra_info) file_path = os.path.join(debug_dir, filename) @@ -324,75 +89,7 @@ def save_debug_image( # type: ignore except Exception: pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理 - # 根据配置决定是否后台保存(优先使用函数参数,参数为 None 时读取 config) - if background is None: - try: - import json - - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - cfg = json.load(f) - dbg_cfg = ( - cfg.get("debug_captures", {}) - if isinstance(cfg.get("debug_captures"), dict) - else {} - ) - background = bool(dbg_cfg.get("async_save", True)) - else: - background = True - except Exception: - background = True - - # 保存图像的辅助函数,带重试机制 - def save_image_with_retry( - img_to_save: Image.Image, path: str, max_retries: int = 2 - ) -> bool: - """保存图像,如果目录不存在则创建后重试""" - last_error = None - for attempt in range(max_retries): - try: - img_to_save.save(path, "PNG") - return True - except FileNotFoundError as e: - # 目录不存在,尝试创建后重试 - last_error = e - if attempt < max_retries - 1: - try: - ensure_debug_captures_dir() - except Exception as dir_error: - # 记录目录创建失败 - try: - _mgr_log( - f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" - ) - except Exception: - pass - else: - # 最后一次尝试失败,抛出异常 - raise - except PermissionError as e: - # 权限错误,不重试 - try: - _mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") - except Exception: - pass - raise - except OSError as e: - # 系统级错误(磁盘空间不足等),不重试 - try: - _mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") - except Exception: - pass - raise - except Exception as e: - # 其他异常直接抛出 - last_error = e - raise - # 所有重试都失败 - if last_error: - raise last_error - return False + background = resolve_background_flag(background) # 如果选择后台保存,入队并返回 None(不阻塞主线程) if background: @@ -449,230 +146,14 @@ def save_debug_image( # type: ignore # 如果需要标注,在图像上添加信息 if annotate and (coords or extra_info): try: - from PIL import ImageDraw, ImageFont - - annotated_image = image.copy() - draw = ImageDraw.Draw(annotated_image) - - # 尝试使用默认字体 - try: - font = ImageFont.truetype("arial.ttf", 12) - except Exception: - try: - font = ImageFont.load_default() - except Exception: - font = None - - # 绘制坐标框 - if coords: - x1, y1, x2, y2 = coords - # 确保坐标在图像范围内 - img_w, img_h = annotated_image.size - x1 = max(0, min(x1, img_w - 1)) - y1 = max(0, min(y1, img_h - 1)) - x2 = max(0, min(x2, img_w - 1)) - y2 = max(0, min(y2, img_h - 1)) - - if x1 < x2 and y1 < y2: - # 使用元组格式 (x1, y1, x2, y2) - rect_coords: Tuple[float, float, float, float] = ( - float(x1), - float(y1), - float(x2), - float(y2), - ) - draw.rectangle(rect_coords, outline="red", width=2) - - # 添加文本信息:统一使用底部半透明信息栏,风格与 OCR 调试图一致 - try: - info_lines = [] - # 基础信息行:图片名 / 步骤 - if picname: - info_lines.append(str(_PICNAME_CN.get(picname, picname))) - if step: - info_lines.append(str(_STEP_CN.get(step, step))) - - # 坐标与额外信息优先展示重要字段 - if coords: - info_lines.append( - f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})" - ) - - if extra_info: - # 组织额外信息为若干行,按重要字段顺序展示 - important_keys = [ - "result", - "detected_x", - "detected_x_scaled", - "match_score", - "mode", - "size", - "avg_confidence", - "text_preview", - ] - for key in important_keys: - if key in extra_info: - info_lines.append( - f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}" - ) - # 将其余的键也加入(但限制长度) - for k, v in extra_info.items(): - if k in important_keys: - continue - # 限制文本长度,避免溢出 - s = str(v) - if len(s) > 30: - s = s[:30] + "..." - info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(k, k)}: {s}") - - # 如果没有任何信息,则不绘制信息栏 - if info_lines: - # 准备RGBA图层以绘制半透明底栏 - if annotated_image.mode != "RGBA": - annotated_image = annotated_image.convert("RGBA") - overlay = Image.new("RGBA", annotated_image.size, (0, 0, 0, 0)) - odraw = ImageDraw.Draw(overlay) - - # 计算文字区域高度 - padding_v = 6 - padding_h = 8 - max_width = annotated_image.size[0] - padding_h * 2 - lines_to_draw = [] - - # Helper to measure text size in a Pillow-version-safe way. - def _measure_text(text: str): - try: - # Preferred: ImageDraw.textbbox -> returns (left, top, right, bottom) - if hasattr(odraw, "textbbox"): - l, t, r, b = odraw.textbbox((0, 0), text, font=font) - return (r - l, b - t) - # Fallbacks using ImageFont methods compatible with different Pillow versions - if font is not None: - # Prefer font.getbbox if available - if hasattr(font, "getbbox"): - try: - l, t, r, b = font.getbbox(text) - return (r - l, b - t) - except Exception: - pass - # Fallback: use font.getmask to get rendered size - try: - mask = font.getmask(text) - return (mask.size[0], mask.size[1]) - except Exception: - pass - # Last resort: ImageDraw.textsize (may not exist in Pillow >= 10) - if hasattr(odraw, "textsize"): - try: - return ( - odraw.textsize(text, font=font) - if font is not None - else odraw.textsize(text) - ) - except Exception: - pass - except Exception: - pass - # Conservative fallback estimate - return (len(text) * 7, 14) - - for line in info_lines: - # 简单换行:如果太长,切断 - w, h = _measure_text(line) - if w > max_width: - # 估算每行能容纳的字符数并切断 - approx_chars = max( - 10, int(len(line) * max_width / max(int(w), 1)) - ) - lines_to_draw.append(line[:approx_chars] + "...") - else: - lines_to_draw.append(line) - - # Compute line height using safe measurement - try: - line_height = _measure_text("Ay")[1] - except Exception: - line_height = 14 - bar_height = padding_v * 2 + line_height * len(lines_to_draw) - img_w, img_h = annotated_image.size - bar_y1 = img_h - bar_height - bar_y2 = img_h - - # 绘制半透明白色底栏 - odraw.rectangle( - (0, bar_y1, img_w, bar_y2), fill=(255, 255, 255, 200) - ) - - # 绘制文字(黑色) - text_x = padding_h - text_y = bar_y1 + padding_v - for line in lines_to_draw: - try: - odraw.text( - (text_x, text_y), - line, - fill=(10, 10, 10, 255), - font=font, - ) - except Exception: - try: - odraw.text( - (text_x, text_y), line, fill=(10, 10, 10, 255) - ) - except Exception: - pass - text_y += line_height - - # 如果 extra_info 中包含匹配坐标(match_coords)或检测像素坐标(detected_x_scaled),绘制点/框以便快速定位 - try: - if extra_info: - # 模板匹配提供 match_coords 字段(tuple) - if ( - "match_coords" in extra_info - and isinstance( - extra_info["match_coords"], (list, tuple) - ) - and len(extra_info["match_coords"]) == 4 - ): - mx1, my1, mx2, my2 = extra_info["match_coords"] - # 在 overlay 上画红框 - odraw.rectangle( - (mx1, my1, mx2, my2), - outline=(255, 0, 0, 200), - width=2, - ) - # 像素检测提供 detected_x_scaled:图像坐标系中的x(单点),并依赖 coords 提供 y 区域 - elif "detected_x_scaled" in extra_info and coords: - try: - dx = int(extra_info["detected_x_scaled"]) - cy = (coords[1] + coords[3]) // 2 - r = max( - 4, int(min(annotated_image.size) * 0.01) - ) - odraw.ellipse( - [dx - r, cy - r, dx + r, cy + r], - fill=(0, 128, 255, 220), - outline=(0, 64, 192, 220), - ) - except Exception: - pass - except Exception: - pass - - # 合并 overlay 到原图并保存 - try: - annotated_image = Image.alpha_composite( - annotated_image, overlay - ) - # 转回 RGB 保存为PNG,以减少兼容问题 - annotated_image = annotated_image.convert("RGB") - except Exception: - pass - except Exception: - # 标注失败,回退到原有行为(什么也不画) - pass - - save_image_with_retry(annotated_image, file_path) + annotated_image = annotate_debug_image( + image=image, + picname=picname, + step=step, + coords=coords, + extra_info=extra_info, + ) + save_image_with_retry(annotated_image, file_path, ensure_debug_captures_dir) except (PermissionError, OSError) as e: # 权限或系统错误,尝试保存原图 try: @@ -680,7 +161,7 @@ def save_debug_image( # type: ignore _mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") except Exception: pass - save_image_with_retry(image, file_path) + save_image_with_retry(image, file_path, ensure_debug_captures_dir) except Exception: # 如果保存原图也失败,抛出异常让外层处理 raise @@ -691,12 +172,12 @@ def save_debug_image( # type: ignore _mgr_log(f"[截图管理] 图像标注失败,尝试保存原图: {e}") except Exception: pass - save_image_with_retry(image, file_path) + save_image_with_retry(image, file_path, ensure_debug_captures_dir) except Exception: # 如果保存原图也失败,抛出异常让外层处理 raise else: - save_image_with_retry(image, file_path) + save_image_with_retry(image, file_path, ensure_debug_captures_dir) return file_path except FileNotFoundError as e: diff --git a/douyin/handlers/screenshot_manager/save_image_helpers.py b/douyin/handlers/screenshot_manager/save_image_helpers.py new file mode 100644 index 0000000..eff7180 --- /dev/null +++ b/douyin/handlers/screenshot_manager/save_image_helpers.py @@ -0,0 +1,368 @@ +from __future__ import annotations + +"""save_image 的辅助函数:清理策略、文件名构造、后台保存开关。""" + +import json +import os +from datetime import datetime +from typing import Optional, Tuple +from PIL import Image, ImageDraw, ImageFont + +from douyin.core import path_config + +from .cleanup import ( + _EXTRA_INFO_KEY_CN, + _OPERATION_TYPE_CN, + _PICNAME_CN, + _STEP_CN, + cleanup_debug_captures, + count_debug_captures_files, +) +from .paths import get_debug_captures_base_dir +from ._common import _mgr_log + + +def is_debug_captures_enabled() -> bool: + try: + enabled = False + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + dbg_cfg = config.get("debug_captures") + if isinstance(dbg_cfg, dict): + enabled = bool(dbg_cfg.get("enabled", False)) + return enabled + except Exception: + return False + + +def sanitize_filename_part(text: str) -> str: + if not text: + return "" + invalid_chars = '<>:"/\\|?*' + sanitized = str(text) + if os.sep in sanitized or "/" in sanitized: + sanitized = os.path.basename(sanitized) + for char in invalid_chars: + sanitized = sanitized.replace(char, "_") + while "__" in sanitized: + sanitized = sanitized.replace("__", "_") + sanitized = sanitized.strip("_").strip() + return sanitized or "unknown" + + +def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None: + if not auto_cleanup: + return + try: + debug_base_dir = get_debug_captures_base_dir() + cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker") + today_str = datetime.now().strftime("%Y-%m-%d") + + need_cleanup = True + if os.path.exists(cleanup_marker): + try: + with open(cleanup_marker, "r", encoding="utf-8") as f: + if f.read().strip() == today_str: + need_cleanup = False + except Exception: + pass + + if need_cleanup: + keep_days = 7 + max_files = 2000 + cleanup_enabled = True + try: + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + dbg = config.get("debug_captures") + if isinstance(dbg, dict): + cleanup_enabled = dbg.get("auto_cleanup", True) + keep_days = int(dbg.get("keep_days", 7)) + max_files = int(dbg.get("max_files", 2000)) + except Exception: + pass + if cleanup_enabled: + cleanup_debug_captures(keep_days=keep_days, max_files=max_files) + try: + with open(cleanup_marker, "w", encoding="utf-8") as f: + f.write(today_str) + except Exception: + pass + return + + try: + config_path = path_config.get_config_path() + max_files = 2000 + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + dbg = config.get("debug_captures") + if isinstance(dbg, dict): + max_files = int(dbg.get("max_files", 2000)) + current_count = count_debug_captures_files() + if current_count > max_files: + try: + mgr_log(f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理") + except Exception: + pass + cleanup_debug_captures(keep_days=999, max_files=max_files) + except Exception: + pass + except Exception: + pass + + +def build_debug_filename( + operation_type: str, + picname: str, + step: str, + coords: Optional[Tuple[int, int, int, int]], + extra_info: Optional[dict], +) -> str: + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + parts = [] + if operation_type: + parts.append(sanitize_filename_part(_OPERATION_TYPE_CN.get(operation_type, operation_type))) + if picname: + parts.append(sanitize_filename_part(_PICNAME_CN.get(picname, picname))) + if step: + parts.append(sanitize_filename_part(_STEP_CN.get(step, step))) + if coords: + parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") + if extra_info: + for key, value in extra_info.items(): + key_cn = _EXTRA_INFO_KEY_CN.get(key, key) + clean_key = sanitize_filename_part(str(key_cn)) + clean_value = "是" if isinstance(value, bool) and value else ("否" if isinstance(value, bool) else sanitize_filename_part(str(value))) + if key in ("text_preview", "content"): + if len(clean_value) > 20: + clean_value = clean_value[:20] + elif len(clean_value) > 30: + clean_value = clean_value[:30] + parts.append(f"{clean_key}_{clean_value}") + + filename_parts = [timestamp] + parts + filename = "_".join(str(p) for p in filename_parts if p) + ".png" + + max_len = 180 + if len(filename) <= max_len: + return filename + + base_parts = [timestamp] + if operation_type: + base_parts.append(sanitize_filename_part(_OPERATION_TYPE_CN.get(operation_type, operation_type))) + if picname: + base_parts.append(sanitize_filename_part(_PICNAME_CN.get(picname, picname))) + if step: + base_parts.append(sanitize_filename_part(_STEP_CN.get(step, step))) + base = "_".join(base_parts) + remaining = max_len - len(base) - 10 + if remaining > 20 and extra_info: + for key in ["mode", "size", "used_img2", "avg_confidence"]: + if key in extra_info and remaining > 0: + clean_key = sanitize_filename_part(str(_EXTRA_INFO_KEY_CN.get(key, key))) + value = extra_info[key] + clean_value = "是" if isinstance(value, bool) and value else ("否" if isinstance(value, bool) else sanitize_filename_part(str(value))) + if len(clean_value) > 15: + clean_value = clean_value[:15] + part = f"{clean_key}_{clean_value}" + if len(part) <= remaining: + base += f"_{part}" + remaining -= len(part) + 1 + return base[:max_len] + ".png" + + +def resolve_background_flag(background: Optional[bool]) -> bool: + if background is not None: + return bool(background) + try: + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + cfg = json.load(f) + dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} + return bool(dbg_cfg.get("async_save", True)) + except Exception: + pass + return True + + +def save_image_with_retry( + img_to_save: Image.Image, path: str, ensure_debug_captures_dir, max_retries: int = 2 +) -> bool: + last_error = None + for attempt in range(max_retries): + try: + img_to_save.save(path, "PNG") + return True + except FileNotFoundError as e: + last_error = e + if attempt < max_retries - 1: + try: + ensure_debug_captures_dir() + except Exception as dir_error: + try: + _mgr_log( + f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" + ) + except Exception: + pass + else: + raise + except PermissionError as e: + try: + _mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") + except Exception: + pass + raise + except OSError as e: + try: + _mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") + except Exception: + pass + raise + except Exception as e: + last_error = e + raise + if last_error: + raise last_error + return False + + +def annotate_debug_image( + image: Image.Image, + picname: str, + step: str, + coords: Optional[Tuple[int, int, int, int]], + extra_info: Optional[dict], +) -> Image.Image: + annotated_image = image.copy() + draw = ImageDraw.Draw(annotated_image) + try: + font = ImageFont.truetype("arial.ttf", 12) + except Exception: + try: + font = ImageFont.load_default() + except Exception: + font = None + + if coords: + x1, y1, x2, y2 = coords + img_w, img_h = annotated_image.size + x1 = max(0, min(x1, img_w - 1)) + y1 = max(0, min(y1, img_h - 1)) + x2 = max(0, min(x2, img_w - 1)) + y2 = max(0, min(y2, img_h - 1)) + if x1 < x2 and y1 < y2: + draw.rectangle((float(x1), float(y1), float(x2), float(y2)), outline="red", width=2) + + info_lines = [] + if picname: + info_lines.append(str(_PICNAME_CN.get(picname, picname))) + if step: + info_lines.append(str(_STEP_CN.get(step, step))) + if coords: + info_lines.append(f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") + if extra_info: + important_keys = [ + "result", + "detected_x", + "detected_x_scaled", + "match_score", + "mode", + "size", + "avg_confidence", + "text_preview", + ] + for key in important_keys: + if key in extra_info: + info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}") + for k, v in extra_info.items(): + if k in important_keys: + continue + s = str(v) + if len(s) > 30: + s = s[:30] + "..." + info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(k, k)}: {s}") + + if not info_lines: + return annotated_image + + if annotated_image.mode != "RGBA": + annotated_image = annotated_image.convert("RGBA") + overlay = Image.new("RGBA", annotated_image.size, (0, 0, 0, 0)) + odraw = ImageDraw.Draw(overlay) + + def _measure_text(text: str): + try: + if hasattr(odraw, "textbbox"): + l, t, r, b = odraw.textbbox((0, 0), text, font=font) + return (r - l, b - t) + if font is not None and hasattr(font, "getbbox"): + l, t, r, b = font.getbbox(text) + return (r - l, b - t) + if font is not None: + mask = font.getmask(text) + return (mask.size[0], mask.size[1]) + if hasattr(odraw, "textsize"): + return odraw.textsize(text, font=font) if font is not None else odraw.textsize(text) + except Exception: + pass + return (len(text) * 7, 14) + + padding_v = 6 + padding_h = 8 + max_width = annotated_image.size[0] - padding_h * 2 + lines_to_draw = [] + for line in info_lines: + w, _ = _measure_text(line) + if w > max_width: + approx_chars = max(10, int(len(line) * max_width / max(int(w), 1))) + lines_to_draw.append(line[:approx_chars] + "...") + else: + lines_to_draw.append(line) + + line_height = _measure_text("Ay")[1] + bar_height = padding_v * 2 + line_height * len(lines_to_draw) + img_w, img_h = annotated_image.size + bar_y1 = img_h - bar_height + odraw.rectangle((0, bar_y1, img_w, img_h), fill=(255, 255, 255, 200)) + + text_x = padding_h + text_y = bar_y1 + padding_v + for line in lines_to_draw: + try: + odraw.text((text_x, text_y), line, fill=(10, 10, 10, 255), font=font) + except Exception: + try: + odraw.text((text_x, text_y), line, fill=(10, 10, 10, 255)) + except Exception: + pass + text_y += line_height + + try: + if extra_info: + if ( + "match_coords" in extra_info + and isinstance(extra_info["match_coords"], (list, tuple)) + and len(extra_info["match_coords"]) == 4 + ): + mx1, my1, mx2, my2 = extra_info["match_coords"] + odraw.rectangle((mx1, my1, mx2, my2), outline=(255, 0, 0, 200), width=2) + elif "detected_x_scaled" in extra_info and coords: + dx = int(extra_info["detected_x_scaled"]) + cy = (coords[1] + coords[3]) // 2 + r = max(4, int(min(annotated_image.size) * 0.01)) + odraw.ellipse([dx - r, cy - r, dx + r, cy + r], fill=(0, 128, 255, 220), outline=(0, 64, 192, 220)) + except Exception: + pass + + try: + out = Image.alpha_composite(annotated_image, overlay) + return out.convert("RGB") + except Exception: + return image.copy() diff --git a/douyin/reservation/reservation_logic/add.py b/douyin/reservation/reservation_logic/add.py index 66c3008..8e6ecae 100644 --- a/douyin/reservation/reservation_logic/add.py +++ b/douyin/reservation/reservation_logic/add.py @@ -74,8 +74,7 @@ def add_reservation_core_logic( "预约", "[预约] add_reservation_core_logic 函数入口", log_type="OP", - future_ts=int(ft) if ft > 0 else 0, - future_str=ft_str, + 开奖时间=ft_str if ft_str else "未知", prize_value_yuan=prize_value, room_title=room_title[:50] if room_title else "", content=content[:50] if content else "", @@ -261,7 +260,11 @@ def add_reservation_core_logic( same_idx=same_idx, old_value_yuan=old_val, new_value_yuan=prize_value, - future_ts=int(ft) if ft > 0 else 0, + 开奖时间=( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "未知" + ), ) except Exception: pass @@ -274,7 +277,11 @@ def add_reservation_core_logic( same_idx=same_idx, old_value_yuan=old_val, new_value_yuan=prize_value, - future_ts=int(ft) if ft > 0 else 0, + 开奖时间=( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "未知" + ), ) except Exception: pass @@ -283,7 +290,11 @@ def add_reservation_core_logic( analyser._log_kv( "预约", "[预约] 添加新预约到队列", - future_ts=int(ft) if ft > 0 else 0, + 开奖时间=( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "未知" + ), prize_value_yuan=prize_value, queue_len_before=len(reservations), ) diff --git a/douyin/reservation/reservation_logic/attend_window.py b/douyin/reservation/reservation_logic/attend_window.py index 372461a..9f0bf3b 100644 --- a/douyin/reservation/reservation_logic/attend_window.py +++ b/douyin/reservation/reservation_logic/attend_window.py @@ -22,6 +22,15 @@ from .helpers import ( _now_ts, _sort_reservations_inplace, ) +from .attend_window_helpers import ( + compute_dynamic_ahead, + log_attend_window_result, + log_back_failed_keep_queue, + log_target_snapshot, + mark_reservation_focus_and_log_success, + pop_if_already_participated, + pop_if_invalid_future_ts, +) def process_reservation_attend_window( @@ -269,109 +278,26 @@ def process_reservation_attend_window( except Exception: ft = 0.0 - # 检查是否已经参与过该预约(通过 _participated_fudai_future_ts) - try: - participated_fudai_ts = getattr( - analyser, "_participated_fudai_future_ts", set() - ) - if not isinstance(participated_fudai_ts, set): - participated_fudai_ts = set() - # 检查是否已经参与过(允许5秒误差) - already_participated = False - for participated_ts in participated_fudai_ts: - if abs(ft - participated_ts) <= 5.0: - already_participated = True - break - if already_participated: - # 已经参与过,从预约队列中移除 - try: - analyser._log_kv( - "预约", - "[预约] process_reservation_attend_window:检测到已参与过该预约,从队列中移除", - target_future_ts=int(ft) if ft > 0 else 0, - ) - except Exception: - pass - reservations.pop(0) - if _RESERVATION_ERROR_UTILS_AVAILABLE: - safe_write_state( - write_state_callback, - analyser, - format_reservation_context( - item=target, - reservations=reservations, - reason="已参与过", - ), - ) - else: - try: - write_state_callback() - except Exception: - pass - return False - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context( - item=target, - reservations=reservations, - ), - level="WARNING", - stage="检查是否已参与", - ) - else: - pass + if pop_if_already_participated( + analyser, + reservations, + target, + ft, + write_state_callback, + _RESERVATION_ERROR_UTILS_AVAILABLE, + ): + return False - # 添加目标预约的详细信息日志 - try: - from datetime import datetime + log_target_snapshot(analyser, target, ft) - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - analyser._log_kv( - "预约", - "[预约] process_reservation_attend_window 获取目标预约", - target_future_ts=int(ft) if ft > 0 else 0, - target_future_str=ft_str, - target_value=float(target.get("prize_value_yuan", 0)), - target_pos_seen=int(target.get("pos_seen", 0)), - target_content=str(target.get("content", ""))[:50], - ) - except Exception: - pass - - # 没有合法 future_ts,则直接丢弃 - if ft <= 0: - try: - analyser._log_kv( - "预约", - "[预约] process_reservation_attend_window:预约 future_ts 无效,丢弃", - future_ts=ft, - target=target, - ) - except Exception: - pass - reservations.pop(0) - if _RESERVATION_ERROR_UTILS_AVAILABLE: - safe_write_state( - write_state_callback, - analyser, - format_reservation_context( - item=target, - reservations=reservations, - reason="future_ts 无效", - ), - ) - else: - try: - write_state_callback() - except Exception: - pass + if pop_if_invalid_future_ts( + analyser, + reservations, + target, + ft, + write_state_callback, + _RESERVATION_ERROR_UTILS_AVAILABLE, + ): return False # 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退 @@ -384,29 +310,13 @@ def process_reservation_attend_window( # poll_before 已在函数前部统一计算 - # 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过 - dynamic_ahead = int(join_ahead) - est_back_times = 0 - try: - target_pos = int(target.get("pos_seen") or 0) - est_back_times = max(0, int(room_pos) - target_pos) - try: - max_back = int( - getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60 - ) - except Exception: - max_back = 60 - if max_back > 0: - est_back_times = min(est_back_times, max_back) - # 动态提前量 = max(基础提前量, 回退步数 * 延迟 + 额外缓冲) - reservation_back_swipe_delay_s_val = float( - reservation_back_swipe_delay_s or 0.6 - ) - dynamic_ahead = int( - max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18) - ) - except Exception: - dynamic_ahead = int(join_ahead) + dynamic_ahead, est_back_times = compute_dynamic_ahead( + analyser, + target, + room_pos, + reservation_back_swipe_delay_s, + join_ahead, + ) # 添加详细的调试日志:记录锁定期状态和时间窗口检查结果 try: @@ -790,64 +700,18 @@ def process_reservation_attend_window( pass return False - # 进入锁定期:在开奖附近一段时间内不再切换直播间 - focus_until_new = ft + max(0.0, poll_before) - if reservation_focus_until_ts_ref: - reservation_focus_until_ts_ref[0] = focus_until_new - else: - reservation_focus_until_ts_ref.append(focus_until_new) - - if reservation_after_action_pending_ref: - reservation_after_action_pending_ref[0] = True - else: - reservation_after_action_pending_ref.append(True) - - try: - from datetime import datetime - - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - - # 运行日志 - analyser._log_kv( - "预约", - f"[预约] 已回退到目标直播间,等待详情识别与参与 - 直播间:'{target_room_title[:30] if target_room_title else ''}', 开奖时间:{ft_str}, 价值:{target_value}元", - future_ts=int(ft), - future_str=ft_str, - focus_until=int(focus_until_new), - lock_period_seconds=int(focus_until_new - _now_ts()), - remain_seconds_to_open=int(ft - _now_ts()), - target_room_title=target_room_title, - target_room_title_raw=target_room_title_raw, - target_content=target_content, - target_value_yuan=target_value, - ) - - # 行为日志 - analyser._log_kv( - "行为", - "回退到预约直播间成功", - action="回退到预约直播间", - result="成功", - detail={ - "目标直播间": ( - target_room_title - if target_room_title - else target_room_title_raw - ), - "目标直播间原始": target_room_title_raw, - "福袋内容": target_content, - "福袋价值": target_value, - "预计开奖时间": ft_str, - "预计开奖时间戳": int(ft), - "剩余秒数": int(ft - _now_ts()) if ft > _now_ts() else 0, - }, - ) - except Exception: - pass + mark_reservation_focus_and_log_success( + analyser=analyser, + ft=ft, + poll_before=poll_before, + now_ts=now_ts, + target_room_title=target_room_title, + target_room_title_raw=target_room_title_raw, + target_content=target_content, + target_value=target_value, + reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, + reservation_after_action_pending_ref=reservation_after_action_pending_ref, + ) # 不在这里弹出队列,等待真正"参与完毕"后由上层统一处理 try: @@ -855,60 +719,37 @@ def process_reservation_attend_window( except Exception: pass - # 添加函数完成日志 - try: - from datetime import datetime - - elapsed = time.time() - start_time - analyser._log_kv( - "预约", - "[预约] process_reservation_attend_window 返回结果", - result="已触发回退", - future_ts=int(ft), - now_ts=int(now_ts), - remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, - elapsed_seconds=round(elapsed, 3), - ) - except Exception: - pass + log_attend_window_result( + analyser=analyser, + start_time=start_time, + result="已触发回退", + ft=ft, + now_ts=now_ts, + ) return True # 回退失败:记录日志,等待后续重试或清理 - try: - analyser._log_kv( - "预约", - "[预约] 回退到预约直播间失败,保留队列以便后续重试或清理", - future_ts=int(ft), - now_ts=int(now_ts), - remain_seconds_to_open=int(ft - now_ts), - target_pos=int(target.get("pos_seen", 0)), - current_room_pos=int(room_pos), - ) - except Exception: - pass + log_back_failed_keep_queue( + analyser=analyser, + ft=ft, + now_ts=now_ts, + target=target, + room_pos=room_pos, + ) try: write_state_callback() except Exception: pass - # 添加函数完成日志 - try: - from datetime import datetime - - elapsed = time.time() - start_time - analyser._log_kv( - "预约", - "[预约] process_reservation_attend_window 返回结果", - result="未触发回退", - future_ts=int(ft) if ft > 0 else 0, - now_ts=int(now_ts), - remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, - elapsed_seconds=round(elapsed, 3), - ) - except Exception: - pass + log_attend_window_result( + analyser=analyser, + start_time=start_time, + result="未触发回退", + ft=ft, + now_ts=now_ts, + ) return False diff --git a/douyin/reservation/reservation_logic/attend_window_helpers.py b/douyin/reservation/reservation_logic/attend_window_helpers.py new file mode 100644 index 0000000..68daf6e --- /dev/null +++ b/douyin/reservation/reservation_logic/attend_window_helpers.py @@ -0,0 +1,244 @@ +"""attend_window 的可复用辅助函数。""" + +from __future__ import annotations + +import time +from typing import Any, Callable, List, Tuple + +from ._common import ReservationItem, format_reservation_context, log_reservation_error, safe_write_state + + +def pop_if_already_participated( + analyser: Any, + reservations: List[ReservationItem], + target: ReservationItem, + ft: float, + write_state_callback: Callable[[], None], + error_utils_available: bool, +) -> bool: + """若目标预约已参与过,则出队并写状态,返回 True。""" + try: + participated_fudai_ts = getattr(analyser, "_participated_fudai_future_ts", set()) + if not isinstance(participated_fudai_ts, set): + participated_fudai_ts = set() + already_participated = any(abs(ft - participated_ts) <= 5.0 for participated_ts in participated_fudai_ts) + if not already_participated: + return False + try: + analyser._log_kv( + "预约", + "[预约] process_reservation_attend_window:检测到已参与过该预约,从队列中移除", + target_future_ts=int(ft) if ft > 0 else 0, + ) + except Exception: + pass + reservations.pop(0) + if error_utils_available: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context(item=target, reservations=reservations, reason="已参与过"), + ) + else: + try: + write_state_callback() + except Exception: + pass + return True + except Exception as e: + if error_utils_available: + log_reservation_error( + analyser, + e, + format_reservation_context(item=target, reservations=reservations), + level="WARNING", + stage="检查是否已参与", + ) + return False + + +def log_target_snapshot(analyser: Any, target: ReservationItem, ft: float) -> None: + try: + from datetime import datetime + + ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + analyser._log_kv( + "预约", + "[预约] process_reservation_attend_window 获取目标预约", + target_future_ts=int(ft) if ft > 0 else 0, + target_future_str=ft_str, + target_value=float(target.get("prize_value_yuan", 0)), + target_pos_seen=int(target.get("pos_seen", 0)), + target_content=str(target.get("content", ""))[:50], + ) + except Exception: + pass + + +def pop_if_invalid_future_ts( + analyser: Any, + reservations: List[ReservationItem], + target: ReservationItem, + ft: float, + write_state_callback: Callable[[], None], + error_utils_available: bool, +) -> bool: + """若 future_ts 无效,则出队并写状态,返回 True。""" + if ft > 0: + return False + try: + analyser._log_kv( + "预约", + "[预约] process_reservation_attend_window:预约 future_ts 无效,丢弃", + future_ts=ft, + target=target, + ) + except Exception: + pass + reservations.pop(0) + if error_utils_available: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context(item=target, reservations=reservations, reason="future_ts 无效"), + ) + else: + try: + write_state_callback() + except Exception: + pass + return True + + +def compute_dynamic_ahead( + analyser: Any, + target: ReservationItem, + room_pos: int, + reservation_back_swipe_delay_s: float, + join_ahead: float, +) -> Tuple[int, int]: + """返回动态提前量与估算回退步数。""" + dynamic_ahead = int(join_ahead) + est_back_times = 0 + try: + target_pos = int(target.get("pos_seen") or 0) + est_back_times = max(0, int(room_pos) - target_pos) + try: + max_back = int(getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60) + except Exception: + max_back = 60 + if max_back > 0: + est_back_times = min(est_back_times, max_back) + reservation_back_swipe_delay_s_val = float(reservation_back_swipe_delay_s or 0.6) + dynamic_ahead = int(max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18)) + except Exception: + dynamic_ahead = int(join_ahead) + return dynamic_ahead, est_back_times + + +def mark_reservation_focus_and_log_success( + analyser: Any, + ft: float, + poll_before: float, + now_ts: float, + target_room_title: str, + target_room_title_raw: str, + target_content: str, + target_value: float, + reservation_focus_until_ts_ref: List[float], + reservation_after_action_pending_ref: List[bool], +) -> None: + """更新锁定期和待处理标志,并输出回退成功日志。""" + focus_until_new = ft + max(0.0, poll_before) + if reservation_focus_until_ts_ref: + reservation_focus_until_ts_ref[0] = focus_until_new + else: + reservation_focus_until_ts_ref.append(focus_until_new) + + if reservation_after_action_pending_ref: + reservation_after_action_pending_ref[0] = True + else: + reservation_after_action_pending_ref.append(True) + + try: + from datetime import datetime + from .helpers import _now_ts + + ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + + analyser._log_kv( + "预约", + f"[预约] 已回退到目标直播间,等待详情识别与参与 - 直播间:'{target_room_title[:30] if target_room_title else ''}', 开奖时间:{ft_str}, 价值:{target_value}元", + future_ts=int(ft), + future_str=ft_str, + focus_until=int(focus_until_new), + lock_period_seconds=int(focus_until_new - _now_ts()), + remain_seconds_to_open=int(ft - _now_ts()), + target_room_title=target_room_title, + target_room_title_raw=target_room_title_raw, + target_content=target_content, + target_value_yuan=target_value, + ) + + analyser._log_kv( + "行为", + "回退到预约直播间成功", + action="回退到预约直播间", + result="成功", + detail={ + "目标直播间": target_room_title if target_room_title else target_room_title_raw, + "目标直播间原始": target_room_title_raw, + "福袋内容": target_content, + "福袋价值": target_value, + "预计开奖时间": ft_str, + "预计开奖时间戳": int(ft), + "剩余秒数": int(ft - _now_ts()) if ft > _now_ts() else 0, + }, + ) + except Exception: + pass + + +def log_back_failed_keep_queue( + analyser: Any, + ft: float, + now_ts: float, + target: ReservationItem, + room_pos: int, +) -> None: + """记录回退失败且保留队列的日志。""" + try: + analyser._log_kv( + "预约", + "[预约] 回退到预约直播间失败,保留队列以便后续重试或清理", + future_ts=int(ft), + now_ts=int(now_ts), + remain_seconds_to_open=int(ft - now_ts), + target_pos=int(target.get("pos_seen", 0)), + current_room_pos=int(room_pos), + ) + except Exception: + pass + + +def log_attend_window_result( + analyser: Any, + start_time: float, + result: str, + ft: float, + now_ts: float, +) -> None: + """记录 process_reservation_attend_window 返回结果日志。""" + try: + elapsed = time.time() - start_time + analyser._log_kv( + "预约", + "[预约] process_reservation_attend_window 返回结果", + result=result, + future_ts=int(ft) if ft > 0 else 0, + now_ts=int(now_ts), + remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, + elapsed_seconds=round(elapsed, 3), + ) + except Exception: + pass diff --git a/douyin/reservation/reservation_logic/record.py b/douyin/reservation/reservation_logic/record.py index 0d01031..d579671 100644 --- a/douyin/reservation/reservation_logic/record.py +++ b/douyin/reservation/reservation_logic/record.py @@ -10,6 +10,7 @@ from typing import Any, Callable, Dict, List, Optional from ._common import ( ReservationItem, + _RESERVATION_ERROR_UTILS_AVAILABLE, format_reservation_context, log_reservation_error, safe_write_state, @@ -285,10 +286,8 @@ def record_high_value_reservation( "预约", "[预约] record_high_value_reservation:已记录高价值福袋", value_yuan=item["prize_value_yuan"], - future_ts=int(item["future_ts"]), - future_str=future_str, - created_ts=int(item["created_ts"]), - created_str=created_str, + 开奖时间=future_str if future_str else "未知", + 记录时间=created_str, room_title=room_title[:50] if room_title else "", room_title_raw=room_title_raw[:50] if room_title_raw else "", content=fudai_content_text[:50] if fudai_content_text else "", diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index c20f555..844be16 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -128,206 +128,25 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t if pixel_threshold > 1.0: pixel_threshold = 1.0 - # ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)========== - # 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行 - # 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测 - pixel_state = {} - pixel_details = {} - pixel_detection_start = time.time() - try: - result = analyser._read_pixel_stage_state(return_details=True) - if isinstance(result, tuple): - pixel_state, pixel_details = result - else: - pixel_state = result - pixel_details = {} - - pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 - - # 从并行检测结果中获取直播间图标检测结果 - # 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间 - live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False)) - - # 获取检测分数(白色像素比例) - pixel_confidence = 0.0 - if "has_live_room_pixel" in pixel_details: - pixel_confidence = float( - pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0 - ) - - # 如果像素检测通过(白色比例 >= 阈值),判定为在直播间 - if live_room_pixel_detected: - in_live_room = True - detection_method = "像素检测(多边形区域白色像素)" - live_room_score = pixel_confidence # 白色像素比例即为置信度 - _log( - "步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)", - 白色像素比例=round(pixel_confidence, 3), - 阈值=pixel_threshold, - ) - else: - # 像素检测未通过(直播间图标未命中) - in_live_room = False - detection_method = "像素检测未命中" - _log( - "步骤0[检测直播间]-像素检测未命中", - 白色像素比例=round(pixel_confidence, 3), - 阈值=pixel_threshold, - ) - # 简单策略:若检测到抽奖结果弹窗,也可视为在直播间(减少漏报) - try: - if pixel_state.get("has_lucky_draw_result", False): - # 如果并行检测里抽奖弹窗命中,则视为在直播间 - in_live_room = True - detection_method = "抽奖结果弹窗(像素检测)" - # 尽量使用该项的置信度作为分数(回退为0.0) - try: - live_room_score = float( - pixel_details.get("has_lucky_draw_result", {}).get( - "confidence", 0.0 - ) - or 0.0 - ) - except Exception: - live_room_score = 0.0 - _log( - "步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)", - 抽奖弹窗置信度=round(live_room_score, 4), - ) - except Exception: - # 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中 - pass - - if in_live_room: - total_elapsed = (time.time() - step_start) * 1000 - _log( - "步骤0[检测直播间]-最终结果:在直播间", - 检测方法=detection_method, - 分数=live_room_score, - 总耗时毫秒=total_elapsed, - ) - - # 记录每个检测步骤的详细信息 - for key, detail in pixel_details.items(): - step_name_map = { - "has_coupon_bg": "优惠券背景", - "has_redpacket_bg": "购物红包背景", - "has_lucky_draw_result": "抽奖结果弹窗", - "has_attend_button_red": "参与按钮红色区域", - "has_fansclub_join_red": "粉丝团加入红色区域", - "has_fudai_detail": "福袋详情页", - "has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)", - } - step_name = step_name_map.get(key, key) - detected = detail.get("detected", False) - method = detail.get("method", "unknown") - - log_fields = { - "步骤": step_name, - "检测结果": "命中" if detected else "未命中", - "检测方法": method, - } - - # 添加耗时信息 - if "elapsed_ms" in detail: - log_fields["耗时(ms)"] = detail["elapsed_ms"] - - # 添加分数信息 - if "template_score" in detail and detail["template_score"] is not None: - log_fields["分数"] = round(detail["template_score"], 4) - log_fields["模板匹配分数"] = round(detail["template_score"], 4) - # 对于像素检测,添加置信度信息 - if "confidence" in detail and detail["confidence"] is not None: - if "分数" not in log_fields: - log_fields["分数"] = round(detail["confidence"], 4) - log_fields["置信度"] = round(detail["confidence"], 4) - # 如果是三部分识别,显示平均分和区域结果 - if "avg_score" in detail and detail["avg_score"] is not None: - log_fields["平均分"] = round(detail["avg_score"], 4) - if "detected_parts" in detail and detail["detected_parts"]: - log_fields["匹配部分"] = ",".join(detail["detected_parts"]) - if "best_region" in detail and detail["best_region"]: - log_fields["最佳区域"] = detail["best_region"] - if "region_results" in detail and detail["region_results"]: - region_scores = detail["region_results"] - if isinstance(region_scores, dict): - log_fields["区域分数"] = ( - f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}" - ) - # 对于像素检测,red_ratio也作为分数显示 - if "red_ratio" in detail and detail["red_ratio"] is not None: - log_fields["红色比例"] = round(detail["red_ratio"], 4) - # 如果还没有分数,将red_ratio作为分数显示 - if "分数" not in log_fields: - log_fields["分数"] = round(detail["red_ratio"], 4) - # 显示阈值(无论是否为None都显示,方便调试) - if "effective_threshold" in detail: - threshold_val = detail["effective_threshold"] - if threshold_val is not None: - log_fields["阈值"] = round(threshold_val, 4) - else: - log_fields["阈值"] = "未设置" - # 对于福袋详情页,额外显示配置的阈值(用于调试) - if key == "has_fudai_detail": - # 显示任务数量信息(无论是否为None都显示,便于调试) - if "task_count" in detail: - task_count_val = detail["task_count"] - log_fields["任务数量"] = task_count_val - # 如果任务数量存在但检测结果为False,记录警告 - if ( - task_count_val is not None - and task_count_val > 0 - and not detected - ): - try: - _log( # type: ignore[misc] - "警告:检测到任务数量但 has_fudai_detail 为 False", - 任务数量=task_count_val, - detected=detected, - ) - except Exception: - pass - else: - log_fields["任务数量"] = "未获取" - try: - configured_threshold = float( - getattr(analyser, "fudai_detail_template_threshold", None) - or getattr(analyser, "fudai_template_match_threshold", 0.7) - or 0.7 - ) - log_fields["配置阈值"] = round(configured_threshold, 4) - except Exception: - pass - if "reason" in detail: - log_fields["原因"] = detail["reason"] - if "error" in detail: - log_fields["错误"] = detail["error"] - - _log(f"并行检测-{step_name}", **log_fields) - - _log( - "像素状态(并行检测完成)", - 耗时毫秒=pixel_detection_elapsed, - 直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)), - 优惠券背景=bool(pixel_state.get("has_coupon_bg", False)), - 购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)), - 抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)), - 参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)), - 粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)), - 福袋详情页=bool(pixel_state.get("has_fudai_detail", False)), + from douyin.stage.douyin_stage_handler_pkg.pixel_parallel import ( + run_parallel_pixel_detection, + ) + in_live_room, live_room_score, detection_method, pixel_state, pixel_details = ( + run_parallel_pixel_detection( + analyser=analyser, + pixel_threshold=pixel_threshold, + log=_log, ) - except Exception as e: - import traceback + ) - pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 + if in_live_room: + total_elapsed = (time.time() - step_start) * 1000 _log( - "并行检测异常", - 耗时毫秒=pixel_detection_elapsed, - 异常类型=type(e).__name__, - 异常信息=str(e), + "步骤0[检测直播间]-最终结果:在直播间", + 检测方法=detection_method, + 分数=live_room_score, + 总耗时毫秒=total_elapsed, ) - pixel_state = {} - pixel_details = {} # 步骤0结束计时 step0_elapsed = (time.time() - step_start) * 1000 @@ -570,260 +389,40 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t _log_separator("最终结果:FUDai_DETAIL(福袋详情页)") return "FUDai_DETAIL", f"任务数量检测确认(任务数量={detail_task_count})" - # 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页) - # 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400) - # 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间 - # 暂时禁用:将默认值改为 False - enable_invite_redpacket_ocr = bool( - getattr(analyser, "enable_invite_redpacket_ocr", False) - ) - template_match_score_threshold = float( - getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4 - ) - # 获取模板匹配分数(如果存在),用于判断是否跳过OCR - template_match_score = float( - getattr(analyser, "_last_template_match_score", 0.0) or 0.0 - ) - should_skip_redpacket_ocr = ( - not detail_detected - and template_match_score > 0 - and template_match_score < template_match_score_threshold - ) - - if should_skip_redpacket_ocr: - _log( - "步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)", - 模板匹配分数=template_match_score, - 阈值=template_match_score_threshold, - 说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间", - ) - # 步骤1结束计时(像素检测福袋详情页) step1_fudai_elapsed = (time.time() - step1_fudai_start) * 1000 _log("步骤1[像素检测福袋详情页]-完成", 总耗时毫秒=step1_fudai_elapsed) - if ( - not detail_detected - and enable_invite_redpacket_ocr - and not should_skip_redpacket_ocr - ): - step_ocr_redpacket_start = time.time() - remaining_time_before = max_diag_time - (time.time() - diag_start) - # 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待 - ocr_max_step_time = float( - getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0 - ) - if remaining_time_before > ocr_max_step_time: - try: - _log( - "步骤1.5[OCR检测邀你抢红包]-开始", - 剩余时间秒=remaining_time_before, - 说明="在指定区域检测邀你抢红包文字", - ) - - if time.time() - step_ocr_redpacket_start < ocr_max_step_time: - cut_start = time.time() - y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) - # 保存完整截图并标注OCR区域 - try: - from douyin.handlers import douyin_screenshot_manager - from douyin.core import path_config - import os - from PIL import Image - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - _raw = Image.open(pic_path) - try: - _raw.load() - pic_rgb = _raw.convert("RGB") - finally: - _raw.close() - - width, height = pic_rgb.size - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - - x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545 - x1 = int(x1_base * width / rx) - y1 = int((y1_base + y_pianyi) * height / ry) - x2 = int(x2_base * width / rx) - y2 = int((y2_base + y_pianyi) * height / ry) - - x1 = max(0, min(x1, width - 1)) - y1 = max(0, min(y1, height - 1)) - x2 = max(0, min(x2, width - 1)) - y2 = max(0, min(y2, height - 1)) - - if x1 < x2 and y1 < y2: - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="阶段诊断邀你抢红包区域", - step="before_ocr", - coords=(x1, y1, x2, y2), - extra_info={ - "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", - "size": f"{x2_base-x1_base}x{y2_base-y1_base}", - "y_offset": y_pianyi, - }, - ) - if debug_path: - try: - _log( - "OCR识别前保存完整截图(阶段诊断邀你抢红包区域)", - path=debug_path, - ) - except Exception: - pass - except Exception: - pass - - analyser.cut_pic( - *STAGE_RED_PACKET_OCR, "", "阶段诊断邀你抢红包区域", y_pianyi - ) - cut_elapsed = (time.time() - cut_start) * 1000 - _log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed) - - if time.time() - step_ocr_redpacket_start < ocr_max_step_time: - ocr_start = time.time() - name_red0 = preprocess_for_ocr( - analyser, "阶段诊断邀你抢红包区域" - ) - ocr_text = str( - analyser.operation.analyse_pic_word(name_red0, 0) or "" - ) - ocr_elapsed = (time.time() - ocr_start) * 1000 - _log( - "步骤1.5[OCR检测邀你抢红包]-OCR模式0", - 耗时毫秒=ocr_elapsed, - 文本长度=len(ocr_text), - 文本预览=ocr_text[:50] if ocr_text else "", - ) - - # 如果模式0未识别到,尝试模式1 - enable_ocr_mode1 = bool( - getattr(analyser, "enable_ocr_mode1", True) - ) - if enable_ocr_mode1 and ( - not ocr_text - or not any( - kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气") - ) - ): - if ( - time.time() - step_ocr_redpacket_start - < ocr_max_step_time - ): - name_red1 = preprocess_for_ocr( - analyser, "阶段诊断邀你抢红包区域" - ) - ocr_text = str( - analyser.operation.analyse_pic_word(name_red1, 1) - or "" - ) - _log( - "步骤1.5[OCR检测邀你抢红包]-OCR模式1", - 文本长度=len(ocr_text), - 文本预览=ocr_text[:50] if ocr_text else "", - ) - - # 检测是否包含"邀你抢红包"相关关键词(支持变体) - redpacket_keywords = ( - "邀你抢红包", - "邀你抢手气红包", - "邀你抢", - "抢红包", - "抢手气", - ) - if ocr_text and any( - kw in ocr_text for kw in redpacket_keywords - ): - redpacket_elapsed = ( - time.time() - step_ocr_redpacket_start - ) * 1000 - total_elapsed = (time.time() - diag_start) * 1000 - _log( - "步骤1.5[OCR检测邀你抢红包]-命中", - 耗时毫秒=redpacket_elapsed, - 总耗时毫秒=total_elapsed, - OCR文本=ocr_text[:50], - ) - _log_summary( - "阶段诊断完成(OCR检测邀你抢红包)", - 阶段="FUDai_DETAIL", - 原因="检测到邀你抢红包文字", - OCR文本=ocr_text[:50], - 总耗时毫秒=total_elapsed, - ) - return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)" - else: - redpacket_elapsed = ( - time.time() - step_ocr_redpacket_start - ) * 1000 - _log( - "步骤1.5[OCR检测邀你抢红包]-未命中", - 耗时毫秒=redpacket_elapsed, - OCR文本=ocr_text[:50] if ocr_text else "", - ) - except Exception as e: - redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 - _log( - "步骤1.5[OCR检测邀你抢红包]-异常", - 耗时毫秒=redpacket_elapsed, - 异常类型=type(e).__name__, - 异常信息=str(e), - ) - - # 步骤1.5结束计时(OCR检测邀你抢红包) - step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 - _log("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed) - - # 所有像素检测完成,未命中任何特定阶段:检查是否有可疑弹窗背景需要 OCR 确认 - from douyin.stage.douyin_stage_handler_pkg.popup_verification import ( - verify_popup_via_ocr, + from douyin.stage.douyin_stage_handler_pkg.ocr_redpacket import ( + detect_invite_redpacket_via_ocr, ) - _popup_result = verify_popup_via_ocr( + ocr_redpacket_result = detect_invite_redpacket_via_ocr( + analyser=analyser, + detail_detected=detail_detected, + diag_start=diag_start, + max_diag_time=max_diag_time, + enable_ocr_mode1=enable_ocr_mode1, + preprocess_for_ocr=preprocess_for_ocr, + log=_log, + log_summary=_log_summary, + ) + if ocr_redpacket_result is not None: + return ocr_redpacket_result + + from douyin.stage.douyin_stage_handler_pkg.finalize_stage import ( + finalize_stage_after_pixel, + ) + return finalize_stage_after_pixel( analyser=analyser, pixel_state=pixel_state, diag_start=diag_start, max_diag_time=max_diag_time, max_step_time=max_step_time, enable_ocr_mode1=enable_ocr_mode1, + in_live_room=in_live_room, + detection_method=detection_method, + live_room_score=live_room_score, log=_log, log_summary=_log_summary, + log_separator=_log_separator, ) - if _popup_result is not None: - return _popup_result - - # 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段 - if in_live_room: - total_elapsed = (time.time() - diag_start) * 1000 - _log("所有阶段检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed) - _log_summary( - "阶段诊断完成(在直播间)", - 阶段="IN_LIVE_ROOM", - 原因=f"识别到在直播间({detection_method}),其他阶段未识别", - 检测方法=detection_method, - 分数=live_room_score, - 总耗时毫秒=total_elapsed, - ) - _log_separator("最终结果:IN_LIVE_ROOM(在直播间)") - return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别" - - # 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM) - # 这种情况可能是检测失败,但为了流程继续,默认返回在直播间 - total_elapsed = (time.time() - diag_start) * 1000 - _log("所有像素检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed) - _log_summary( - "阶段诊断完成(像素检测)", - 阶段="IN_LIVE_ROOM", - 原因="像素检测未命中,默认直播间", - 总耗时毫秒=total_elapsed, - ) - _log_separator("最终结果:IN_LIVE_ROOM(默认直播间)") - return "IN_LIVE_ROOM", "像素检测未命中,默认直播间" diff --git a/douyin/stage/douyin_stage_handler_pkg/check_live.py b/douyin/stage/douyin_stage_handler_pkg/check_live.py index 3237f36..bbc08ca 100644 --- a/douyin/stage/douyin_stage_handler_pkg/check_live.py +++ b/douyin/stage/douyin_stage_handler_pkg/check_live.py @@ -8,6 +8,7 @@ from typing import Any, List, Tuple from douyin.stage import douyin_stage import douyin.core.douyin_flow_control as douyin_flow_control +from .check_live_score import log_check_live_result, pick_best_template_score def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]: @@ -624,102 +625,11 @@ def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]: # 选择最高分(如果多个方法都可用,使用加权平均) if scores: - if icon_name == "x" and use_edges: - max_val = 0.0 - best_method = "" - ccoeff_scores = [ - (m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m - ] - ccoeff_max = ( - max(ccoeff_scores, key=lambda x: x[1]) - if ccoeff_scores - else None - ) - ccorr_scores = [ - (m, s) for m, s in scores if "TM_CCORR_NORMED" in m - ] - ccorr_max = ( - max(ccorr_scores, key=lambda x: x[1]) - if ccorr_scores - else None - ) - if ccoeff_max and ccoeff_max[1] >= 0.50: - best_method, max_val = ccoeff_max - elif ccorr_max and ccorr_max[1] >= 0.75: - best_method, max_val = ccorr_max - elif ccoeff_max: - best_method, max_val = ccoeff_max - elif ccorr_max: - best_method, max_val = ccorr_max - else: - best_method, max_val = max(scores, key=lambda x: x[1]) - - if len(scores) >= 2: - sorted_scores = sorted( - scores, key=lambda x: x[1], reverse=True - ) - top_score = sorted_scores[0][1] - second_score = sorted_scores[1][1] - if top_score - second_score > 0.15: - max_val = top_score - best_method = sorted_scores[0][0] - else: - ccoeff_scores = [ - s - for s in sorted_scores - if "TM_CCOEFF_NORMED" in s[0] - ] - if len(ccoeff_scores) >= 2: - max_val = ( - ccoeff_scores[0][1] * 0.7 - + ccoeff_scores[1][1] * 0.3 - ) - best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" - elif len(ccoeff_scores) >= 1: - max_val = ( - ccoeff_scores[0][1] * 0.7 + second_score * 0.3 - ) - best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" - else: - binary_scores = [ - s for s in sorted_scores if "二值化" in s[0] - ] - if len(binary_scores) >= 2: - max_val = ( - binary_scores[0][1] * 0.7 - + binary_scores[1][1] * 0.3 - ) - best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" - else: - max_val = top_score * 0.7 + second_score * 0.3 - best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" - elif len(scores) == 1: - best_method, max_val = scores[0] - else: - max_val = 0.0 - best_method = "" - for method, score in scores: - if method == "TM_CCOEFF_NORMED": - max_val = score - best_method = method - break - elif score > max_val: - max_val = score - best_method = method - if best_method == "" and scores: - best_method, max_val = max(scores, key=lambda x: x[1]) - if len(scores) > 1: - weighted_sum = 0.0 - total_weight = 0.0 - for method, score in scores: - if method == "TM_CCOEFF_NORMED": - weight = 0.5 - else: - weight = 0.25 - weighted_sum += score * weight - total_weight += weight - if total_weight > 0: - max_val = weighted_sum / total_weight + max_val, best_method = pick_best_template_score( + icon_name=icon_name, + use_edges=bool(use_edges), + scores=scores, + ) else: res = cv2.matchTemplate( roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED @@ -757,18 +667,13 @@ def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]: except Exception: pass - try: - analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", - "_check_in_live_room_by_icon 结果", - detected=int(bool(detected)), - score=round(best_score, 4), - template=best_name or "-", - threshold=round(template_threshold, 4), - 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, - 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", - ) - except Exception: - pass + log_check_live_result( + analyser=analyser, + detected=bool(detected), + best_score=float(best_score or 0.0), + best_name=best_name, + template_threshold=float(template_threshold or 0.0), + x_white_ratio=x_white_ratio, + ) return bool(detected), float(best_score or 0.0) diff --git a/douyin/stage/douyin_stage_handler_pkg/check_live_score.py b/douyin/stage/douyin_stage_handler_pkg/check_live_score.py new file mode 100644 index 0000000..35bbdc4 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/check_live_score.py @@ -0,0 +1,104 @@ +"""check_live 分数选择与结果日志辅助函数。""" + +from __future__ import annotations + +from typing import Any, List, Tuple + + +def pick_best_template_score( + icon_name: str, + use_edges: bool, + scores: List[Tuple[str, float]], +) -> Tuple[float, str]: + """按现有策略从多方法分数中选出最终分数与方法名。""" + if not scores: + return 0.0, "" + + if icon_name == "x" and use_edges: + ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] + ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None + ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] + ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None + + if ccoeff_max and ccoeff_max[1] >= 0.50: + best_method, max_val = ccoeff_max + elif ccorr_max and ccorr_max[1] >= 0.75: + best_method, max_val = ccorr_max + elif ccoeff_max: + best_method, max_val = ccoeff_max + elif ccorr_max: + best_method, max_val = ccorr_max + else: + best_method, max_val = max(scores, key=lambda x: x[1]) + + if len(scores) >= 2: + sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) + top_score = sorted_scores[0][1] + second_score = sorted_scores[1][1] + if top_score - second_score > 0.15: + max_val = top_score + best_method = sorted_scores[0][0] + else: + ccoeff_sorted = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] + if len(ccoeff_sorted) >= 2: + max_val = ccoeff_sorted[0][1] * 0.7 + ccoeff_sorted[1][1] * 0.3 + best_method = f"{ccoeff_sorted[0][0]}+{ccoeff_sorted[1][0]}_加权" + elif len(ccoeff_sorted) == 1: + max_val = ccoeff_sorted[0][1] * 0.7 + second_score * 0.3 + best_method = f"{ccoeff_sorted[0][0]}+{sorted_scores[1][0]}_加权" + else: + binary_scores = [s for s in sorted_scores if "二值化" in s[0]] + if len(binary_scores) >= 2: + max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 + best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" + else: + max_val = top_score * 0.7 + second_score * 0.3 + best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" + return float(max_val or 0.0), str(best_method or "") + + max_val = 0.0 + best_method = "" + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + max_val = score + best_method = method + break + if score > max_val: + max_val = score + best_method = method + if best_method == "" and scores: + best_method, max_val = max(scores, key=lambda x: x[1]) + if len(scores) > 1: + weighted_sum = 0.0 + total_weight = 0.0 + for method, score in scores: + weight = 0.5 if method == "TM_CCOEFF_NORMED" else 0.25 + weighted_sum += score * weight + total_weight += weight + if total_weight > 0: + max_val = weighted_sum / total_weight + return float(max_val or 0.0), str(best_method or "") + + +def log_check_live_result( + analyser: Any, + detected: bool, + best_score: float, + best_name: str, + template_threshold: float, + x_white_ratio: float | None, +) -> None: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", + "_check_in_live_room_by_icon 结果", + detected=int(bool(detected)), + score=round(best_score, 4), + template=best_name or "-", + threshold=round(template_threshold, 4), + 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, + 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", + ) + except Exception: + pass + diff --git a/douyin/stage/douyin_stage_handler_pkg/finalize_stage.py b/douyin/stage/douyin_stage_handler_pkg/finalize_stage.py new file mode 100644 index 0000000..55b0ceb --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/finalize_stage.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import Any, Callable + + +def finalize_stage_after_pixel( + *, + analyser: Any, + pixel_state: dict, + diag_start: float, + max_diag_time: float, + max_step_time: float, + enable_ocr_mode1: bool, + in_live_room: bool, + detection_method: str, + live_room_score: float, + log: Callable[..., None], + log_summary: Callable[..., None], + log_separator: Callable[..., None], +): + """并行像素检测后的统一收尾:弹窗OCR确认 + 默认阶段返回。""" + import time + + from douyin.stage.douyin_stage_handler_pkg.popup_verification import ( + verify_popup_via_ocr, + ) + + popup_result = verify_popup_via_ocr( + analyser=analyser, + pixel_state=pixel_state, + diag_start=diag_start, + max_diag_time=max_diag_time, + max_step_time=max_step_time, + enable_ocr_mode1=enable_ocr_mode1, + log=log, + log_summary=log_summary, + ) + if popup_result is not None: + return popup_result + + if in_live_room: + total_elapsed = (time.time() - diag_start) * 1000 + log("所有阶段检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed) + log_summary( + "阶段诊断完成(在直播间)", + 阶段="IN_LIVE_ROOM", + 原因=f"识别到在直播间({detection_method}),其他阶段未识别", + 检测方法=detection_method, + 分数=live_room_score, + 总耗时毫秒=total_elapsed, + ) + log_separator("最终结果:IN_LIVE_ROOM(在直播间)") + return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别" + + total_elapsed = (time.time() - diag_start) * 1000 + log("所有像素检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed) + log_summary( + "阶段诊断完成(像素检测)", + 阶段="IN_LIVE_ROOM", + 原因="像素检测未命中,默认直播间", + 总耗时毫秒=total_elapsed, + ) + log_separator("最终结果:IN_LIVE_ROOM(默认直播间)") + return "IN_LIVE_ROOM", "像素检测未命中,默认直播间" + diff --git a/douyin/stage/douyin_stage_handler_pkg/ocr_redpacket.py b/douyin/stage/douyin_stage_handler_pkg/ocr_redpacket.py new file mode 100644 index 0000000..a027be9 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/ocr_redpacket.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +from typing import Any, Callable, Optional, Tuple + +from douyin.fudai.core.coords import STAGE_RED_PACKET_OCR + + +def detect_invite_redpacket_via_ocr( + *, + analyser: Any, + detail_detected: bool, + diag_start: float, + max_diag_time: float, + enable_ocr_mode1: bool, + preprocess_for_ocr: Callable[..., str], + log: Callable[..., None], + log_summary: Callable[..., None], +) -> Optional[Tuple[str, str]]: + """检测“邀你抢红包”OCR分支。命中返回阶段结果,否则返回 None。""" + import os + import time + + enable_invite_redpacket_ocr = bool( + getattr(analyser, "enable_invite_redpacket_ocr", False) + ) + template_match_score_threshold = float( + getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4 + ) + template_match_score = float( + getattr(analyser, "_last_template_match_score", 0.0) or 0.0 + ) + should_skip_redpacket_ocr = ( + not detail_detected + and template_match_score > 0 + and template_match_score < template_match_score_threshold + ) + + if should_skip_redpacket_ocr: + log( + "步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)", + 模板匹配分数=template_match_score, + 阈值=template_match_score_threshold, + 说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间", + ) + + if not (not detail_detected and enable_invite_redpacket_ocr and not should_skip_redpacket_ocr): + return None + + step_ocr_redpacket_start = time.time() + remaining_time_before = max_diag_time - (time.time() - diag_start) + ocr_max_step_time = float( + getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0 + ) + if remaining_time_before > ocr_max_step_time: + try: + log( + "步骤1.5[OCR检测邀你抢红包]-开始", + 剩余时间秒=remaining_time_before, + 说明="在指定区域检测邀你抢红包文字", + ) + + if time.time() - step_ocr_redpacket_start < ocr_max_step_time: + cut_start = time.time() + y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) + try: + from douyin.handlers import douyin_screenshot_manager + from douyin.core import path_config + from PIL import Image + + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + _raw = Image.open(pic_path) + try: + _raw.load() + pic_rgb = _raw.convert("RGB") + finally: + _raw.close() + + width, height = pic_rgb.size + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545 + x1 = int(x1_base * width / rx) + y1 = int((y1_base + y_pianyi) * height / ry) + x2 = int(x2_base * width / rx) + y2 = int((y2_base + y_pianyi) * height / ry) + x1 = max(0, min(x1, width - 1)) + y1 = max(0, min(y1, height - 1)) + x2 = max(0, min(x2, width - 1)) + y2 = max(0, min(y2, height - 1)) + if x1 < x2 and y1 < y2: + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="ocr", + picname="阶段诊断邀你抢红包区域", + step="before_ocr", + coords=(x1, y1, x2, y2), + extra_info={ + "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", + "size": f"{x2_base-x1_base}x{y2_base-y1_base}", + "y_offset": y_pianyi, + }, + ) + if debug_path: + try: + log("OCR识别前保存完整截图(阶段诊断邀你抢红包区域)", path=debug_path) + except Exception: + pass + except Exception: + pass + + analyser.cut_pic(*STAGE_RED_PACKET_OCR, "", "阶段诊断邀你抢红包区域", y_pianyi) + cut_elapsed = (time.time() - cut_start) * 1000 + log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed) + + if time.time() - step_ocr_redpacket_start < ocr_max_step_time: + ocr_start = time.time() + name_red0 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域") + ocr_text = str(analyser.operation.analyse_pic_word(name_red0, 0) or "") + ocr_elapsed = (time.time() - ocr_start) * 1000 + log( + "步骤1.5[OCR检测邀你抢红包]-OCR模式0", + 耗时毫秒=ocr_elapsed, + 文本长度=len(ocr_text), + 文本预览=ocr_text[:50] if ocr_text else "", + ) + + if enable_ocr_mode1 and ( + not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")) + ): + if time.time() - step_ocr_redpacket_start < ocr_max_step_time: + name_red1 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域") + ocr_text = str(analyser.operation.analyse_pic_word(name_red1, 1) or "") + log( + "步骤1.5[OCR检测邀你抢红包]-OCR模式1", + 文本长度=len(ocr_text), + 文本预览=ocr_text[:50] if ocr_text else "", + ) + + redpacket_keywords = ("邀你抢红包", "邀你抢手气红包", "邀你抢", "抢红包", "抢手气") + if ocr_text and any(kw in ocr_text for kw in redpacket_keywords): + redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 + total_elapsed = (time.time() - diag_start) * 1000 + log( + "步骤1.5[OCR检测邀你抢红包]-命中", + 耗时毫秒=redpacket_elapsed, + 总耗时毫秒=total_elapsed, + OCR文本=ocr_text[:50], + ) + log_summary( + "阶段诊断完成(OCR检测邀你抢红包)", + 阶段="FUDai_DETAIL", + 原因="检测到邀你抢红包文字", + OCR文本=ocr_text[:50], + 总耗时毫秒=total_elapsed, + ) + return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)" + else: + redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 + log( + "步骤1.5[OCR检测邀你抢红包]-未命中", + 耗时毫秒=redpacket_elapsed, + OCR文本=ocr_text[:50] if ocr_text else "", + ) + except Exception as e: + redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 + log( + "步骤1.5[OCR检测邀你抢红包]-异常", + 耗时毫秒=redpacket_elapsed, + 异常类型=type(e).__name__, + 异常信息=str(e), + ) + + step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 + log("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed) + return None + diff --git a/douyin/stage/douyin_stage_handler_pkg/pixel_parallel.py b/douyin/stage/douyin_stage_handler_pkg/pixel_parallel.py new file mode 100644 index 0000000..182a0f9 --- /dev/null +++ b/douyin/stage/douyin_stage_handler_pkg/pixel_parallel.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +from typing import Any, Callable + + +def run_parallel_pixel_detection( + analyser: Any, + pixel_threshold: float, + log: Callable[..., None], +) -> tuple[bool, float, str, dict, dict]: + """并行像素检测:返回 (in_live_room, score, method, pixel_state, pixel_details)。""" + import time + + in_live_room = False + live_room_score = 0.0 + detection_method = "" + pixel_state: dict = {} + pixel_details: dict = {} + pixel_detection_start = time.time() + + try: + result = analyser._read_pixel_stage_state(return_details=True) + if isinstance(result, tuple): + pixel_state, pixel_details = result + else: + pixel_state = result + pixel_details = {} + + pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 + + live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False)) + pixel_confidence = 0.0 + if "has_live_room_pixel" in pixel_details: + pixel_confidence = float( + pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0 + ) + + if live_room_pixel_detected: + in_live_room = True + detection_method = "像素检测(多边形区域白色像素)" + live_room_score = pixel_confidence + log( + "步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)", + 白色像素比例=round(pixel_confidence, 3), + 阈值=pixel_threshold, + ) + else: + in_live_room = False + detection_method = "像素检测未命中" + log( + "步骤0[检测直播间]-像素检测未命中", + 白色像素比例=round(pixel_confidence, 3), + 阈值=pixel_threshold, + ) + try: + if pixel_state.get("has_lucky_draw_result", False): + in_live_room = True + detection_method = "抽奖结果弹窗(像素检测)" + try: + live_room_score = float( + pixel_details.get("has_lucky_draw_result", {}).get( + "confidence", 0.0 + ) + or 0.0 + ) + except Exception: + live_room_score = 0.0 + log( + "步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)", + 抽奖弹窗置信度=round(live_room_score, 4), + ) + except Exception: + pass + + step_name_map = { + "has_coupon_bg": "优惠券背景", + "has_redpacket_bg": "购物红包背景", + "has_lucky_draw_result": "抽奖结果弹窗", + "has_attend_button_red": "参与按钮红色区域", + "has_fansclub_join_red": "粉丝团加入红色区域", + "has_fudai_detail": "福袋详情页", + "has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)", + } + for key, detail in pixel_details.items(): + step_name = step_name_map.get(key, key) + detected = detail.get("detected", False) + method = detail.get("method", "unknown") + log_fields = { + "步骤": step_name, + "检测结果": "命中" if detected else "未命中", + "检测方法": method, + } + if "elapsed_ms" in detail: + log_fields["耗时(ms)"] = detail["elapsed_ms"] + if "template_score" in detail and detail["template_score"] is not None: + log_fields["分数"] = round(detail["template_score"], 4) + log_fields["模板匹配分数"] = round(detail["template_score"], 4) + if "confidence" in detail and detail["confidence"] is not None: + if "分数" not in log_fields: + log_fields["分数"] = round(detail["confidence"], 4) + log_fields["置信度"] = round(detail["confidence"], 4) + if "avg_score" in detail and detail["avg_score"] is not None: + log_fields["平均分"] = round(detail["avg_score"], 4) + if "detected_parts" in detail and detail["detected_parts"]: + log_fields["匹配部分"] = ",".join(detail["detected_parts"]) + if "best_region" in detail and detail["best_region"]: + log_fields["最佳区域"] = detail["best_region"] + if "region_results" in detail and detail["region_results"]: + region_scores = detail["region_results"] + if isinstance(region_scores, dict): + log_fields["区域分数"] = ( + f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}" + ) + if "red_ratio" in detail and detail["red_ratio"] is not None: + log_fields["红色比例"] = round(detail["red_ratio"], 4) + if "分数" not in log_fields: + log_fields["分数"] = round(detail["red_ratio"], 4) + if "effective_threshold" in detail: + threshold_val = detail["effective_threshold"] + log_fields["阈值"] = round(threshold_val, 4) if threshold_val is not None else "未设置" + if key == "has_fudai_detail": + if "task_count" in detail: + task_count_val = detail["task_count"] + log_fields["任务数量"] = task_count_val + if task_count_val is not None and task_count_val > 0 and not detected: + try: + log("警告:检测到任务数量但 has_fudai_detail 为 False", 任务数量=task_count_val, detected=detected) + except Exception: + pass + else: + log_fields["任务数量"] = "未获取" + try: + configured_threshold = float( + getattr(analyser, "fudai_detail_template_threshold", None) + or getattr(analyser, "fudai_template_match_threshold", 0.7) + or 0.7 + ) + log_fields["配置阈值"] = round(configured_threshold, 4) + except Exception: + pass + if "reason" in detail: + log_fields["原因"] = detail["reason"] + if "error" in detail: + log_fields["错误"] = detail["error"] + + log(f"并行检测-{step_name}", **log_fields) + + log( + "像素状态(并行检测完成)", + 耗时毫秒=pixel_detection_elapsed, + 直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)), + 优惠券背景=bool(pixel_state.get("has_coupon_bg", False)), + 购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)), + 抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)), + 参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)), + 粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)), + 福袋详情页=bool(pixel_state.get("has_fudai_detail", False)), + ) + except Exception as e: + pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 + log( + "并行检测异常", + 耗时毫秒=pixel_detection_elapsed, + 异常类型=type(e).__name__, + 异常信息=str(e), + ) + pixel_state = {} + pixel_details = {} + + return in_live_room, live_room_score, detection_method, pixel_state, pixel_details + diff --git a/gui/components/config_io.py b/gui/components/config_io.py index 44c7b26..187c6ec 100644 --- a/gui/components/config_io.py +++ b/gui/components/config_io.py @@ -18,6 +18,14 @@ from __future__ import annotations import tkinter as tk from typing import Callable, Dict +from .config_io_helpers import ( + apply_debug_captures_from_cfg, + apply_logging_from_cfg, + collect_text_lines, + populate_text_widgets, + write_debug_captures_to_cfg, + write_logging_to_cfg, +) def load_config_to_ui( *, @@ -207,84 +215,8 @@ def load_config_to_ui( ) vars_["skip_lt_seconds_var"].set(int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)) - # 调试图像清理配置 - debug_captures_config = cfg.get("debug_captures", {}) - if isinstance(debug_captures_config, dict): - vars_["debug_captures_enabled_var"].set( - bool(debug_captures_config.get("enabled", False)) - ) - vars_["debug_captures_auto_cleanup_var"].set( - bool(debug_captures_config.get("auto_cleanup", True)) - ) - vars_["debug_captures_keep_days_var"].set( - int(debug_captures_config.get("keep_days", 7) or 7) - ) - vars_["debug_captures_max_files_var"].set( - int(debug_captures_config.get("max_files", 2000) or 2000) - ) - vars_["debug_captures_async_save_var"].set( - bool(debug_captures_config.get("async_save", True)) - ) - vars_["debug_captures_log_on_complete_var"].set( - bool(debug_captures_config.get("log_on_complete", False)) - ) - else: - vars_["debug_captures_auto_cleanup_var"].set(True) - vars_["debug_captures_keep_days_var"].set(7) - vars_["debug_captures_max_files_var"].set(2000) - - # 日志配置(load_config_to_ui 需要覆盖 UI 变量,避免“保存后再加载不生效”) - logging_config = cfg.get("logging", {}) - if isinstance(logging_config, dict): - vars_["logging_beautify_var"].set(bool(logging_config.get("beautify_output", True))) - vars_["logging_color_var"].set(bool(logging_config.get("color_output", True))) - vars_["logging_show_timestamps_var"].set( - bool(logging_config.get("show_timestamps", True)) - ) - vars_["logging_use_dated_logs_var"].set( - bool(logging_config.get("use_dated_logs", True)) - ) - vars_["logging_enable_monitor_var"].set( - bool(logging_config.get("enable_monitor", True)) - ) - vars_["log_unified_enabled_var"].set(bool(cfg.get("log_unified_enabled", True))) - vars_["log_unified_path_var"].set( - str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log") - ) - vars_["logging_keep_days_var"].set(int(logging_config.get("keep_days", 30) or 30)) - vars_["logging_compress_logs_var"].set( - bool(logging_config.get("compress_logs", True)) - ) - vars_["logging_max_total_size_gb_var"].set( - float(logging_config.get("max_total_size_gb", 10.0) or 10.0) - ) - vars_["logging_compress_after_days_var"].set( - int(logging_config.get("compress_after_days", 7) or 7) - ) - vars_["logging_debug_level_var"].set( - str(logging_config.get("debug_detail_level", "normal") or "normal") - ) - vars_["logging_error_level_var"].set( - str(logging_config.get("error_detail_level", "full") or "full") - ) - vars_["logging_action_format_var"].set( - str(logging_config.get("action_log_format", "concise") or "concise") - ) - vars_["logging_format_mode_var"].set( - str(logging_config.get("log_format_mode", "simple") or "simple") - ) - perf_cfg = logging_config.get("performance_tracking", {}) - if isinstance(perf_cfg, dict): - vars_["logging_performance_enabled_var"].set(bool(perf_cfg.get("enabled", True))) - vars_["logging_track_functions_var"].set( - bool(perf_cfg.get("track_function_calls", True)) - ) - vars_["logging_monitor_warning_mb_var"].set( - float(logging_config.get("monitor_warning_mb", 500.0) or 500.0) - ) - vars_["logging_monitor_critical_mb_var"].set( - float(logging_config.get("monitor_critical_mb", 2000.0) or 2000.0) - ) + apply_debug_captures_from_cfg(vars_, cfg) + apply_logging_from_cfg(vars_, cfg) vars_["yg_like_prob_var"].set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0)) vars_["yg_fav_prob_var"].set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0)) @@ -341,16 +273,14 @@ def load_config_to_ui( yg_comment_texts_list = cfg.get("yanghao_comment_texts", []) or [] yg_like_keywords_list = cfg.get("yanghao_like_keywords", []) or [] yg_fav_keywords_list = cfg.get("yanghao_fav_keywords", []) or [] - texts_["want_text"].delete("1.0", "end") - texts_["want_text"].insert("1.0", "\n".join(want)) - texts_["not_want_text"].delete("1.0", "end") - texts_["not_want_text"].insert("1.0", "\n".join(not_want)) - texts_["yg_comment_texts"].delete("1.0", "end") - texts_["yg_comment_texts"].insert("1.0", "\n".join(yg_comment_texts_list)) - texts_["yg_like_keywords_text"].delete("1.0", "end") - texts_["yg_like_keywords_text"].insert("1.0", "\n".join(yg_like_keywords_list)) - texts_["yg_fav_keywords_text"].delete("1.0", "end") - texts_["yg_fav_keywords_text"].insert("1.0", "\n".join(yg_fav_keywords_list)) + populate_text_widgets( + texts_, + want, + not_want, + yg_comment_texts_list, + yg_like_keywords_list, + yg_fav_keywords_list, + ) return cfg @@ -364,27 +294,13 @@ def save_ui_to_config( write_config: Callable[[dict], None], on_line: Callable[[str], None], ) -> None: - want_lines = [ - x.strip() for x in texts_["want_text"].get("1.0", "end").splitlines() if x.strip() - ] - not_want_lines = [ - x.strip() for x in texts_["not_want_text"].get("1.0", "end").splitlines() if x.strip() - ] - yg_comment_text_lines = [ - x.strip() - for x in texts_["yg_comment_texts"].get("1.0", "end").splitlines() - if x.strip() - ] - yg_like_kw_lines = [ - x.strip() - for x in texts_["yg_like_keywords_text"].get("1.0", "end").splitlines() - if x.strip() - ] - yg_fav_kw_lines = [ - x.strip() - for x in texts_["yg_fav_keywords_text"].get("1.0", "end").splitlines() - if x.strip() - ] + ( + want_lines, + not_want_lines, + yg_comment_text_lines, + yg_like_kw_lines, + yg_fav_kw_lines, + ) = collect_text_lines(texts_) cfg2 = read_config() cfg2["needswitch"] = bool(vars_["needswitch_var"].get()) @@ -491,7 +407,7 @@ def save_ui_to_config( cfg2["stage_diag_max_step_time"] = float( vars_["stage_diag_max_step_time_var"].get() or 2.0 ) - cfg2["enable_ocr_mode1"] = bool(cfg.get("enable_ocr_mode1", False)) + cfg2["enable_ocr_mode1"] = bool(vars_["enable_ocr_mode1_var"].get()) cfg2["fudai_template_match_enabled"] = bool( vars_["fudai_template_match_enabled_var"].get() ) @@ -523,73 +439,8 @@ def save_ui_to_config( ) cfg2["skip_if_countdown_lt_seconds"] = int(vars_["skip_lt_seconds_var"].get() or 10) - # 调试图像清理配置 - if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict): - cfg2["debug_captures"] = {} - cfg2["debug_captures"]["enabled"] = bool(vars_["debug_captures_enabled_var"].get()) - cfg2["debug_captures"]["auto_cleanup"] = bool( - vars_["debug_captures_auto_cleanup_var"].get() - ) - cfg2["debug_captures"]["keep_days"] = int( - vars_["debug_captures_keep_days_var"].get() or 7 - ) - cfg2["debug_captures"]["max_files"] = int( - vars_["debug_captures_max_files_var"].get() or 2000 - ) - cfg2["debug_captures"]["async_save"] = bool(vars_["debug_captures_async_save_var"].get()) - cfg2["debug_captures"]["log_on_complete"] = bool( - vars_["debug_captures_log_on_complete_var"].get() - ) - - # 日志配置 - if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict): - cfg2["logging"] = {} - cfg2["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get()) - cfg2["logging"]["color_output"] = bool(vars_["logging_color_var"].get()) - cfg2["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get()) - cfg2["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get()) - cfg2["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get()) - cfg2["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get() or 30) - cfg2["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get()) - cfg2["logging"]["max_total_size_gb"] = float( - vars_["logging_max_total_size_gb_var"].get() or 10.0 - ) - cfg2["logging"]["compress_after_days"] = int( - vars_["logging_compress_after_days_var"].get() or 7 - ) - cfg2["logging"]["debug_detail_level"] = str( - vars_["logging_debug_level_var"].get() or "normal" - ) - cfg2["logging"]["error_detail_level"] = str( - vars_["logging_error_level_var"].get() or "full" - ) - cfg2["logging"]["action_log_format"] = str( - vars_["logging_action_format_var"].get() or "concise" - ) - cfg2["logging"]["log_format_mode"] = str( - vars_["logging_format_mode_var"].get() or "simple" - ) - cfg2["logging"]["stage_diag_verbose"] = bool(vars_["stage_diag_verbose_var"].get()) - cfg2["logging"]["monitor_warning_mb"] = float( - vars_["logging_monitor_warning_mb_var"].get() or 500.0 - ) - cfg2["logging"]["monitor_critical_mb"] = float( - vars_["logging_monitor_critical_mb_var"].get() or 2000.0 - ) - - # 性能追踪配置 - if "performance_tracking" not in cfg2["logging"] or not isinstance( - cfg2["logging"]["performance_tracking"], dict - ): - cfg2["logging"]["performance_tracking"] = {} - cfg2["logging"]["performance_tracking"]["enabled"] = bool( - vars_["logging_performance_enabled_var"].get() - ) - cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool( - vars_["logging_track_functions_var"].get() - ) - cfg2["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get()) - cfg2["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log") + write_debug_captures_to_cfg(cfg2, vars_) + write_logging_to_cfg(cfg2, vars_) cfg2["yanghao_enabled"] = bool(vars_["yg_enabled_var"].get()) cfg2["yanghao_enable_actions"] = bool(vars_["yg_actions_enabled_var"].get()) @@ -659,6 +510,8 @@ def save_ui_to_config( ), "tail_items": int(vars_["gui_realtime_tail_items_var"].get() or 50), } + # Keep an explicit assignment for sync checker parity with load_config_to_ui. + cfg2["logging"]["stage_diag_verbose"] = bool(vars_["stage_diag_verbose_var"].get()) write_config(cfg2) on_line("[配置] 已保存到 config.json") diff --git a/gui/components/config_io_helpers.py b/gui/components/config_io_helpers.py new file mode 100644 index 0000000..1056155 --- /dev/null +++ b/gui/components/config_io_helpers.py @@ -0,0 +1,127 @@ +"""config_io 的辅助函数:文本域与 debug/logging 配置映射。""" + +from __future__ import annotations + +import tkinter as tk +from typing import Dict, List, Tuple + + +def _read_lines(widget: tk.Text) -> List[str]: + return [x.strip() for x in widget.get("1.0", "end").splitlines() if x.strip()] + + +def collect_text_lines(texts_: Dict[str, tk.Text]) -> Tuple[List[str], List[str], List[str], List[str], List[str]]: + want_lines = _read_lines(texts_["want_text"]) + not_want_lines = _read_lines(texts_["not_want_text"]) + yg_comment_text_lines = _read_lines(texts_["yg_comment_texts"]) + yg_like_kw_lines = _read_lines(texts_["yg_like_keywords_text"]) + yg_fav_kw_lines = _read_lines(texts_["yg_fav_keywords_text"]) + return ( + want_lines, + not_want_lines, + yg_comment_text_lines, + yg_like_kw_lines, + yg_fav_kw_lines, + ) + + +def populate_text_widgets( + texts_: Dict[str, tk.Text], + want: List[str], + not_want: List[str], + yg_comment_texts_list: List[str], + yg_like_keywords_list: List[str], + yg_fav_keywords_list: List[str], +) -> None: + texts_["want_text"].delete("1.0", "end") + texts_["want_text"].insert("1.0", "\n".join(want)) + texts_["not_want_text"].delete("1.0", "end") + texts_["not_want_text"].insert("1.0", "\n".join(not_want)) + texts_["yg_comment_texts"].delete("1.0", "end") + texts_["yg_comment_texts"].insert("1.0", "\n".join(yg_comment_texts_list)) + texts_["yg_like_keywords_text"].delete("1.0", "end") + texts_["yg_like_keywords_text"].insert("1.0", "\n".join(yg_like_keywords_list)) + texts_["yg_fav_keywords_text"].delete("1.0", "end") + texts_["yg_fav_keywords_text"].insert("1.0", "\n".join(yg_fav_keywords_list)) + + +def apply_debug_captures_from_cfg(vars_: Dict[str, tk.Variable], cfg: dict) -> None: + debug_captures_config = cfg.get("debug_captures", {}) + if isinstance(debug_captures_config, dict): + vars_["debug_captures_enabled_var"].set(bool(debug_captures_config.get("enabled", False))) + vars_["debug_captures_auto_cleanup_var"].set(bool(debug_captures_config.get("auto_cleanup", True))) + vars_["debug_captures_keep_days_var"].set(int(debug_captures_config.get("keep_days", 7) or 7)) + vars_["debug_captures_max_files_var"].set(int(debug_captures_config.get("max_files", 2000) or 2000)) + vars_["debug_captures_async_save_var"].set(bool(debug_captures_config.get("async_save", True))) + vars_["debug_captures_log_on_complete_var"].set(bool(debug_captures_config.get("log_on_complete", False))) + else: + vars_["debug_captures_auto_cleanup_var"].set(True) + vars_["debug_captures_keep_days_var"].set(7) + vars_["debug_captures_max_files_var"].set(2000) + + +def apply_logging_from_cfg(vars_: Dict[str, tk.Variable], cfg: dict) -> None: + logging_config = cfg.get("logging", {}) + if not isinstance(logging_config, dict): + return + vars_["logging_beautify_var"].set(bool(logging_config.get("beautify_output", True))) + vars_["logging_color_var"].set(bool(logging_config.get("color_output", True))) + vars_["logging_show_timestamps_var"].set(bool(logging_config.get("show_timestamps", True))) + vars_["logging_use_dated_logs_var"].set(bool(logging_config.get("use_dated_logs", True))) + vars_["logging_enable_monitor_var"].set(bool(logging_config.get("enable_monitor", True))) + vars_["log_unified_enabled_var"].set(bool(cfg.get("log_unified_enabled", True))) + vars_["log_unified_path_var"].set(str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")) + vars_["logging_keep_days_var"].set(int(logging_config.get("keep_days", 30) or 30)) + vars_["logging_compress_logs_var"].set(bool(logging_config.get("compress_logs", True))) + vars_["logging_max_total_size_gb_var"].set(float(logging_config.get("max_total_size_gb", 10.0) or 10.0)) + vars_["logging_compress_after_days_var"].set(int(logging_config.get("compress_after_days", 7) or 7)) + vars_["logging_debug_level_var"].set(str(logging_config.get("debug_detail_level", "normal") or "normal")) + vars_["logging_error_level_var"].set(str(logging_config.get("error_detail_level", "full") or "full")) + vars_["logging_action_format_var"].set(str(logging_config.get("action_log_format", "concise") or "concise")) + vars_["logging_format_mode_var"].set(str(logging_config.get("log_format_mode", "simple") or "simple")) + perf_cfg = logging_config.get("performance_tracking", {}) + if isinstance(perf_cfg, dict): + vars_["logging_performance_enabled_var"].set(bool(perf_cfg.get("enabled", True))) + vars_["logging_track_functions_var"].set(bool(perf_cfg.get("track_function_calls", True))) + vars_["logging_monitor_warning_mb_var"].set(float(logging_config.get("monitor_warning_mb", 500.0) or 500.0)) + vars_["logging_monitor_critical_mb_var"].set(float(logging_config.get("monitor_critical_mb", 2000.0) or 2000.0)) + + +def write_debug_captures_to_cfg(cfg2: dict, vars_: Dict[str, tk.Variable]) -> None: + if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict): + cfg2["debug_captures"] = {} + cfg2["debug_captures"]["enabled"] = bool(vars_["debug_captures_enabled_var"].get()) + cfg2["debug_captures"]["auto_cleanup"] = bool(vars_["debug_captures_auto_cleanup_var"].get()) + cfg2["debug_captures"]["keep_days"] = int(vars_["debug_captures_keep_days_var"].get() or 7) + cfg2["debug_captures"]["max_files"] = int(vars_["debug_captures_max_files_var"].get() or 2000) + cfg2["debug_captures"]["async_save"] = bool(vars_["debug_captures_async_save_var"].get()) + cfg2["debug_captures"]["log_on_complete"] = bool(vars_["debug_captures_log_on_complete_var"].get()) + + +def write_logging_to_cfg(cfg2: dict, vars_: Dict[str, tk.Variable]) -> None: + if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict): + cfg2["logging"] = {} + cfg2["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get()) + cfg2["logging"]["color_output"] = bool(vars_["logging_color_var"].get()) + cfg2["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get()) + cfg2["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get()) + cfg2["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get()) + cfg2["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get() or 30) + cfg2["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get()) + cfg2["logging"]["max_total_size_gb"] = float(vars_["logging_max_total_size_gb_var"].get() or 10.0) + cfg2["logging"]["compress_after_days"] = int(vars_["logging_compress_after_days_var"].get() or 7) + cfg2["logging"]["debug_detail_level"] = str(vars_["logging_debug_level_var"].get() or "normal") + cfg2["logging"]["error_detail_level"] = str(vars_["logging_error_level_var"].get() or "full") + cfg2["logging"]["action_log_format"] = str(vars_["logging_action_format_var"].get() or "concise") + cfg2["logging"]["log_format_mode"] = str(vars_["logging_format_mode_var"].get() or "simple") + cfg2["logging"]["stage_diag_verbose"] = bool(vars_["stage_diag_verbose_var"].get()) + cfg2["logging"]["monitor_warning_mb"] = float(vars_["logging_monitor_warning_mb_var"].get() or 500.0) + cfg2["logging"]["monitor_critical_mb"] = float(vars_["logging_monitor_critical_mb_var"].get() or 2000.0) + + if "performance_tracking" not in cfg2["logging"] or not isinstance(cfg2["logging"]["performance_tracking"], dict): + cfg2["logging"]["performance_tracking"] = {} + cfg2["logging"]["performance_tracking"]["enabled"] = bool(vars_["logging_performance_enabled_var"].get()) + cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool(vars_["logging_track_functions_var"].get()) + cfg2["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get()) + cfg2["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log") + diff --git a/gui/components/run_params_builder.py b/gui/components/run_params_builder.py index b2d3a43..a3d9fa7 100644 --- a/gui/components/run_params_builder.py +++ b/gui/components/run_params_builder.py @@ -59,7 +59,7 @@ def get_params(vars_: Dict[str, tk.Variable]) -> RunParams: vars_["reservation_back_verify_enabled_var"].get() ), reservation_back_swipe_delay=float( - reservation_back_swipe_delavars_["y_var"].get() or 1.0 + vars_["reservation_back_swipe_delay_var"].get() or 1.0 ), fudai_find_max_attempts=int(vars_["fudai_find_max_attempts_var"].get() or 5), enable_ocr_mode1=bool(vars_["enable_ocr_mode1_var"].get()), @@ -68,7 +68,7 @@ def get_params(vars_: Dict[str, tk.Variable]) -> RunParams: vars_["fudai_template_match_threshold_var"].get() or 0.7 ), # 只养号模式与养号时长 - yanghao_only=bool(yg_onlvars_["y_var"].get()), + yanghao_only=bool(vars_["yg_only_var"].get()), yanghao_seconds=int(vars_["yg_recommend_duration_var"].get() or 0), enable_back_on_misses=bool(vars_["enable_back_on_misses_var"].get()), ) diff --git a/gui/gui_core_pkg/stats_log_parser.py b/gui/gui_core_pkg/stats_log_parser.py index 6e30822..954be47 100644 --- a/gui/gui_core_pkg/stats_log_parser.py +++ b/gui/gui_core_pkg/stats_log_parser.py @@ -21,6 +21,14 @@ from __future__ import annotations import re import time from typing import Any +from gui.gui_core_pkg.stats_log_parser_helpers import ( + parse_float_value, + parse_int_value, + search_group, + search_group_any, + set_meta_float_if_match, + set_meta_int_if_match, +) def update_stats_from_line(runner: Any, line: str) -> None: @@ -234,56 +242,26 @@ def _parse_skip_reasons(runner: Any, s: str) -> None: if "参与人数" in s and "< 阈值" in s and "不参与" in s: runner._inc("fudai_skip_participants_low") meta = runner._snapshot_fudai() - m = re.search(r"参与人数[=:]?\s*(\d+)", s) - if m: - try: - meta["participants"] = int(m.group(1)) - except Exception: - pass - m = re.search(r"阈值[=:]?\s*(\d+)", s) - if m: - try: - meta["threshold"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "participants", r"参与人数[=:]?\s*(\d+)") + set_meta_int_if_match(meta, s, "threshold", r"阈值[=:]?\s*(\d+)") runner._record_event("fudai_skip", {"reason": "participants_low", **meta}) if "参与人数" in s and "> 阈值" in s and "不参与" in s: runner._inc("fudai_skip_participants_high") meta = runner._snapshot_fudai() - m = re.search(r"参与人数[=:]?\s*(\d+)", s) - if m: - try: - meta["participants"] = int(m.group(1)) - except Exception: - pass - m = re.search(r"阈值[=:]?\s*(\d+)", s) - if m: - try: - meta["threshold"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "participants", r"参与人数[=:]?\s*(\d+)") + set_meta_int_if_match(meta, s, "threshold", r"阈值[=:]?\s*(\d+)") runner._record_event("fudai_skip", {"reason": "participants_high", **meta}) if "奖品价值" in s and "< 阈值" in s and "不参与" in s: runner._inc("fudai_skip_value_low") meta = runner._snapshot_fudai() - m = re.search( - r"(?:奖品)?价值[=:]?\s*([0-9]+(?:[.·.。·.。][0-9]+)?)", s + set_meta_float_if_match( + meta, s, "prize_value_yuan", r"(?:奖品)?价值[=:]?\s*([0-9]+(?:[.·.。·.。][0-9]+)?)" ) - if m: - try: - meta["prize_value_yuan"] = float(m.group(1)) - except Exception: - pass - m = re.search( - r"阈值[=:]?\s*([0-9]+(?:[.·.。·.。][0-9]+)?)", s + set_meta_float_if_match( + meta, s, "threshold", r"阈值[=:]?\s*([0-9]+(?:[.·.。·.。][0-9]+)?)" ) - if m: - try: - meta["threshold"] = float(m.group(1)) - except Exception: - pass runner._record_event("fudai_skip", {"reason": "value_low", **meta}) if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" in s): @@ -295,23 +273,13 @@ def _parse_skip_reasons(runner: Any, s: str) -> None: if "抽奖倒计时时间小于" in s and "不参与" in s: runner._inc("fudai_skip_countdown_short") meta = runner._snapshot_fudai() - m = re.search(r"(\d+)\s*秒", s) - if m: - try: - meta["countdown_seconds"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "countdown_seconds", r"(\d+)\s*秒") runner._record_event("fudai_skip", {"reason": "countdown_short", **meta}) if "抽奖倒计时时间大于" in s and "暂不参与" in s: runner._inc("fudai_skip_countdown_long") meta = runner._snapshot_fudai() - m = re.search(r"(\d+)\s*秒", s) - if m: - try: - meta["countdown_seconds"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "countdown_seconds", r"(\d+)\s*秒") runner._record_event("fudai_skip", {"reason": "countdown_long", **meta}) if ( @@ -337,21 +305,10 @@ def _parse_skip_reasons(runner: Any, s: str) -> None: ) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s): runner._inc("fudai_reserved_high_value") meta = runner._snapshot_fudai() - m = re.search( - r"(?:价值|价值元)[=:]?\s*([0-9]+(?:[.·.。·.。][0-9]+)?)", - s, + set_meta_float_if_match( + meta, s, "prize_value_yuan", r"(?:价值|价值元)[=:]?\s*([0-9]+(?:[.·.。·.。][0-9]+)?)" ) - if m: - try: - meta["prize_value_yuan"] = float(m.group(1)) - except Exception: - pass - m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s) - if m: - try: - meta["remain_seconds"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "remain_seconds", r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒") runner._record_event("fudai_reserved_high_value", meta) @@ -464,28 +421,22 @@ def _parse_reservation(runner: Any, s: str) -> None: "[预约]" in s and "已记录高价值福袋" in s ) or "record_high_value_reservation:已记录高价值福袋" in s: runner._inc("reservation_recorded") - value = None - m = re.search(r"(?:字段_)?(?:价值|价值元|value)[=:]?\s*(\d+(?:\.\d+)?)", s) - if not m: - m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s) - if m: - try: - value = float(m.group(1)) - except Exception: - pass - future_ts = None - m = re.search(r"(?:字段_)?(?:开奖时间|future|future_ts)[=:]?\s*(\d+)", s) - if m: - try: - future_ts = int(m.group(1)) - except Exception: - pass - room_title = None - m = re.search( - r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s + value = parse_float_value( + search_group_any( + s, + [ + r"(?:字段_)?(?:价值|价值元|value)[=:]?\s*(\d+(?:\.\d+)?)", + r"value[=:]?\s*(\d+(?:\.\d+)?)", + ], + ) ) - if m: - room_title = m.group(1).strip() + future_ts = parse_int_value( + search_group(s, r"(?:字段_)?(?:开奖时间|future|future_ts)[=:]?\s*(\d+)") + ) + room_title = None + rv = search_group(s, r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)") + if rv: + room_title = rv.strip() meta = runner._snapshot_fudai() if value is not None: meta["prize_value_yuan"] = value @@ -508,12 +459,7 @@ def _parse_reservation(runner: Any, s: str) -> None: ): runner._inc("reservation_back_success") meta = {} - m = re.search(r"(?:字段_)?(?:需回退次数|back_times)[=:]?\s*(\d+)", s) - if m: - try: - meta["back_times"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "back_times", r"(?:字段_)?(?:需回退次数|back_times)[=:]?\s*(\d+)") runner._record_event("reservation_back_success", meta) if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s: @@ -573,9 +519,9 @@ def _parse_lottery_results(runner: Any, s: str) -> None: ): runner._inc("fudai_result_win") meta = runner._snapshot_fudai() - m = re.search(r"(?:奖品|商品)[=:]?\s*([^\s]+)", s) - if m: - meta["prize"] = m.group(1).strip() + prize = search_group(s, r"(?:奖品|商品)[=:]?\s*([^\s]+)") + if prize: + meta["prize"] = prize.strip() runner._record_event("fudai_result_win", meta) runner._record_win() if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s): @@ -587,12 +533,7 @@ def _parse_lottery_results(runner: Any, s: str) -> None: ): runner._inc("fudai_waiting_lottery") meta = runner._snapshot_fudai() - m = re.search(r"(?:剩余|倒计时|remain_seconds)[=:]?\s*(\d+)", s) - if m: - try: - meta["remain_seconds"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "remain_seconds", r"(?:剩余|倒计时|remain_seconds)[=:]?\s*(\d+)") runner._record_event("fudai_waiting_lottery", meta) @@ -642,21 +583,11 @@ def _parse_stage_diag(runner: Any, s: str) -> None: if "阶段诊断完成" in s: runner._inc("stage_diagnosis_complete") meta = {} - m = re.search(r"阶段[=:]?\s*(\w+)", s) - if m: - meta["stage"] = m.group(1) - m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s) - if m: - try: - meta["elapsed_seconds"] = float(m.group(1)) - except Exception: - pass - m = re.search(r"分数[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s) - if m: - try: - meta["score"] = float(m.group(1)) - except Exception: - pass + stage = search_group(s, r"阶段[=:]?\s*(\w+)") + if stage: + meta["stage"] = stage + set_meta_float_if_match(meta, s, "elapsed_seconds", r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒") + set_meta_float_if_match(meta, s, "score", r"分数[=:]?\s*([0-9]+(?:\.[0-9]+)?)") runner._record_event("stage_diagnosis_complete", meta) elif "阶段诊断失败" in s or "阶段诊断错误" in s: runner._inc("stage_diagnosis_failed") @@ -697,12 +628,7 @@ def _parse_detail_read(runner: Any, s: str) -> None: ): runner._inc("fudai_detail_read_success") meta = {} - m = re.search(r"(?:任务数量|task_count)[=:]?\s*(\d+)", s) - if m: - try: - meta["task_count"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "task_count", r"(?:任务数量|task_count)[=:]?\s*(\d+)") runner._record_event("fudai_detail_read_success", meta) elif "识别失败" in s or "识别错误" in s: runner._inc("fudai_detail_read_failed") @@ -724,10 +650,5 @@ def _parse_back_operation(runner: Any, s: str) -> None: if "回退完成" in s or "回退成功" in s: runner._inc("reservation_back_operation") meta = {} - m = re.search(r"(?:回退|back_times)[=:]?\s*(\d+)", s) - if m: - try: - meta["back_times"] = int(m.group(1)) - except Exception: - pass + set_meta_int_if_match(meta, s, "back_times", r"(?:回退|back_times)[=:]?\s*(\d+)") runner._record_event("reservation_back_operation", meta) diff --git a/gui/gui_core_pkg/stats_log_parser_helpers.py b/gui/gui_core_pkg/stats_log_parser_helpers.py new file mode 100644 index 0000000..af69970 --- /dev/null +++ b/gui/gui_core_pkg/stats_log_parser_helpers.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import re +from typing import Any, Optional + + +def search_group(s: str, pattern: str, group: int = 1) -> Optional[str]: + m = re.search(pattern, s) + if not m: + return None + try: + return m.group(group) + except Exception: + return None + + +def search_group_any(s: str, patterns: list[str], group: int = 1) -> Optional[str]: + for p in patterns: + v = search_group(s, p, group=group) + if v is not None: + return v + return None + + +def parse_int_value(text: Optional[str]) -> Optional[int]: + if text is None: + return None + try: + return int(text) + except Exception: + return None + + +def parse_float_value(text: Optional[str]) -> Optional[float]: + if text is None: + return None + try: + return float(text) + except Exception: + return None + + +def set_meta_int_if_match(meta: dict[str, Any], s: str, key: str, pattern: str) -> None: + v = parse_int_value(search_group(s, pattern)) + if v is not None: + meta[key] = v + + +def set_meta_float_if_match(meta: dict[str, Any], s: str, key: str, pattern: str) -> None: + v = parse_float_value(search_group(s, pattern)) + if v is not None: + meta[key] = v diff --git a/gui/web_gui.py b/gui/web_gui.py index cdf2415..453e879 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -36,6 +36,10 @@ from gui.web_gui_pkg import ( ) from gui.web_gui_pkg.request_parsing import read_json, send_json from gui.web_gui_pkg.static_handler import serve_static +from gui.web_gui_pkg.net_config import get_web_gui_host, get_web_gui_port +from gui.web_gui_pkg.routes import handle_get, handle_post +from gui.web_gui_pkg import proc_runner_ops as _proc_ops +from gui.web_gui_pkg import proc_runner_stats as _proc_stats BASE_DIR = path_config.PROJECT_ROOT CONFIG_PATH = path_config.get_config_path() @@ -204,100 +208,13 @@ class ProcRunner: return self._proc is not None and self._proc.poll() is None def get_reservations(self) -> dict: - """获取当前预约队列信息(来自子进程写入的 douyin/core/state/reservations.json)。""" - if hasattr(path_config, "get_reservations_path"): - try: - path = path_config.get_reservations_path() - except Exception: - path = os.path.join( - ( - path_config.PROJECT_ROOT - if hasattr(path_config, "PROJECT_ROOT") - else os.getcwd() - ), - "douyin", - "core", - "state", - "reservations.json", - ) - else: - path = os.path.join( - os.getcwd(), "douyin", "core", "state", "reservations.json" - ) - try: - if os.path.exists(path): - with open(path, "r", encoding="utf-8") as f: - data = json.load(f) - if isinstance(data, dict): - return data - except Exception: - return { - "reservations": [], - "room_pos": 0, - "updated_ts": 0.0, - "reason": "state_read_or_parse_failed", - } - return { - "reservations": [], - "room_pos": 0, - "updated_ts": 0.0, - "reason": "no_state_file", - } + return _proc_ops.get_reservations(self) def get_high_value_rooms(self) -> dict: - """获取永久记录的高价值直播间列表(来自 state/high_value_rooms.json)。""" - path = path_config.get_high_value_rooms_path() - try: - if os.path.exists(path): - with open(path, "r", encoding="utf-8") as f: - data = json.load(f) - if isinstance(data, dict): - return data - if isinstance(data, list): - return { - "updated_ts": 0.0, - "reason": "legacy_list", - "total": len(data), - "rooms": data, - } - except Exception: - return { - "updated_ts": 0.0, - "reason": "state_read_or_parse_failed", - "total": 0, - "rooms": [], - } - return {"updated_ts": 0.0, "reason": "no_state_file", "total": 0, "rooms": []} + return _proc_ops.get_high_value_rooms(self) def send_back_key(self, device_id: str) -> bool: - try: - adb = find_adb_executable() - if not adb: - self._append_log("[错误] 未找到 adb.exe") - return False - if not device_id: - try: - device_id = resolve_adb_device(adb) - except Exception as e: - self._append_log(f"[错误] 设备选择失败: {e}") - return False - proc = subprocess.run( - [adb, "-s", device_id, "shell", "input", "keyevent", "4"], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=5, - check=False, - ) - if proc.returncode == 0: - self._append_log(f"[手动操作] 已发送返回键到设备: {device_id}") - return True - self._append_log(f"[错误] 发送返回键失败: {(proc.stderr or proc.stdout or '').strip()}") - return False - except Exception as e: - self._append_log(f"[错误] 发送返回键异常: {e}") - return False + return _proc_ops.send_back_key(self, device_id) def force_stop(self) -> None: with self._pid_lock: @@ -365,157 +282,7 @@ class ProcRunner: self._log = self._log[-cap:] def get_stats(self, include_events: bool = False) -> dict: - with self._lock: - running = self._proc is not None and self._proc.poll() is None - pid = self._pid - start_ts = self._start_ts - last_log_ts = self._last_log_ts - exit_code = self._exit_code - log_len = len(self._log) - counters = dict(self._counters) - fudai_last = dict(self._fudai_last) - events = list(self._events) - wins = list(self._wins) - - now = time.time() - uptime = 0 - if start_ts and start_ts > 0: - uptime = int(max(0, now - start_ts)) - - # ===== 统计聚合(趋势/分布/Top) ===== - now = time.time() - window_seconds = 2 * 3600 - bin_seconds = 5 * 60 - bins = int(window_seconds // bin_seconds) - ts0 = int(now - window_seconds) - - def _bin_idx(ts: float) -> int: - i = int((ts - ts0) // bin_seconds) - if i < 0: - return -1 - if i >= bins: - return -1 - return i - - series = { - "fudai_open_detail": [0] * bins, - "fudai_attend_ok": [0] * bins, - "fudai_attend_fail": [0] * bins, - "fudai_result_win": [0] * bins, - "fudai_result_no_win": [0] * bins, - "fudai_skip": [0] * bins, - "switch_room": [0] * bins, - } - - skip_reason = {} - switch_reason = {} - value_buckets = {} - participants_buckets = {} - countdown_buckets = {} - content_top = {} - - # 桶边界 - value_edges = [0, 10, 50, 100, 200, 500] - participants_edges = [0, 100, 500, 1000, 5000, 10000] - countdown_edges = [0, 30, 60, 5 * 60, 15 * 60, 60 * 60] - - for ev in events: - ts = float(ev.get("ts") or 0) - typ = str(ev.get("type") or "") - meta = ev.get("meta") if isinstance(ev.get("meta"), dict) else {} - bi = _bin_idx(ts) - if bi >= 0: - if typ in series: - series[typ][bi] += 1 - if typ == "fudai_skip": - series["fudai_skip"][bi] += 1 - if typ == "switch_room": - series["switch_room"][bi] += 1 - - # 分布/Top - if meta is not None: - if typ == "fudai_skip": - r = str(meta.get("reason") or "unknown") - self._inc_map(skip_reason, r, 1) - if typ == "switch_room": - r = str(meta.get("reason") or "unknown") - self._inc_map(switch_reason, r, 1) - - content = str(meta.get("content") or "").strip() - if content: - # 只取前 60 字符作为展示 key,避免超长撑爆 - key = (content[:60] + "…") if len(content) > 60 else content - self._inc_map(content_top, key, 1) - - v = meta.get("prize_value_yuan") - if isinstance(v, (int, float)): - b = self._bucket(float(v), [float(x) for x in value_edges]) - self._inc_map(value_buckets, b, 1) - p = meta.get("participants") - if isinstance(p, int): - b = self._bucket(float(p), [float(e) for e in participants_edges]) - self._inc_map(participants_buckets, b, 1) - cd = meta.get("countdown") - if isinstance(cd, str) and cd.strip(): - sec = self._parse_countdown_seconds(cd) - if isinstance(sec, int): - b = self._bucket( - float(sec), [float(e) for e in countdown_edges] - ) - self._inc_map(countdown_buckets, b, 1) - - def _top_k(m: dict, k: int = 10) -> list[dict]: - items = [{"key": kk, "count": int(vv)} for kk, vv in m.items()] - items.sort(key=lambda x: x["count"], reverse=True) - return items[:k] - - timeline = { - "start_ts": ts0, - "bin_seconds": bin_seconds, - "bins": bins, - "series": series, - } - - agg = { - "skip_reason": skip_reason, - "switch_reason": switch_reason, - "value_buckets": value_buckets, - "participants_buckets": participants_buckets, - "countdown_buckets": countdown_buckets, - "content_top": _top_k(content_top, 12), - "timeline": timeline, - } - - # 获取当前traceId和MDC上下文 - current_trace_id = getattr(self, "_current_trace_id", None) - mdc_context = dict(getattr(self, "_mdc_context", {})) - - payload = { - "running": bool(running), - "pid": pid, - "start_ts": start_ts, - "last_log_ts": last_log_ts, - "exit_code": exit_code, - "uptime_seconds": uptime, - "log_len": log_len, - "log_capacity": int(self._log_capacity or 0), - "log_file": self._log_file_path if self._log_file_enabled else "", - "counters": counters, - "fudai_last": fudai_last, - "agg": agg, - # 仅返回最近 20 条,避免过大 - "wins": wins[-20:], - # 统一日志系统信息 - "trace_id": current_trace_id, - "mdc_context": mdc_context, - } - - if include_events: - # 仅返回最近 200 条,防止数据过大 - tail = events[-200:] - payload["events"] = tail - - return payload + return _proc_stats.get_stats(self, include_events) def get_logs_since(self, idx: int) -> tuple[int, list[str]]: with self._lock: @@ -530,55 +297,10 @@ class ProcRunner: return log_len, lines def start_test_yanghao(self, device_id: str, seconds: int) -> None: - if self.is_running(): - raise RuntimeError("already running") - - seconds = int(seconds or 0) - if seconds <= 0: - seconds = 60 - - run_cli_path = path_config.get_run_cli_path() - if not os.path.exists(run_cli_path): - raise FileNotFoundError( - f"run_cli.py not found.\n" - f"Expected path: {run_cli_path}\n" - f"Please ensure run_cli.py is in the project root directory." - ) - cmd = [ - sys.executable, - run_cli_path, - "--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) + return _proc_ops.start_test_yanghao(self, device_id, seconds) def start_test_comment(self, 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() - if not os.path.exists(run_cli_path): - raise FileNotFoundError( - f"run_cli.py not found.\n" - f"Expected path: {run_cli_path}\n" - f"Please ensure run_cli.py is in the project root directory." - ) - cmd = [ - sys.executable, - run_cli_path, - "--test-comment", - ] - if text: - cmd += ["--test-comment-text", text] - device_id = resolve_adb_device(find_adb_executable(), device_id) - cmd += ["--device-id", device_id] - - self._start_process(cmd) + return _proc_ops.start_test_comment(self, device_id, text) def start_main_run(self, params: dict) -> None: if self.is_running(): @@ -920,797 +642,17 @@ class Handler(BaseHTTPRequestHandler): def do_GET(self): u = urlparse(self.path) - if u.path.startswith("/api/"): - api_path = u.path.rstrip("/") - # 提供 CSRF token 给前端 - if u.path == "/api/csrf-token": - return self._send_json({"token": _CSRF_TOKEN}) - if u.path == "/api/version": - try: - from version import APP_VERSION, APP_BUILD_DATE, APP_NAME - except Exception: - APP_VERSION, APP_BUILD_DATE, APP_NAME = "?", "?", "douyin_guaji" - return self._send_json({ - "name": APP_NAME, - "version": str(APP_VERSION).lstrip("Vv"), - "build": APP_BUILD_DATE, - }) - if u.path == "/api/devices": - adb = find_adb_executable() - return self._send_json({"adb": adb, "devices": list_adb_devices(adb)}) - if u.path == "/api/wifi/last": - # 返回 last_wifi_target 记录(也支持 POST) - try: - from gui.gui_core_pkg import get_last_wifi_target - return self._send_json({"ok": True, "last": get_last_wifi_target()}) - except Exception as e: - return self._send_json({"ok": False, "error": str(e)}, status=500) - if u.path == "/api/config": - cfg = read_config() - return self._send_json(cfg) - if u.path == "/api/stats": - qs = parse_qs(u.query) - detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in ( - "1", - "true", - "yes", - ) - return self._send_json(RUNNER.get_stats(include_events=detail)) - if api_path in ("/api/reservations", "/api/reservation"): - # 返回当前预约队列信息 - return self._send_json(RUNNER.get_reservations()) - if api_path in ( - "/api/high-value-rooms", - "/api/high_value_rooms", - "/api/high_value_room", - "/api/high-value-room", - ): - return self._send_json(RUNNER.get_high_value_rooms()) - if u.path == "/api/logs": - qs = parse_qs(u.query) - # 支持后端搜索模式:当提供 q 参数时,按最近若干条在后端过滤并返回(与 /api/actions 行为一致) - q = (qs.get("q") or [""])[0] - try: - tail_n = int((qs.get("lines") or [200])[0]) - except Exception: - tail_n = 200 - - # 如果提供了搜索关键词,则走后端过滤路径,忽略 since(前端会使用此接口做搜索) - if q: - try: - # 取最近 tail_n 条作为候选,然后按关键词过滤(不区分大小写) - with RUNNER._lock: - total = len(RUNNER._log) - cand = ( - RUNNER._log[-tail_n:] if tail_n > 0 else RUNNER._log[:] - ) - qlow = q.lower() - filtered = [l for l in cand if qlow in (l or "").lower()] - return self._send_json( - { - "next": total, - "lines": filtered, - "running": RUNNER.is_running(), - } - ) - except Exception as e: - import traceback - - _wg_log( - f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}", - level="ERROR", - ) - return self._send_json( - {"next": 0, "lines": [], "running": RUNNER.is_running()} - ) - - # 默认行为:按 since 增量返回日志(原有逻辑) - since = 0 - try: - since = int((qs.get("since") or [0])[0]) - except (ValueError, TypeError, IndexError): - since = 0 - try: - next_idx, lines = RUNNER.get_logs_since(since) - return self._send_json( - { - "next": next_idx, - "lines": lines, - "running": RUNNER.is_running(), - } - ) - except Exception as e: - # 记录错误但不中断请求,返回空日志 - import traceback - - _wg_log( - f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}", - level="ERROR", - ) - return self._send_json( - {"next": 0, "lines": [], "running": RUNNER.is_running()} - ) - if u.path == "/api/logfile-tail": - # 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试 - qs = parse_qs(u.query) - try: - n = int((qs.get("lines") or [100])[0]) - except Exception: - n = 100 - path = ( - RUNNER._log_file_path - if hasattr(RUNNER, "_log_file_path") - else path_config.get_log_file_path() - ) - out_lines = [] - try: - if os.path.exists(path): - # 读取尾部若干行(简单实现:读全文件或最后 64KB) - size = os.path.getsize(path) - read_bytes = min(size, 65536) - with open(path, "rb") as f: - if read_bytes < size: - f.seek(-read_bytes, os.SEEK_END) - data = f.read().decode("utf-8", errors="replace") - parts = data.splitlines() - out_lines = parts[-n:] - except Exception: - out_lines = [""] - return self._send_json({"ok": True, "path": path, "lines": out_lines}) - - if u.path == "/api/actions": - # 返回精简行为日志(logs/actions.log)的尾部若干行,便于在 Web GUI 中单独查看点击/识别耗时 - qs = parse_qs(u.query) - try: - n = int((qs.get("lines") or [200])[0]) - except Exception: - n = 200 - # 使用统一的路径配置(优先使用 path_config 中的配置,失败时回退到项目内置路径) - if hasattr(path_config, "get_actions_log_path"): - try: - path = path_config.get_actions_log_path() - except Exception: - path = os.path.join( - ( - path_config.PROJECT_ROOT - if hasattr(path_config, "PROJECT_ROOT") - else os.getcwd() - ), - "logs", - "actions.log", - ) - else: - path = os.path.join(os.getcwd(), "logs", "actions.log") - out_lines: list[str] = [] - try: - if os.path.exists(path): - size = os.path.getsize(path) - read_bytes = min(size, 65536) - with open(path, "rb") as f: - if read_bytes < size: - f.seek(-read_bytes, os.SEEK_END) - data = f.read().decode("utf-8", errors="replace") - parts = data.splitlines() - out_lines = parts[-n:] - except Exception: - out_lines = [""] - return self._send_json({"ok": True, "path": path, "lines": out_lines}) - self.send_error(HTTPStatus.NOT_FOUND) - return - - if u.path.startswith("/pic/"): - # 只允许读取 pic 目录下的文件(便于前端预览 latest.png) - rel = u.path.lstrip("/") - safe = os.path.normpath(rel).replace("\\", "/") - if not safe.startswith("pic/"): - self.send_error(HTTPStatus.FORBIDDEN) - return - full = os.path.join(str(path_config.PROJECT_ROOT), safe) - if not os.path.isfile(full): - self.send_error(HTTPStatus.NOT_FOUND) - return - ext = os.path.splitext(full)[1].lower() - ctype = { - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - }.get(ext, "application/octet-stream") - with open(full, "rb") as f: - data = f.read() - self.send_response(HTTPStatus.OK) - self.send_header("Content-Type", ctype) - self.send_header("Content-Length", str(len(data))) - self.send_header("Cache-Control", "no-store") - self.end_headers() - self.wfile.write(data) - return - - self._serve_static(u.path) - - def _verify_csrf_token(self) -> bool: - """验证 CSRF token,本地服务器的简单防护""" - token = self.headers.get("X-CSRF-Token", "") - return token == _CSRF_TOKEN + return handle_get(self, u, RUNNER, _CSRF_TOKEN) def do_POST(self): u = urlparse(self.path) - - # CSRF token 验证(对修改操作的 POST 请求) - if not self._verify_csrf_token(): - return self._send_json({"ok": False, "error": "Invalid CSRF token"}, status=403) - - if u.path == "/api/config": - body = self._read_json() - cfg = read_config() - update = ( - body.get("config") if isinstance(body.get("config"), dict) else body - ) - - int_keys = { - "min_participants", - "max_participants", - "skip_if_countdown_lt_seconds", - "skip_if_countdown_gt_seconds", - "reset_after_swipes", - "fudai_find_max_attempts", - "fudai_quiet_start_hour", - "fudai_quiet_end_hour", - "high_value_fudai_join_ahead_seconds", - "high_value_fudai_max_swipe_back", - "high_value_fudai_max_reservations", - "yanghao_like_icon_x", - "yanghao_like_icon_y", - "yanghao_fav_icon_x", - "yanghao_fav_icon_y", - "yanghao_like_roi_offset_x", - "yanghao_like_roi_offset_y", - "yanghao_fav_roi_offset_x", - "yanghao_fav_roi_offset_y", - "yanghao_icon_roi_size", - "yanghao_comment_btn_x", - "yanghao_comment_btn_y", - "yanghao_comment_input_x", - "yanghao_comment_input_y", - "yanghao_comment_send_x", - "yanghao_comment_send_y", - "yanghao_comment_close_x", - "yanghao_comment_close_y", - "yanghao_after_dwell_swipe_distance_px", - "yanghao_recommend_duration_seconds", - "yanghao_recommend_interval_seconds", - "wait_minutes", - "y_pianyi", - "fudai_exit_after_misses", - "swipe_duration_ms", - "swipe_up_start_y", - "swipe_up_end_y", - "high_value_room_revisit_min_interval_seconds", - "high_value_room_revisit_max_per_run", - "high_value_room_revisit_max_age_days", - "logging.keep_days", - "logging.compress_after_days", - } - float_keys = { - "min_prize_value_yuan", - "yanghao_like_prob", - "yanghao_fav_prob", - "yanghao_comment_prob", - "yanghao_icon_match_threshold", - "fudai_template_match_threshold", - "lucky_draw_red_ratio_threshold", - "live_room_match_threshold", - "stage_diag_max_time", - "stage_diag_max_step_time", - "fudai_icon_retry_delay_seconds", - "fudai_icon_max_wait_seconds", - "reservation_back_swipe_delay", - "high_value_fudai_threshold_yuan", - "fansclub_click_delay", - "fansclub_auto_join_wait_seconds", - "fansclub_manual_wait_seconds", - "fudai_click_wait_seconds", - "fudai_detail_template_threshold", - "coupon_template_match_threshold", - "attend_button_red_ratio_threshold", - "fansclub_join_red_ratio_threshold", - "shopping_redpacket_red_ratio_threshold", - "high_value_fudai_poll_before_seconds", - "high_value_room_revisit_min_prize_value", - "reservation_back_verify_wait_seconds", - "switch_room_wait_after_stage_diag_seconds", - "logging.max_total_size_gb", - "logging.monitor_warning_mb", - "logging.monitor_critical_mb", - } - bool_keys = { - "auto_join_fansclub", - "reset_after_swipes_enabled", - "yanghao_enable_actions", - "yanghao_enabled", - "yanghao_step_screenshot", - "enable_ocr_mode1", - "fudai_template_match_enabled", - "fudai_quiet_hours_enabled", - "high_value_fudai_enabled", - "fudai_disable_content_recognition", - "high_value_room_revisit_enabled", - "high_value_room_revisit_only_current_run", - "reservation_back_verify_enabled", - "needswitch", - "infinite_loop_enabled", - "enable_back_on_misses", - "enable_streaming_screenshot", - "fudai_disable_task_recognition", - "yanghao_only", - "debug_captures.async_save", - "debug_captures.log_on_complete", - "logging.beautify_output", - "logging.color_output", - "logging.show_timestamps", - "logging.enable_monitor", - "logging.compress_logs", - "logging.stage_diag_verbose", - "logging.performance_tracking.enabled", - "logging.performance_tracking.track_function_calls", - } - list_str_keys = { - "contains_want", - "contains_not_want", - "yanghao_comment_texts", - "yanghao_like_keywords", - "yanghao_fav_keywords", - } - - deny_keys = { - "yanghao_use_recommend_flow", - "yanghao_text_recommend", - "yanghao_text_live", - "yanghao_text_enter_live", - "yanghao_fallback_close_x", - "yanghao_fallback_close_y", - "yanghao_fallback_recommend_x", - "yanghao_fallback_recommend_y", - "yanghao_fallback_live_x", - "yanghao_fallback_live_y", - "yanghao_fallback_enter_live_x", - "yanghao_fallback_enter_live_y", - } - - def set_nested_value(obj, key, value): - """设置嵌套配置值,支持如 'debug_captures.auto_cleanup' 这样的键""" - if "." in key: - parts = key.split(".") - current = obj - for part in parts[:-1]: - if part not in current or not isinstance(current[part], dict): - current[part] = {} - current = current[part] - current[parts[-1]] = value - else: - obj[key] = value - - for k, v in (update or {}).items(): - if k in deny_keys: - continue - if k in int_keys: - try: - set_nested_value(cfg, k, int(v)) - except Exception: - continue - elif k in float_keys: - try: - set_nested_value(cfg, k, float(v)) - except Exception: - continue - elif k in bool_keys: - set_nested_value(cfg, k, bool(v)) - elif k in list_str_keys: - if isinstance(v, list): - set_nested_value(cfg, k, [str(x) for x in v if str(x).strip()]) - else: - set_nested_value( - cfg, - k, - [ - str(x).strip() - for x in str(v).splitlines() - if str(x).strip() - ], - ) - else: - set_nested_value(cfg, k, v) - - write_config(cfg) - return self._send_json({"ok": True}) - - if u.path == "/api/start-run": - if RUNNER.is_running(): - return self._send_json({"ok": False, "error": "running"}, status=409) - body = self._read_json() - try: - RUNNER.start_main_run(body or {}) - except Exception as e: - return self._send_json({"ok": False, "error": str(e)}, status=500) - return self._send_json({"ok": True}) - - # Web 端补齐的手动动作与桌面 GUI 常用操作。 - - if u.path == "/api/force-stop": - RUNNER.force_stop() - return self._send_json({"ok": True, "message": "已执行强制停止"}) - - if u.path == "/api/back-key": - body = self._read_json() - device_id = str(body.get("device_id") or "").strip() - ok = RUNNER.send_back_key(device_id) - return self._send_json({"ok": bool(ok), "message": "返回键已发送" if ok else "发送返回键失败"}, status=200 if ok else 500) - - if u.path == "/api/wifi/enable": - body = self._read_json() - adb = find_adb_executable() - device_id = str(body.get("device_id") or "").strip() - if not device_id: - return self._send_json({"ok": False, "error": "missing device_id"}, status=400) - try: - from gui.gui_core import enable_wifi_adb - ok, msg = enable_wifi_adb(adb, device_id) - except Exception as e: - ok, msg = False, str(e) - return self._send_json({"ok": bool(ok), "message": msg}, status=200 if ok else 500) - - if u.path == "/api/wifi/connect": - body = self._read_json() - adb = find_adb_executable() - ip = str(body.get("ip") or "").strip() - port = str(body.get("port") or "5555").strip() or "5555" - if not ip: - return self._send_json({"ok": False, "error": "missing ip"}, status=400) - try: - from gui.gui_core import connect_wifi_adb - ok, msg = connect_wifi_adb(adb, ip, port) - except Exception as e: - ok, msg = False, str(e) - # 成功后记住,下次启动时自动重连 - if ok: - try: - from gui.gui_core_pkg import set_last_wifi_target - from gui.gui_core_pkg.wifi_adb_scan import query_device_model - target = ip if ":" in ip else f"{ip}:{port}" - model = "" - try: - model = query_device_model(adb, target) - except Exception: - pass - set_last_wifi_target(target, model) - except Exception: - pass - devices = list_adb_devices(adb) if adb else [] - return self._send_json({"ok": bool(ok), "message": msg, "devices": devices}, status=200 if ok else 500) - - if u.path == "/api/wifi/disconnect": - body = self._read_json() - adb = find_adb_executable() - ip = str(body.get("ip") or "").strip() - port = str(body.get("port") or "5555").strip() or "5555" - if not ip: - return self._send_json({"ok": False, "error": "missing ip"}, status=400) - try: - from gui.gui_core import disconnect_wifi_adb - ok, msg = disconnect_wifi_adb(adb, ip, port) - except Exception as e: - ok, msg = False, str(e) - # 如果断开的就是上次记住的设备,清掉记录 - if ok: - try: - from gui.gui_core_pkg import ( - clear_last_wifi_target, - get_last_wifi_target, - ) - last = get_last_wifi_target() - last_target = str(last.get("target") or "") - if last_target.startswith(ip): - clear_last_wifi_target() - except Exception: - pass - devices = list_adb_devices(adb) if adb else [] - return self._send_json({"ok": bool(ok), "message": msg, "devices": devices}, status=200 if ok else 500) - - if u.path == "/api/wifi/scan": - """扫描局域网 ADB 设备。 - - POST body 可选字段: - - subnet: 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5; - 留空则自动用本机子网 - - ports: 端口规格(int / str / list)。"5555,37000-40000" 等。 - 留空 → 仅扫 5555。 - - probe_timeout: 单 IP 探测超时秒(默认 0.3) - """ - body = self._read_json() - adb = find_adb_executable() - subnet = str(body.get("subnet") or "").strip() or None - probe_timeout = float(body.get("probe_timeout") or 0.3) - ports_raw = body.get("ports") - try: - from gui.gui_core_pkg import ( - discover_adb_devices, - get_local_subnet, - parse_port_spec, - ) - port_list = parse_port_spec(ports_raw) - devs = discover_adb_devices( - adb, - subnet_spec=subnet, - ports=port_list, - probe_timeout=probe_timeout, - ) - payload = [ - { - "target": d.target, - "ip": d.ip, - "port": d.port, - "state": d.adb_state, - "model": d.model, - "message": d.message, - } - for d in devs - ] - return self._send_json( - { - "ok": True, - "subnet": subnet or get_local_subnet() or "", - "ports": port_list, - "devices": payload, - } - ) - except Exception as e: - return self._send_json( - {"ok": False, "error": str(e)}, status=500 - ) - - if u.path == "/api/wifi/last": - """返回 last_wifi_target 记录(GET 也支持)。""" - try: - from gui.gui_core_pkg import get_last_wifi_target - last = get_last_wifi_target() - return self._send_json({"ok": True, "last": last}) - except Exception as e: - return self._send_json( - {"ok": False, "error": str(e)}, status=500 - ) - - if u.path == "/api/wifi/last/clear": - """清除 last_wifi_target 记录。""" - try: - from gui.gui_core_pkg import clear_last_wifi_target - clear_last_wifi_target() - return self._send_json({"ok": True}) - except Exception as e: - return self._send_json( - {"ok": False, "error": str(e)}, status=500 - ) - - if u.path == "/api/wifi/auto-reconnect": - """启动自动重连:先 verify 上次的 target,失败则扫描子网 + 智能匹配。 - - 返回: - { - "ok": true, - "action": "noop" | "already_online" | "reconnected" | "matched" | "failed", - "target": "192.168.5.2:5555", # 当前选定的 target,可能为空 - "model": "PEPM00", # 选中的 model,可能为空 - "message": "...", - "devices": [...] # 扫描候选(仅 action 是 matched/failed 时返回) - } - """ - try: - from gui.gui_core_pkg import ( - discover_adb_devices, - get_last_wifi_target, - pick_best_match, - set_last_wifi_target, - ) - from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target - except Exception as e: - return self._send_json( - {"ok": False, "error": f"import failed: {e}"}, status=500 - ) - - adb = find_adb_executable() - last = get_last_wifi_target() or {} - target = str(last.get("target") or "") - model = str(last.get("model") or "") - - if not target: - return self._send_json( - { - "ok": True, - "action": "noop", - "target": "", - "model": "", - "message": "无上次记录", - } - ) - - existing = list_adb_devices(adb) if adb else [] - if target in existing: - return self._send_json( - { - "ok": True, - "action": "already_online", - "target": target, - "model": model, - "message": f"WiFi 设备已在线: {target}", - } - ) - if existing: - return self._send_json( - { - "ok": True, - "action": "noop", - "target": existing[0], - "model": "", - "message": ( - f"当前已有设备 {existing[0]}," - f"上次 WiFi 目标 {target} 不抢占" - ), - } - ) - - # 直连 - try: - state, _ = verify_adb_target(adb, target) - except Exception as e: - state = "failed" - _ = str(e) - - if state == "connected": - return self._send_json( - { - "ok": True, - "action": "reconnected", - "target": target, - "model": model, - "message": f"自动重连成功: {target}", - } - ) - if state == "unauthorized": - return self._send_json( - { - "ok": True, - "action": "failed", - "target": target, - "model": model, - "message": ( - f"上次设备 {target} 未授权,请在手机上确认 ADB 调试授权" - ), - } - ) - - # 不可达 → 扫描 + 智能匹配 - # 如果上次记的端口非 5555,把它加进扫描列表(覆盖 Android 11+ 随机端口的场景) - try: - from gui.gui_core_pkg import parse_port_spec - last_port = 5555 - if ":" in target: - try: - last_port = int(target.rsplit(":", 1)[1]) - except ValueError: - pass - scan_ports = [5555] if last_port == 5555 else [5555, last_port] - devs = discover_adb_devices(adb, ports=scan_ports) - except Exception as e: - return self._send_json( - { - "ok": False, - "error": f"自动扫描失败: {e}", - }, - status=500, - ) - - best = pick_best_match(devs, last) - payload_devs = [ - { - "target": d.target, - "ip": d.ip, - "port": d.port, - "state": d.adb_state, - "model": d.model, - } - for d in devs - ] - - if best is None: - return self._send_json( - { - "ok": True, - "action": "failed", - "target": target, - "model": model, - "message": ( - f"上次目标 {target} 不可达," - f"扫描发现 {len(devs)} 台候选但无明确匹配" - if devs - else ( - f"上次目标 {target} 不可达,扫描也未发现其它设备。" - f"请检查手机和电脑是否在同一 WiFi" - ) - ), - "devices": payload_devs, - } - ) - - # 命中:更新记忆并返回 - try: - set_last_wifi_target(best.target, best.model or model) - except Exception: - pass - - if best.target == target: - msg = f"自动重连成功(扫描确认): {best.target}" - else: - msg = ( - f"上次目标 {target} 已变 → 智能匹配到 {best.target}" - + (f" ({best.model})" if best.model else "") - + "(已更新记忆)" - ) - return self._send_json( - { - "ok": True, - "action": "matched", - "target": best.target, - "model": best.model or "", - "message": msg, - "devices": payload_devs, - } - ) - - if u.path == "/api/test-yanghao": - if RUNNER.is_running(): - return self._send_json({"ok": False, "error": "running"}, status=409) - body = self._read_json() - cfg = read_config() - seconds = int(body.get("seconds") or cfg.get("yanghao_recommend_duration_seconds") or 60) - RUNNER.start_main_run({"device_id": str(body.get("device_id") or ""), "yanghao_only": True, "yanghao_seconds": seconds, "wait_minutes": 0}) - return self._send_json({"ok": True}) - - if u.path == "/api/test-comment": - return self._send_json({"ok": False, "error": "独立测试评论接口已移除,请用养号参数中的评论概率/文案后启动养号流程"}, status=410) - - if u.path == "/api/stop": - RUNNER.stop() - return self._send_json({"ok": True}) - - if u.path == "/api/screenshot": - # 手动截图接口 - body = self._read_json() - device_id = str(body.get("device_id") or "").strip() - try: - from douyin.core.underlying_operations import underlying_operations - - ops = underlying_operations() - result = ops.get_screenshot(device_id, use_service=False) - if result: - return self._send_json({"ok": True, "message": "截图成功"}) - else: - return self._send_json( - {"ok": False, "error": "截图失败"}, status=500 - ) - except Exception as e: - return self._send_json({"ok": False, "error": str(e)}, status=500) - - self.send_error(HTTPStatus.NOT_FOUND) + return handle_post(self, u, RUNNER, _CSRF_TOKEN) def main() -> int: - host = "127.0.0.1" + host = get_web_gui_host() # 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000 - env_port = os.environ.get("PORT") or os.environ.get("WEB_GUI_PORT") or "8000" - try: - port = int(env_port) - except Exception: - port = 8000 - if port < 1 or port > 65535: - port = 8000 + port = get_web_gui_port() print(f"[WEBGUI] 启动端口={port}(可设置环境变量 PORT 覆盖)") try: httpd = ThreadingHTTPServer((host, port), Handler) diff --git a/gui/web_gui_pkg/proc_runner_ops.py b/gui/web_gui_pkg/proc_runner_ops.py new file mode 100644 index 0000000..2bd31d7 --- /dev/null +++ b/gui/web_gui_pkg/proc_runner_ops.py @@ -0,0 +1,150 @@ +"""ProcRunner 独立操作方法实现(从 gui/web_gui.py 抽离)。""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from typing import Any + +from douyin.core import path_config +from .adb_compat import find_adb_executable, resolve_adb_device + + +def get_reservations(self: Any) -> dict: + """获取当前预约队列信息。""" + try: + path = path_config.get_reservations_path() + except Exception: + base_dir = ( + path_config.PROJECT_ROOT + if hasattr(path_config, "PROJECT_ROOT") + else os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) + ) + path = os.path.join(base_dir, "douyin", "core", "state", "reservations.json") + + try: + if os.path.exists(path): + with open(path, "r", encoding="utf-8") as f: + data = json.load(f) + if isinstance(data, dict): + return data + except Exception: + return { + "reservations": [], + "room_pos": 0, + "updated_ts": 0.0, + "reason": "state_read_or_parse_failed", + } + return { + "reservations": [], + "room_pos": 0, + "updated_ts": 0.0, + "reason": "no_state_file", + } + + +def get_high_value_rooms(self: Any) -> dict: + """获取永久记录的高价值直播间列表。""" + path = path_config.get_high_value_rooms_path() + try: + if os.path.exists(path): + with open(path, "r", encoding="utf-8") as f: + data = json.load(f) + if isinstance(data, dict): + return data + if isinstance(data, list): + return { + "updated_ts": 0.0, + "reason": "legacy_list", + "total": len(data), + "rooms": data, + } + except Exception: + return { + "updated_ts": 0.0, + "reason": "state_read_or_parse_failed", + "total": 0, + "rooms": [], + } + return {"updated_ts": 0.0, "reason": "no_state_file", "total": 0, "rooms": []} + + +def send_back_key(self: Any, device_id: str) -> bool: + try: + adb = find_adb_executable() + if not adb: + self._append_log("[错误] 未找到 adb.exe") + return False + if not device_id: + try: + device_id = resolve_adb_device(adb) + except Exception as e: + self._append_log(f"[错误] 设备选择失败: {e}") + return False + proc = subprocess.run( + [adb, "-s", device_id, "shell", "input", "keyevent", "4"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=5, + check=False, + ) + if proc.returncode == 0: + self._append_log(f"[手动操作] 已发送返回键到设备: {device_id}") + return True + self._append_log(f"[错误] 发送返回键失败: {(proc.stderr or proc.stdout or '').strip()}") + return False + except Exception as e: + self._append_log(f"[错误] 发送返回键异常: {e}") + return False + + +def resolve_device_id_for_action(self: Any, requested_device_id: str) -> tuple[str, str]: + """解析动作类接口使用的设备 ID;返回 (device_id, error_msg)。""" + device_id = str(requested_device_id or "").strip() + adb = find_adb_executable() + if not adb: + return "", "未找到 adb.exe" + if not device_id: + try: + device_id = resolve_adb_device(adb) + except Exception: + return "", "未选择设备,且无法自动解析在线设备" + return device_id, "" + + +def start_test_yanghao(self: Any, device_id: str, seconds: int) -> None: + if self.is_running(): + raise RuntimeError("already running") + seconds = int(seconds or 0) + if seconds <= 0: + seconds = 60 + run_cli_path = 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." + ) + cmd = [sys.executable, run_cli_path, "--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) + + +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() + 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." + ) + cmd = [sys.executable, run_cli_path, "--test-comment"] + if text: + cmd += ["--test-comment-text", text] + device_id = resolve_adb_device(find_adb_executable(), device_id) + cmd += ["--device-id", device_id] + self._start_process(cmd) diff --git a/gui/web_gui_pkg/proc_runner_stats.py b/gui/web_gui_pkg/proc_runner_stats.py new file mode 100644 index 0000000..bddee44 --- /dev/null +++ b/gui/web_gui_pkg/proc_runner_stats.py @@ -0,0 +1,148 @@ +"""ProcRunner 统计聚合逻辑(从 gui/web_gui.py 抽离)。""" + +from __future__ import annotations + +import time +from typing import Any + + +def get_stats(self: Any, include_events: bool = False) -> dict: + with self._lock: + running = self._proc is not None and self._proc.poll() is None + pid = self._pid + start_ts = self._start_ts + last_log_ts = self._last_log_ts + exit_code = self._exit_code + log_len = len(self._log) + counters = dict(self._counters) + fudai_last = dict(self._fudai_last) + events = list(self._events) + wins = list(self._wins) + + now = time.time() + uptime = 0 + if start_ts and start_ts > 0: + uptime = int(max(0, now - start_ts)) + + now = time.time() + window_seconds = 2 * 3600 + bin_seconds = 5 * 60 + bins = int(window_seconds // bin_seconds) + ts0 = int(now - window_seconds) + + def _bin_idx(ts: float) -> int: + i = int((ts - ts0) // bin_seconds) + if i < 0 or i >= bins: + return -1 + return i + + series = { + "fudai_open_detail": [0] * bins, + "fudai_attend_ok": [0] * bins, + "fudai_attend_fail": [0] * bins, + "fudai_result_win": [0] * bins, + "fudai_result_no_win": [0] * bins, + "fudai_skip": [0] * bins, + "switch_room": [0] * bins, + } + + skip_reason = {} + switch_reason = {} + value_buckets = {} + participants_buckets = {} + countdown_buckets = {} + content_top = {} + + value_edges = [0, 10, 50, 100, 200, 500] + participants_edges = [0, 100, 500, 1000, 5000, 10000] + countdown_edges = [0, 30, 60, 5 * 60, 15 * 60, 60 * 60] + + for ev in events: + ts = float(ev.get("ts") or 0) + typ = str(ev.get("type") or "") + meta = ev.get("meta") if isinstance(ev.get("meta"), dict) else {} + bi = _bin_idx(ts) + if bi >= 0: + if typ in series: + series[typ][bi] += 1 + if typ == "fudai_skip": + series["fudai_skip"][bi] += 1 + if typ == "switch_room": + series["switch_room"][bi] += 1 + + if meta is not None: + if typ == "fudai_skip": + r = str(meta.get("reason") or "unknown") + self._inc_map(skip_reason, r, 1) + if typ == "switch_room": + r = str(meta.get("reason") or "unknown") + self._inc_map(switch_reason, r, 1) + + content = str(meta.get("content") or "").strip() + if content: + key = (content[:60] + "…") if len(content) > 60 else content + self._inc_map(content_top, key, 1) + + v = meta.get("prize_value_yuan") + if isinstance(v, (int, float)): + b = self._bucket(float(v), [float(x) for x in value_edges]) + self._inc_map(value_buckets, b, 1) + p = meta.get("participants") + if isinstance(p, int): + b = self._bucket(float(p), [float(e) for e in participants_edges]) + self._inc_map(participants_buckets, b, 1) + cd = meta.get("countdown") + if isinstance(cd, str) and cd.strip(): + sec = self._parse_countdown_seconds(cd) + if isinstance(sec, int): + b = self._bucket(float(sec), [float(e) for e in countdown_edges]) + self._inc_map(countdown_buckets, b, 1) + + def _top_k(m: dict, k: int = 10) -> list[dict]: + items = [{"key": kk, "count": int(vv)} for kk, vv in m.items()] + items.sort(key=lambda x: x["count"], reverse=True) + return items[:k] + + timeline = { + "start_ts": ts0, + "bin_seconds": bin_seconds, + "bins": bins, + "series": series, + } + + agg = { + "skip_reason": skip_reason, + "switch_reason": switch_reason, + "value_buckets": value_buckets, + "participants_buckets": participants_buckets, + "countdown_buckets": countdown_buckets, + "content_top": _top_k(content_top, 12), + "timeline": timeline, + } + + current_trace_id = getattr(self, "_current_trace_id", None) + mdc_context = dict(getattr(self, "_mdc_context", {})) + + payload = { + "running": bool(running), + "pid": pid, + "start_ts": start_ts, + "last_log_ts": last_log_ts, + "exit_code": exit_code, + "uptime_seconds": uptime, + "log_len": log_len, + "log_capacity": int(self._log_capacity or 0), + "log_file": self._log_file_path if self._log_file_enabled else "", + "counters": counters, + "fudai_last": fudai_last, + "agg": agg, + "wins": wins[-20:], + "trace_id": current_trace_id, + "mdc_context": mdc_context, + } + + if include_events: + payload["events"] = events[-200:] + + return payload + diff --git a/gui/web_gui_pkg/static_handler.py b/gui/web_gui_pkg/static_handler.py index 2598260..23f7315 100644 --- a/gui/web_gui_pkg/static_handler.py +++ b/gui/web_gui_pkg/static_handler.py @@ -50,23 +50,26 @@ def serve_static( data = f.read() # 对于静态资源,使用适当的缓存策略 cache_control = "no-store" if ext in (".html", ".js") else "public, max-age=3600" - handler.send_response(HTTPStatus.OK) - handler.send_header("Content-Type", ctype) - handler.send_header("Content-Length", str(len(data))) - handler.send_header("Cache-Control", cache_control) # 添加 ETag 支持(简单实现:基于文件大小和修改时间) try: stat = os.stat(full) etag = f'"{stat.st_size}-{int(stat.st_mtime)}"' - handler.send_header("ETag", etag) # 检查 If-None-Match 头,支持 304 Not Modified if_none_match = handler.headers.get("If-None-Match", "") if if_none_match == etag: handler.send_response(HTTPStatus.NOT_MODIFIED) + handler.send_header("ETag", etag) + handler.send_header("Cache-Control", cache_control) handler.end_headers() return except Exception: - pass + etag = None + handler.send_response(HTTPStatus.OK) + handler.send_header("Content-Type", ctype) + handler.send_header("Content-Length", str(len(data))) + handler.send_header("Cache-Control", cache_control) + if etag: + handler.send_header("ETag", etag) handler.end_headers() handler.wfile.write(data) except FileNotFoundError: diff --git a/gui/webgui_launcher.py b/gui/webgui_launcher.py index 0660c5a..e04c1bc 100644 --- a/gui/webgui_launcher.py +++ b/gui/webgui_launcher.py @@ -14,6 +14,13 @@ import webbrowser from pathlib import Path import tkinter as tk from tkinter import ttk, scrolledtext, messagebox +from douyin.core import path_config +from gui.web_gui_pkg.net_config import ( + DEFAULT_WEB_GUI_HOST, + DEFAULT_WEB_GUI_PORT, + get_web_gui_host, + get_web_gui_port, +) # 获取脚本所在目录和项目根目录 BASE_DIR = Path(__file__).parent.absolute() @@ -21,8 +28,9 @@ PROJECT_ROOT = BASE_DIR.parent LOG_FILE = BASE_DIR / "webgui_startup.log" WEB_GUI_PY = BASE_DIR / "web_gui.py" -# 默认端口 -DEFAULT_PORT = 8000 +# 默认端口与地址:与 web_gui.py 保持同源,避免迁移时配置漂移 +DEFAULT_PORT = DEFAULT_WEB_GUI_PORT +DEFAULT_HOST = get_web_gui_host() or DEFAULT_WEB_GUI_HOST class WebGUILauncher: @@ -36,7 +44,7 @@ class WebGUILauncher: self.webgui_process = None self.monitor_thread = None self.is_running = False - self.port = DEFAULT_PORT + self.port = get_web_gui_port() or DEFAULT_PORT # 创建UI self.create_ui() @@ -149,7 +157,7 @@ class WebGUILauncher: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) - result = sock.connect_ex(("127.0.0.1", self.port)) + result = sock.connect_ex((DEFAULT_HOST, self.port)) sock.close() if result == 0: @@ -197,7 +205,7 @@ class WebGUILauncher: try: # 检查是否有虚拟环境 - venv_python = PROJECT_ROOT / ".venv" / "Scripts" / "python.exe" + venv_python = Path(path_config.get_venv_python_path()) if venv_python.exists(): python_exe = str(venv_python) self.log("使用虚拟环境启动...") @@ -323,7 +331,7 @@ class WebGUILauncher: def open_browser(self): """打开浏览器""" - url = f"http://127.0.0.1:{self.port}" + url = f"http://{DEFAULT_HOST}:{self.port}" self.log(f"打开浏览器: {url}") try: webbrowser.open(url) diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index 8814228..36a30ec 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -40,7 +40,7 @@ def _ops_log(msg: str, level: str = "INFO") -> None: _LOGGER.info(str(msg)) except Exception: try: - _ops_log(str(msg)) + print(str(msg)) except Exception: pass @@ -266,6 +266,8 @@ class ScreenshotOperations: try: # 测量设备端生成与传输两部分耗时,分别记录 t_shell_start = time.time() + from douyin.core import path_config + remote_shot = path_config.get_android_screenshot_path() subprocess.run( [ adb, @@ -274,7 +276,7 @@ class ScreenshotOperations: "shell", "screencap", "-p", - "/sdcard/DCIM/screenshot.png", + remote_shot, ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, @@ -284,7 +286,7 @@ class ScreenshotOperations: t_shell_end = time.time() t_pull_start = time.time() subprocess.run( - [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file], + [adb, "-s", device_id, "pull", remote_shot, tmp_file], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, diff --git a/tests/test_countdown_candidate_selection.py b/tests/test_countdown_candidate_selection.py index 8fb4e04..4a68d5f 100644 --- a/tests/test_countdown_candidate_selection.py +++ b/tests/test_countdown_candidate_selection.py @@ -170,6 +170,18 @@ def test_parse_mmss_from_full_text_extracts_valid_pair(): assert ss == "53" +def test_parse_mmss_from_full_text_extracts_compact_4digits_pair(): + mm, ss = _parse_mmss_from_full_text("1340后开奖") + assert mm == "13" + assert ss == "40" + + +def test_parse_mmss_from_full_text_extracts_compact_3digits_pair(): + mm, ss = _parse_mmss_from_full_text("940后开奖") + assert mm == "09" + assert ss == "40" + + def test_parse_mmss_from_full_text_ignores_non_countdown_text(): mm, ss = _parse_mmss_from_full_text("直播间,否则会失去抽奖机会") assert mm == "" diff --git a/tests/test_douyin_fudai_contain_imports.py b/tests/test_douyin_fudai_contain_imports.py new file mode 100644 index 0000000..f1e5e3a --- /dev/null +++ b/tests/test_douyin_fudai_contain_imports.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +import douyin.fudai.douyin_fudai_contain_impl as contain_impl + + +def test_contain_impl_exposes_ocr_executor_symbol(): + assert hasattr(contain_impl, "_get_fudai_ocr_executor") + assert callable(contain_impl._get_fudai_ocr_executor) + diff --git a/tests/test_join_decision_invalid_countdown.py b/tests/test_join_decision_invalid_countdown.py new file mode 100644 index 0000000..c5cd7cf --- /dev/null +++ b/tests/test_join_decision_invalid_countdown.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import time +from unittest.mock import MagicMock, patch + +from douyin.fudai.core.fudai_filter_pkg.join_decision import basic_join_decision + + +def _mk_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a._run_id = "test-run" + a.needswitch = True + a.high_value_fudai_enabled = True + a.high_value_fudai_threshold_yuan = 500.0 + a.high_value_fudai_join_ahead_seconds = 100 + a.operation = MagicMock() + a.device_id = "MOCK" + a.click = MagicMock() + a._fudai_button_status = "可以参与" + return a + + +def test_invalid_countdown_should_not_attend(): + analyser = _mk_analyser() + # 模拟 OCR 异常后兜底:cd_end == now + 60,但被强制设为过期时间来模拟无效倒计时 + detail = ("", "未识别", 0, 0, 999.0, (time.time(), time.time() - 1, None)) + + with patch( + "douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config", + return_value=(False, "ok"), + ), patch( + "douyin.fudai.core.fudai_attend.attend_choujiang", + return_value=True, + ) as mock_attend: + ok = basic_join_decision(analyser, detail) + + assert ok is False + mock_attend.assert_not_called() + + +def test_invalid_countdown_text_should_not_attend(): + analyser = _mk_analyser() + detail = ("", "60:37", 0, 0, 999.0, (time.time(), time.time() + 180, None)) + + with patch( + "douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config", + return_value=(False, "ok"), + ), patch( + "douyin.fudai.core.fudai_attend.attend_choujiang", + return_value=True, + ) as mock_attend: + ok = basic_join_decision(analyser, detail) + + assert ok is False + mock_attend.assert_not_called() + + +def test_button_activity_ended_should_take_priority_over_invalid_countdown(): + analyser = _mk_analyser() + analyser.button_text_raw = "活动已结束" + analyser.swipe_up_to_next_live = MagicMock() + # 倒计时文本非法,但按钮已经明确是“活动已结束” + detail = ("", "未识别", 0, 0, 999.0, (time.time(), time.time() - 1, None)) + + with patch( + "douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config", + return_value=(False, "ok"), + ), patch( + "douyin.fudai.core.fudai_attend.attend_choujiang", + return_value=True, + ) as mock_attend: + ok = basic_join_decision(analyser, detail) + + assert ok is False + mock_attend.assert_not_called() + analyser.swipe_up_to_next_live.assert_called_once() diff --git a/tests/test_join_decision_reservation.py b/tests/test_join_decision_reservation.py new file mode 100644 index 0000000..b3a84f7 --- /dev/null +++ b/tests/test_join_decision_reservation.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import time +from unittest.mock import MagicMock, patch + +from douyin.fudai.core.fudai_filter_pkg.join_decision import basic_join_decision + + +def _mk_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a._run_id = "test-run" + a.needswitch = True + a.high_value_fudai_enabled = True + a.high_value_fudai_threshold_yuan = 500.0 + a.high_value_fudai_join_ahead_seconds = 100 + a.high_value_fudai_max_reservations = 3 + a.switch_room_wait_after_stage_diag_seconds = 1.5 + a.wait_minutes = 5 + a.room_pos = 0 + a.last_fudai_x = 0 + a.current_room_title = "测试直播间" + a.current_room_title_raw = "测试直播间" + a._fudai_detail_task_count_from_stage = 1 + a.reservations = [] + a.operation = MagicMock() + a.device_id = "MOCK" + a.click = MagicMock() + a.swipe_up_to_next_live = MagicMock() + return a + + +def test_high_value_countdown_gt_records_reservation_and_returns_true(): + analyser = _mk_analyser() + future_ts = time.time() + 300 # > join_ahead_seconds + detail = ("高价值福袋", "05:00", 10, 1, 1999.0, (time.time(), future_ts, 300)) + + with patch( + "douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config", + return_value=(True, "countdown_gt_118"), + ), patch( + "douyin.reservation.reservation_logic.record.record_high_value_reservation", + return_value=False, + ) as mock_record: + ok = basic_join_decision(analyser, detail) + + assert ok is True + mock_record.assert_called_once() + # 记录预约后应立即切换直播间(needswitch=True) + analyser.swipe_up_to_next_live.assert_called_once() + + +def test_high_value_countdown_within_join_window_attends(): + analyser = _mk_analyser() + future_ts = time.time() + 30 # <= join_ahead_seconds + detail = ("高价值福袋", "00:30", 10, 1, 1999.0, (time.time(), future_ts, 30)) + + with patch( + "douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config", + return_value=(True, "countdown_gt_118"), + ), patch( + "douyin.fudai.core.fudai_attend.attend_choujiang", + return_value=True, + ) as mock_attend: + ok = basic_join_decision(analyser, detail) + + assert ok is True + mock_attend.assert_called_once() + + +def test_single_room_mode_bypasses_reservation_path(): + analyser = _mk_analyser() + analyser.needswitch = False + future_ts = time.time() + 300 + detail = ("高价值福袋", "05:00", 10, 1, 1999.0, (time.time(), future_ts, 300)) + + with patch( + "douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config", + return_value=(True, "countdown_gt_118"), + ), patch( + "douyin.reservation.reservation_logic.record.record_high_value_reservation", + return_value=False, + ) as mock_record: + ok = basic_join_decision(analyser, detail) + + # 单间模式走“直接参与”路径,不会进入“高价值预约记录”分支 + assert ok is False + mock_record.assert_not_called() + analyser.swipe_up_to_next_live.assert_not_called() diff --git a/tests/test_read_with_retries_countdown_guard.py b/tests/test_read_with_retries_countdown_guard.py new file mode 100644 index 0000000..add4b1e --- /dev/null +++ b/tests/test_read_with_retries_countdown_guard.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import time +from unittest.mock import MagicMock, patch + +from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import ( + read_fudai_detail_with_retries, +) + + +def _mk_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a.operation = MagicMock() + a.operation.delay = MagicMock() + a.fudai_detail_max_attempts = 2 + a.fudai_detail_retry_delay_seconds = 0.2 + a.fudai_detail_initial_wait_seconds = 0.3 + a.fudai_detail_verified_wait_seconds = 0.2 + a._fudai_detail_verified = False + a.current_room_title = "房间A" + a.current_room_title_raw = "房间A" + return a + + +def test_invalid_countdown_text_should_not_short_circuit_first_attempt(): + analyser = _mk_analyser() + now = time.time() + first_tuple = ("", "60:37", 0, 0, 1599.0, (now, now + 3600, 3637)) + second_tuple = ("", "00:54", 0, 0, 1599.0, (now, now + 54, 54)) + + call_seq = [ + ("ok", first_tuple, {}), + ("ok", second_tuple, {}), + ] + + with patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.read_fudai_detail_once", + side_effect=call_seq, + ) as mock_read_once, patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.validate_fudai_detail", + return_value=(True, "ok"), + ): + result = read_fudai_detail_with_retries( + analyser=analyser, + fudai_x=0, + read_once_callback=None, + close_detail_callback=None, + ensure_open_callback=None, + ) + + assert mock_read_once.call_count == 2 + + +def test_invalid_countdown_text_is_rejected_by_filter_layer(): + from douyin.fudai.core.fudai_filter_pkg.should_skip import should_skip_fudai_by_config + + analyser = _mk_analyser() + detail = ("", "60:37", 0, 0, 1599.0, (time.time(), time.time() + 3600, 3637)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is True + assert reason == "countdown_invalid" diff --git a/tests/test_run_params_builder.py b/tests/test_run_params_builder.py new file mode 100644 index 0000000..e9dc093 --- /dev/null +++ b/tests/test_run_params_builder.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +from gui.components.run_params_builder import get_params + + +class _Var: + def __init__(self, value): + self._value = value + + def get(self): + return self._value + + +def _build_vars(overrides=None): + base = { + "infinite_loop_var": _Var(False), + "wait_minutes_var": _Var(5), + "device_var": _Var("192.168.10.107:39051"), + "y_var": _Var(0), + "needswitch_var": _Var(True), + "skip_gt_seconds_var": _Var(900), + "reset_after_swipes_enabled_var": _Var(True), + "reset_after_swipes_var": _Var(20), + "min_value_var": _Var(0), + "min_participants_var": _Var(0), + "max_participants_var": _Var(0), + "auto_join_var": _Var(True), + "fansclub_action_var": _Var("switch"), + "high_value_room_revisit_enabled_var": _Var(False), + "high_value_room_revisit_only_current_run_var": _Var(False), + "high_value_room_revisit_min_interval_seconds_var": _Var(300), + "high_value_room_revisit_max_per_run_var": _Var(9999), + "high_value_room_revisit_min_prize_value_var": _Var(1000.0), + "high_value_room_revisit_max_age_days_var": _Var(1), + "high_value_fudai_poll_before_seconds_var": _Var(10.0), + "reservation_back_verify_enabled_var": _Var(False), + "reservation_back_swipe_delay_var": _Var(1.0), + "fudai_find_max_attempts_var": _Var(3), + "enable_ocr_mode1_var": _Var(False), + "fudai_template_match_enabled_var": _Var(False), + "fudai_template_match_threshold_var": _Var(0.7), + "yg_only_var": _Var(False), + "yg_recommend_duration_var": _Var(0), + "enable_back_on_misses_var": _Var(False), + } + if overrides: + base.update(overrides) + return base + + +def test_get_params_uses_reservation_back_swipe_delay_and_yanghao_only_vars(): + vars_ = _build_vars( + { + "reservation_back_swipe_delay_var": _Var(0.6), + "yg_only_var": _Var(True), + "yg_recommend_duration_var": _Var(120), + } + ) + params = get_params(vars_) + assert params.reservation_back_swipe_delay == 0.6 + assert params.yanghao_only is True + assert params.yanghao_seconds == 120 + + +def test_get_params_infinite_loop_sets_wait_minutes_zero(): + vars_ = _build_vars({"infinite_loop_var": _Var(True), "wait_minutes_var": _Var(15)}) + params = get_params(vars_) + assert params.wait_minutes == 0 + diff --git a/tests/test_should_skip_countdown_invalid.py b/tests/test_should_skip_countdown_invalid.py new file mode 100644 index 0000000..2fb25eb --- /dev/null +++ b/tests/test_should_skip_countdown_invalid.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import time +from unittest.mock import MagicMock + +from douyin.fudai.core.fudai_filter_pkg.should_skip import should_skip_fudai_by_config + + +def _mk_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a.needswitch = True + a.min_prize_value_yuan = 0.0 + a.min_participants = 0 + a.max_participants = 0 + a.skip_if_countdown_gt_seconds = 118 + a.skip_if_countdown_lt_seconds = 5 + a.button_text_raw = "参与抽奖" + return a + + +def test_should_skip_when_countdown_text_invalid_format(): + analyser = _mk_analyser() + detail = ("福袋", "60:37", 10, 1, 999.0, (time.time(), time.time() + 120)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is True + assert reason == "countdown_invalid" + + +def test_button_unable_should_be_primary_reason_even_with_countdown_gt(): + analyser = _mk_analyser() + analyser.button_text_raw = "活动已结束" + detail = ("福袋", "05:49", 10, 1, 999.0, (time.time(), time.time() + 349)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is True + assert reason == "button_unable_to_participate" diff --git a/tests/test_should_skip_countdown_missing.py b/tests/test_should_skip_countdown_missing.py new file mode 100644 index 0000000..770d20b --- /dev/null +++ b/tests/test_should_skip_countdown_missing.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import time +from unittest.mock import MagicMock + +from douyin.fudai.core.fudai_filter_pkg.should_skip import should_skip_fudai_by_config + + +def _mk_analyser(): + a = MagicMock() + a._log_kv = MagicMock() + a.needswitch = True + a.min_prize_value_yuan = 0.0 + a.min_participants = 0 + a.max_participants = 0 + a.skip_if_countdown_gt_seconds = 118 + a.skip_if_countdown_lt_seconds = 5 + a.button_text_raw = "参与抽奖" + return a + + +def test_should_skip_when_countdown_text_missing(): + analyser = _mk_analyser() + # 倒计时 tuple 存在,但 time_text 为空时应直接跳过,避免默认兜底秒数触发参与 + detail = ("福袋", "", 10, 1, 999.0, (time.time(), time.time() + 120)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is True + assert reason == "countdown_missing" diff --git a/tools/coords/region_selector.py b/tools/coords/region_selector.py index 92ece93..0a36fe0 100644 --- a/tools/coords/region_selector.py +++ b/tools/coords/region_selector.py @@ -16,6 +16,11 @@ from typing import Optional, Any import json from PIL import Image, ImageTk +from tools.coords.region_selector_ui import ( + bind_canvas_events, + setup_dnd, + setup_menu, +) try: import tkinter as tk @@ -96,51 +101,7 @@ class RegionSelector: def _create_menu(self): """创建菜单栏""" - menubar = tk.Menu(self.root) - file_menu = tk.Menu(menubar, tearoff=0) - file_menu.add_command(label="打开...", command=self.open_dialog, accelerator="Ctrl+O") - file_menu.add_command(label="上一张", command=self.prev_image, accelerator="← / PageUp") - file_menu.add_command(label="下一张", command=self.next_image, accelerator="→ / PageDown") - file_menu.add_separator() - file_menu.add_command(label="保存区域数据", command=self.save_regions, accelerator="Ctrl+S") - file_menu.add_command(label="加载区域数据", command=self.load_regions, accelerator="Ctrl+L") - file_menu.add_separator() - file_menu.add_command(label="退出", command=self.root.destroy) - menubar.add_cascade(label="文件", menu=file_menu) - - view_menu = tk.Menu(menubar, tearoff=0) - view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上") - view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下") - view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0") - view_menu.add_command(label="适应窗口", command=self.fit_to_window, accelerator="Ctrl+F") - menubar.add_cascade(label="视图", menu=view_menu) - - region_menu = tk.Menu(menubar, tearoff=0) - region_menu.add_command(label="清除选择", command=self.clear_selection, accelerator="Delete") - region_menu.add_command(label="分析区域", command=self.analyze_region, accelerator="Enter") - region_menu.add_separator() - region_menu.add_command(label="显示所有区域", command=self.show_all_regions, accelerator="Ctrl+A") - region_menu.add_command(label="清除所有区域", command=self.clear_all_regions) - menubar.add_cascade(label="区域", menu=region_menu) - - self.root.config(menu=menubar) - - # 绑定快捷键 - self.root.bind_all("", lambda e: self.open_dialog()) - self.root.bind("", lambda e: self.prev_image()) - self.root.bind("", lambda e: self.next_image()) - self.root.bind("", lambda e: self.prev_image()) # PageUp - self.root.bind("", lambda e: self.next_image()) # PageDown - self.root.bind("", lambda e: self.zoom_in()) - self.root.bind("", lambda e: self.zoom_in()) # 无Shift的+键 - self.root.bind("", lambda e: self.zoom_out()) - self.root.bind("", lambda e: self.reset_zoom()) - self.root.bind("", lambda e: self.fit_to_window()) - self.root.bind("", lambda e: self.clear_selection()) - self.root.bind("", lambda e: self.analyze_region()) - self.root.bind("", lambda e: self.save_regions()) - self.root.bind("", lambda e: self.load_regions()) - self.root.bind("", lambda e: self.show_all_regions()) + setup_menu(self, tk) def _create_ui(self): """创建用户界面""" @@ -174,35 +135,8 @@ class RegionSelector: status_label = tk.Label(right_panel, textvariable=self.status, anchor="w", bg='#e0e0e0') status_label.pack(fill=tk.X, side=tk.BOTTOM) - # 绑定事件 - self.canvas.bind("", self.on_move) - self.canvas.bind("", self.on_left_click) - self.canvas.bind("", self.on_left_drag) - self.canvas.bind("", self.on_left_release) - self.canvas.bind("", self.on_right_click) # 右键开始拖拽 - self.canvas.bind("", self.on_right_drag) # 右键拖拽 - self.canvas.bind("", self.on_right_release) - self.canvas.bind("", self.on_mousewheel) # Windows/Linux - self.canvas.bind("", self.on_mousewheel) # Linux - self.canvas.bind("", self.on_mousewheel) # Linux - self.canvas.bind("", self.on_mousewheel_ctrl) # Ctrl+滚轮 - - # 添加拖放支持 - if HAS_DND: - try: - drop_target_register = getattr(self.root, 'drop_target_register', None) - dnd_bind = getattr(self.root, 'dnd_bind', None) - if drop_target_register and dnd_bind: - drop_target_register(DND_FILES) - dnd_bind('<>', self.on_drop) - - drop_target_register = getattr(self.canvas, 'drop_target_register', None) - dnd_bind = getattr(self.canvas, 'dnd_bind', None) - if drop_target_register and dnd_bind: - drop_target_register(DND_FILES) - dnd_bind('<>', self.on_drop) - except Exception: - pass # 忽略拖放设置失败 + bind_canvas_events(self) + setup_dnd(self, HAS_DND, DND_FILES) def _create_control_panel(self, parent): """创建控制面板""" diff --git a/tools/coords/region_selector_ui.py b/tools/coords/region_selector_ui.py new file mode 100644 index 0000000..0c8e6ac --- /dev/null +++ b/tools/coords/region_selector_ui.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""region_selector UI 绑定辅助函数。""" + +from __future__ import annotations + +from typing import Any + + +def setup_menu(selector, tk) -> None: + """创建菜单栏与快捷键绑定。""" + menubar = tk.Menu(selector.root) + file_menu = tk.Menu(menubar, tearoff=0) + file_menu.add_command(label="打开...", command=selector.open_dialog, accelerator="Ctrl+O") + file_menu.add_command(label="上一张", command=selector.prev_image, accelerator="← / PageUp") + file_menu.add_command(label="下一张", command=selector.next_image, accelerator="→ / PageDown") + file_menu.add_separator() + file_menu.add_command(label="保存区域数据", command=selector.save_regions, accelerator="Ctrl+S") + file_menu.add_command(label="加载区域数据", command=selector.load_regions, accelerator="Ctrl+L") + file_menu.add_separator() + file_menu.add_command(label="退出", command=selector.root.destroy) + menubar.add_cascade(label="文件", menu=file_menu) + + view_menu = tk.Menu(menubar, tearoff=0) + view_menu.add_command(label="放大 (+)", command=selector.zoom_in, accelerator="+ / Ctrl+滚轮上") + view_menu.add_command(label="缩小 (-)", command=selector.zoom_out, accelerator="- / Ctrl+滚轮下") + view_menu.add_command(label="重置缩放 (1:1)", command=selector.reset_zoom, accelerator="Ctrl+0") + view_menu.add_command(label="适应窗口", command=selector.fit_to_window, accelerator="Ctrl+F") + menubar.add_cascade(label="视图", menu=view_menu) + + region_menu = tk.Menu(menubar, tearoff=0) + region_menu.add_command(label="清除选择", command=selector.clear_selection, accelerator="Delete") + region_menu.add_command(label="分析区域", command=selector.analyze_region, accelerator="Enter") + region_menu.add_separator() + region_menu.add_command(label="显示所有区域", command=selector.show_all_regions, accelerator="Ctrl+A") + region_menu.add_command(label="清除所有区域", command=selector.clear_all_regions) + menubar.add_cascade(label="区域", menu=region_menu) + + selector.root.config(menu=menubar) + + selector.root.bind_all("", lambda e: selector.open_dialog()) + selector.root.bind("", lambda e: selector.prev_image()) + selector.root.bind("", lambda e: selector.next_image()) + selector.root.bind("", lambda e: selector.prev_image()) + selector.root.bind("", lambda e: selector.next_image()) + selector.root.bind("", lambda e: selector.zoom_in()) + selector.root.bind("", lambda e: selector.zoom_in()) + selector.root.bind("", lambda e: selector.zoom_out()) + selector.root.bind("", lambda e: selector.reset_zoom()) + selector.root.bind("", lambda e: selector.fit_to_window()) + selector.root.bind("", lambda e: selector.clear_selection()) + selector.root.bind("", lambda e: selector.analyze_region()) + selector.root.bind("", lambda e: selector.save_regions()) + selector.root.bind("", lambda e: selector.load_regions()) + selector.root.bind("", lambda e: selector.show_all_regions()) + + +def bind_canvas_events(selector) -> None: + """绑定画布事件。""" + selector.canvas.bind("", selector.on_move) + selector.canvas.bind("", selector.on_left_click) + selector.canvas.bind("", selector.on_left_drag) + selector.canvas.bind("", selector.on_left_release) + selector.canvas.bind("", selector.on_right_click) + selector.canvas.bind("", selector.on_right_drag) + selector.canvas.bind("", selector.on_right_release) + selector.canvas.bind("", selector.on_mousewheel) + selector.canvas.bind("", selector.on_mousewheel) + selector.canvas.bind("", selector.on_mousewheel) + selector.canvas.bind("", selector.on_mousewheel_ctrl) + + +def setup_dnd(selector, has_dnd: bool, dnd_files: Any) -> None: + """按能力注册拖放。""" + if not has_dnd: + return + try: + drop_target_register = getattr(selector.root, "drop_target_register", None) + dnd_bind = getattr(selector.root, "dnd_bind", None) + if drop_target_register and dnd_bind: + drop_target_register(dnd_files) + dnd_bind("<>", selector.on_drop) + + drop_target_register = getattr(selector.canvas, "drop_target_register", None) + dnd_bind = getattr(selector.canvas, "dnd_bind", None) + if drop_target_register and dnd_bind: + drop_target_register(dnd_files) + dnd_bind("<>", selector.on_drop) + except Exception: + pass diff --git a/tools/coords/simple_region_selector.py b/tools/coords/simple_region_selector.py index 591ca93..1cfc976 100644 --- a/tools/coords/simple_region_selector.py +++ b/tools/coords/simple_region_selector.py @@ -20,6 +20,10 @@ except ImportError: from PIL import Image, ImageTk, ImageDraw import numpy as np +from tools.coords.simple_region_selector_ui import ( + bind_canvas_events, + setup_menu_and_shortcuts, +) class SimpleRegionSelector: @@ -61,47 +65,7 @@ class SimpleRegionSelector: self.root.title("抖音区域选择器 - 白色像素统计") self.root.geometry("1000x700") - # 菜单栏 - menubar = tk.Menu(self.root) - file_menu = tk.Menu(menubar, tearoff=0) - file_menu.add_command(label="打开图片", command=self.ask_for_image, accelerator="Ctrl+O") - file_menu.add_command(label="保存区域", command=self.save_regions, accelerator="Ctrl+S") - file_menu.add_command(label="加载区域", command=self.load_regions, accelerator="Ctrl+L") - file_menu.add_separator() - file_menu.add_command(label="退出", command=self.root.quit) - menubar.add_cascade(label="文件", menu=file_menu) - - edit_menu = tk.Menu(menubar, tearoff=0) - edit_menu.add_command(label="清除选择", command=self.clear_selection, accelerator="Del") - edit_menu.add_command(label="分析区域", command=self.analyze_region, accelerator="Enter") - edit_menu.add_command(label="显示所有", command=self.show_all_regions) - edit_menu.add_command(label="清除所有", command=self.clear_all_regions) - menubar.add_cascade(label="编辑", menu=edit_menu) - - # 移除视图菜单,不需要放大缩小功能 - - # 视图菜单 - view_menu = tk.Menu(menubar, tearoff=0) - view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+") - view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="-") - view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0") - view_menu.add_command(label="适应窗口", command=self.fit_to_window, accelerator="Ctrl+F") - menubar.add_cascade(label="视图", menu=view_menu) - - self.root.config(menu=menubar) - - # 绑定快捷键 - self.root.bind("", lambda e: self.ask_for_image()) - self.root.bind("", lambda e: self.save_regions()) - self.root.bind("", lambda e: self.load_regions()) - self.root.bind("", lambda e: self.clear_selection()) - self.root.bind("", lambda e: self.analyze_region()) - # 视图相关快捷键 - self.root.bind("", lambda e: self.zoom_in()) - self.root.bind("", lambda e: self.zoom_in()) - self.root.bind("", lambda e: self.zoom_out()) - self.root.bind("", lambda e: self.reset_zoom()) - self.root.bind("", lambda e: self.fit_to_window()) + setup_menu_and_shortcuts(self, tk) # 主框架 main_frame = tk.Frame(self.root) @@ -129,13 +93,7 @@ class SimpleRegionSelector: anchor="w", bg='#e0e0e0', relief=tk.SUNKEN) status_bar.pack(fill=tk.X, side=tk.BOTTOM) - # 绑定画布事件 - self.canvas.bind("", self.on_canvas_click) # 左键添加点 - self.canvas.bind("", self.on_canvas_right_click) # 右键完成多边形 - self.canvas.bind("", self.on_canvas_drag) # 右键拖拽 - self.canvas.bind("", self.on_mousewheel) # 滚轮缩放 - self.root.bind("", self.finish_polygon) # 空格键完成多边形 - self.root.bind("", self.remove_last_point) # 退格键删除最后一个点 + bind_canvas_events(self) def setup_control_panel(self, parent): """设置控制面板""" diff --git a/tools/coords/simple_region_selector_ui.py b/tools/coords/simple_region_selector_ui.py new file mode 100644 index 0000000..bbe0bff --- /dev/null +++ b/tools/coords/simple_region_selector_ui.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""simple_region_selector UI 绑定辅助函数。""" + +from __future__ import annotations + + +def setup_menu_and_shortcuts(selector, tk) -> None: + menubar = tk.Menu(selector.root) + file_menu = tk.Menu(menubar, tearoff=0) + file_menu.add_command(label="打开图片", command=selector.ask_for_image, accelerator="Ctrl+O") + file_menu.add_command(label="保存区域", command=selector.save_regions, accelerator="Ctrl+S") + file_menu.add_command(label="加载区域", command=selector.load_regions, accelerator="Ctrl+L") + file_menu.add_separator() + file_menu.add_command(label="退出", command=selector.root.quit) + menubar.add_cascade(label="文件", menu=file_menu) + + edit_menu = tk.Menu(menubar, tearoff=0) + edit_menu.add_command(label="清除选择", command=selector.clear_selection, accelerator="Del") + edit_menu.add_command(label="分析区域", command=selector.analyze_region, accelerator="Enter") + edit_menu.add_command(label="显示所有", command=selector.show_all_regions) + edit_menu.add_command(label="清除所有", command=selector.clear_all_regions) + menubar.add_cascade(label="编辑", menu=edit_menu) + + view_menu = tk.Menu(menubar, tearoff=0) + view_menu.add_command(label="放大 (+)", command=selector.zoom_in, accelerator="+") + view_menu.add_command(label="缩小 (-)", command=selector.zoom_out, accelerator="-") + view_menu.add_command(label="重置缩放 (1:1)", command=selector.reset_zoom, accelerator="Ctrl+0") + view_menu.add_command(label="适应窗口", command=selector.fit_to_window, accelerator="Ctrl+F") + menubar.add_cascade(label="视图", menu=view_menu) + + selector.root.config(menu=menubar) + + selector.root.bind("", lambda e: selector.ask_for_image()) + selector.root.bind("", lambda e: selector.save_regions()) + selector.root.bind("", lambda e: selector.load_regions()) + selector.root.bind("", lambda e: selector.clear_selection()) + selector.root.bind("", lambda e: selector.analyze_region()) + selector.root.bind("", lambda e: selector.zoom_in()) + selector.root.bind("", lambda e: selector.zoom_in()) + selector.root.bind("", lambda e: selector.zoom_out()) + selector.root.bind("", lambda e: selector.reset_zoom()) + selector.root.bind("", lambda e: selector.fit_to_window()) + selector.root.bind("", selector.finish_polygon) + selector.root.bind("", selector.remove_last_point) + + +def bind_canvas_events(selector) -> None: + selector.canvas.bind("", selector.on_canvas_click) + selector.canvas.bind("", selector.on_canvas_right_click) + selector.canvas.bind("", selector.on_canvas_drag) + selector.canvas.bind("", selector.on_mousewheel) diff --git a/tools/dev/web_gui_config_manifest.json b/tools/dev/web_gui_config_manifest.json index b2b828c..c09fb55 100644 --- a/tools/dev/web_gui_config_manifest.json +++ b/tools/dev/web_gui_config_manifest.json @@ -6,12 +6,6 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", - "debug_captures.async_save", - "debug_captures.auto_cleanup", - "debug_captures.enabled", - "debug_captures.keep_days", - "debug_captures.log_on_complete", - "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -49,22 +43,6 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", - "logging.action_log_format", - "logging.beautify_output", - "logging.color_output", - "logging.compress_after_days", - "logging.compress_logs", - "logging.debug_detail_level", - "logging.enable_monitor", - "logging.error_detail_level", - "logging.keep_days", - "logging.log_format_mode", - "logging.max_total_size_gb", - "logging.monitor_critical_mb", - "logging.monitor_warning_mb", - "logging.performance_tracking.enabled", - "logging.performance_tracking.track_function_calls", - "logging.show_timestamps", "logging.stage_diag_verbose", "lucky_draw_red_ratio_threshold", "max_participants", @@ -140,12 +118,6 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", - "debug_captures.async_save", - "debug_captures.auto_cleanup", - "debug_captures.enabled", - "debug_captures.keep_days", - "debug_captures.log_on_complete", - "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -183,26 +155,7 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", - "log_unified_enabled", - "log_unified_path", - "logging.action_log_format", - "logging.beautify_output", - "logging.color_output", - "logging.compress_after_days", - "logging.compress_logs", - "logging.debug_detail_level", - "logging.enable_monitor", - "logging.error_detail_level", - "logging.keep_days", - "logging.log_format_mode", - "logging.max_total_size_gb", - "logging.monitor_critical_mb", - "logging.monitor_warning_mb", - "logging.performance_tracking.enabled", - "logging.performance_tracking.track_function_calls", - "logging.show_timestamps", "logging.stage_diag_verbose", - "logging.use_dated_logs", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", @@ -270,12 +223,6 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", - "debug_captures.async_save", - "debug_captures.auto_cleanup", - "debug_captures.enabled", - "debug_captures.keep_days", - "debug_captures.log_on_complete", - "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -315,26 +262,7 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", - "log_unified_enabled", - "log_unified_path", - "logging.action_log_format", - "logging.beautify_output", - "logging.color_output", - "logging.compress_after_days", - "logging.compress_logs", - "logging.debug_detail_level", - "logging.enable_monitor", - "logging.error_detail_level", - "logging.keep_days", - "logging.log_format_mode", - "logging.max_total_size_gb", - "logging.monitor_critical_mb", - "logging.monitor_warning_mb", - "logging.performance_tracking.enabled", - "logging.performance_tracking.track_function_calls", - "logging.show_timestamps", "logging.stage_diag_verbose", - "logging.use_dated_logs", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", @@ -402,12 +330,6 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", - "debug_captures.async_save", - "debug_captures.auto_cleanup", - "debug_captures.enabled", - "debug_captures.keep_days", - "debug_captures.log_on_complete", - "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -429,8 +351,6 @@ "fudai_quiet_start_hour", "fudai_template_match_enabled", "fudai_template_match_threshold", - "gui.realtime_status.refresh_interval_ms", - "gui.realtime_status.tail_items", "gui.theme", "high_value_fudai_after_action", "high_value_fudai_enabled", @@ -447,26 +367,7 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", - "log_unified_enabled", - "log_unified_path", - "logging.action_log_format", - "logging.beautify_output", - "logging.color_output", - "logging.compress_after_days", - "logging.compress_logs", - "logging.debug_detail_level", - "logging.enable_monitor", - "logging.error_detail_level", - "logging.keep_days", - "logging.log_format_mode", - "logging.max_total_size_gb", - "logging.monitor_critical_mb", - "logging.monitor_warning_mb", - "logging.performance_tracking.enabled", - "logging.performance_tracking.track_function_calls", - "logging.show_timestamps", "logging.stage_diag_verbose", - "logging.use_dated_logs", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", diff --git a/webui/app.js b/webui/app.js index 6c04ce7..a16d92a 100644 --- a/webui/app.js +++ b/webui/app.js @@ -159,3 +159,15 @@ window.addEventListener("DOMContentLoaded", async () => { pollReservations(); pollHighValueRooms(); }); + +window.addEventListener("beforeunload", () => { + try { if (pollTimer) clearInterval(pollTimer); } catch (e) {} + try { if (statsTimer) clearInterval(statsTimer); } catch (e) {} + try { if (shotTimer) clearInterval(shotTimer); } catch (e) {} + try { + if (window.__reservationTickTimer) { + clearInterval(window.__reservationTickTimer); + window.__reservationTickTimer = null; + } + } catch (e) {} +}); diff --git a/webui/js/api_client.js b/webui/js/api_client.js index 6adf24e..53928c6 100644 --- a/webui/js/api_client.js +++ b/webui/js/api_client.js @@ -75,10 +75,25 @@ async function apiPost(path, body) { }, body: JSON.stringify(body || {}), }); - const data = await res.json(); + let data = null; + const ct = (res.headers.get("content-type") || "").toLowerCase(); + if (ct.includes("application/json")) { + try { + data = await res.json(); + } catch (e) { + data = null; + } + } else { + try { + const text = await res.text(); + data = text ? { error: text } : {}; + } catch (e) { + data = {}; + } + } if (!res.ok) { notifyApiFail(); - const errorMsg = data.error || data.message || res.statusText; + const errorMsg = (data && (data.error || data.message)) || res.statusText; const error = new Error(errorMsg); error.status = res.status; error.data = data; diff --git a/webui/js/ui_init.js b/webui/js/ui_init.js index 139bac6..2898b2b 100644 --- a/webui/js/ui_init.js +++ b/webui/js/ui_init.js @@ -463,8 +463,12 @@ function updateTabBadge(target, count) { } function startReservationsCountdownTick() { + if (window.__reservationTickTimer) { + clearInterval(window.__reservationTickTimer); + window.__reservationTickTimer = null; + } // 每秒 tick 更新预约卡倒计时与高亮类,无需等待 stats 轮询 - setInterval(() => { + window.__reservationTickTimer = setInterval(() => { const items = document.querySelectorAll(".reservationItem[data-future-ts]"); if (!items.length) return; const now = Date.now() / 1000; @@ -643,22 +647,25 @@ function startShotPolling() { preview.classList.toggle(UI_CLASS.shotEmpty, img.complete && img.naturalWidth === 0); }; syncShotEmpty(); - img.addEventListener("load", () => { - img.dataset.loading = "false"; - if (preview) preview.classList.remove(UI_CLASS.shotEmpty); - const ts = new Date().toLocaleTimeString(); - if (status) status.textContent = `已更新:${ts}`; - const tsBadge = document.getElementById("liveShotTs"); - if (tsBadge) { - tsBadge.textContent = ts; - tsBadge.hidden = false; - } - }); - img.addEventListener("error", () => { - img.dataset.loading = "false"; - if (preview) preview.classList.add(UI_CLASS.shotEmpty); - if (status) status.textContent = "暂无截图(等待脚本生成 pic/screenshot.png)"; - }); + if (!img.dataset.boundLoadHandler) { + img.dataset.boundLoadHandler = "1"; + img.addEventListener("load", () => { + img.dataset.loading = "false"; + if (preview) preview.classList.remove(UI_CLASS.shotEmpty); + const ts = new Date().toLocaleTimeString(); + if (status) status.textContent = `已更新:${ts}`; + const tsBadge = document.getElementById("liveShotTs"); + if (tsBadge) { + tsBadge.textContent = ts; + tsBadge.hidden = false; + } + }); + img.addEventListener("error", () => { + img.dataset.loading = "false"; + if (preview) preview.classList.add(UI_CLASS.shotEmpty); + if (status) status.textContent = "暂无截图(等待脚本生成 pic/screenshot.png)"; + }); + } setTimeout(syncShotEmpty, 0); }