refactor: split large modules and harden live-room fudai flow

This commit is contained in:
Your Name committed 2026-06-01 18:39:44 +08:00
1 parent 1845561405
commit 36e374ef67
86 files changed
+7422 -8404

No files matched your search

+7
View File
@@ -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*
+2 -1
View File
@@ -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:
+2 -1
View File
@@ -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:
+2 -2
View File
@@ -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
}
}
@@ -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`,继续排查其它入口)
- 本地路径、固定命令、默认端口
- 处理方式:
- 新增集中配置读取函数
- 原调用点只保留薄封装,避免每处单独拼环境变量
+50 -154
View File
@@ -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-id> device
```
若是 `unauthorized`,说明手机还未确认授权。
### 5.3 安装/确认抖音 APP
- 手机上安装并登录要运行的抖音账号
- 手动打开一次抖音到首页,确保账号状态正常
### 5.4(可选)安装 ADBKeyboard(提升文本输入兼容性)
项目内置 APK:`tools/adb/ADBKeyboard.apk`
```powershell
adb -s <device-id> install -r tools/adb/ADBKeyboard.apk
adb -s <device-id> shell ime list -s
```
若列表里存在 `com.android.adbkeyboard/.AdbIME`,可切换:
```powershell
adb -s <device-id> shell ime enable com.android.adbkeyboard/.AdbIME
adb -s <device-id> shell ime set com.android.adbkeyboard/.AdbIME
```
看到 `<device-id> 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 <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 <device-id>
```
若连接异常,先重启 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`
@@ -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
+19 -676
View File
@@ -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)
@@ -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)
@@ -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
@@ -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
@@ -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)
@@ -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
@@ -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))
@@ -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))
File diff suppressed because it is too large. Load diff
@@ -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
@@ -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
@@ -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
+130 -733
View File
@@ -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 <pkg> -c android.intent.category.LAUNCHER 1` 启动主 launcher activity,
失败时回退到 `am start -n <pkg>/.<MainActivity>`(按抖音常用 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)
@@ -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",
]
@@ -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
)
@@ -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")
@@ -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,
@@ -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,
@@ -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)
@@ -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)
@@ -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)
+8 -1
View File
@@ -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:
File diff suppressed because it is too large. Load diff
@@ -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)
@@ -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
@@ -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
@@ -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,说明没有正确打开福袋详情页,尝试重新打开
@@ -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(
"参与",
@@ -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:
+42 -15
View File
@@ -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"(?<!\d)(\d{3,4})(?=\D*(?:后开奖|开奖|后|$))",
raw,
)
if compact:
digits = compact.group(1)
if len(digits) == 4:
mm, ss = _fmt_pair(digits[:2], digits[2:])
if mm and ss:
return mm, ss
elif len(digits) == 3:
mm, ss = _fmt_pair(digits[:1], digits[1:])
if mm and ss:
return mm, ss
return "", ""
@@ -653,16 +677,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> 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 ""),
File diff suppressed because it is too large. Load diff
+30
View File
@@ -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",
]
@@ -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)
@@ -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
@@ -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. 福袋价值
@@ -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
@@ -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
@@ -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:
@@ -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,
}
@@ -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
+27 -546
View File
@@ -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:
@@ -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()
+16 -5
View File
@@ -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),
)
@@ -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
@@ -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
@@ -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 "",
+38 -439
View File
@@ -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", "像素检测未命中,默认直播间"
@@ -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)
@@ -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
@@ -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", "像素检测未命中,默认直播间"
@@ -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
@@ -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
+30 -177
View File
@@ -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")
+127
View File
@@ -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")
+2 -2
View File
@@ -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()),
)
+48 -127
View File
@@ -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)
@@ -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
+14 -1072
View File
File diff suppressed because it is too large. Load diff
+150
View File
@@ -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)
+148
View File
@@ -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
+9 -6
View File
@@ -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:
+14 -6
View File
@@ -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)
+5 -3
View File
@@ -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,
@@ -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 == ""
@@ -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)
@@ -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()
+89
View File
@@ -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()
@@ -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"
+69
View File
@@ -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
@@ -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"
@@ -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"
+8 -74
View File
@@ -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("<Control-o>", lambda e: self.open_dialog())
self.root.bind("<Left>", lambda e: self.prev_image())
self.root.bind("<Right>", lambda e: self.next_image())
self.root.bind("<Prior>", lambda e: self.prev_image()) # PageUp
self.root.bind("<Next>", lambda e: self.next_image()) # PageDown
self.root.bind("<plus>", lambda e: self.zoom_in())
self.root.bind("<equal>", lambda e: self.zoom_in()) # 无Shift的+键
self.root.bind("<minus>", lambda e: self.zoom_out())
self.root.bind("<Control-0>", lambda e: self.reset_zoom())
self.root.bind("<Control-f>", lambda e: self.fit_to_window())
self.root.bind("<Delete>", lambda e: self.clear_selection())
self.root.bind("<Return>", lambda e: self.analyze_region())
self.root.bind("<Control-s>", lambda e: self.save_regions())
self.root.bind("<Control-l>", lambda e: self.load_regions())
self.root.bind("<Control-a>", 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("<Motion>", self.on_move)
self.canvas.bind("<Button-1>", self.on_left_click)
self.canvas.bind("<B1-Motion>", self.on_left_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_left_release)
self.canvas.bind("<Button-3>", self.on_right_click) # 右键开始拖拽
self.canvas.bind("<B3-Motion>", self.on_right_drag) # 右键拖拽
self.canvas.bind("<ButtonRelease-3>", self.on_right_release)
self.canvas.bind("<MouseWheel>", self.on_mousewheel) # Windows/Linux
self.canvas.bind("<Button-4>", self.on_mousewheel) # Linux
self.canvas.bind("<Button-5>", self.on_mousewheel) # Linux
self.canvas.bind("<Control-MouseWheel>", 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('<<Drop>>', 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('<<Drop>>', self.on_drop)
except Exception:
pass # 忽略拖放设置失败
bind_canvas_events(self)
setup_dnd(self, HAS_DND, DND_FILES)
def _create_control_panel(self, parent):
"""创建控制面板"""
+89
View File
@@ -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("<Control-o>", lambda e: selector.open_dialog())
selector.root.bind("<Left>", lambda e: selector.prev_image())
selector.root.bind("<Right>", lambda e: selector.next_image())
selector.root.bind("<Prior>", lambda e: selector.prev_image())
selector.root.bind("<Next>", lambda e: selector.next_image())
selector.root.bind("<plus>", lambda e: selector.zoom_in())
selector.root.bind("<equal>", lambda e: selector.zoom_in())
selector.root.bind("<minus>", lambda e: selector.zoom_out())
selector.root.bind("<Control-0>", lambda e: selector.reset_zoom())
selector.root.bind("<Control-f>", lambda e: selector.fit_to_window())
selector.root.bind("<Delete>", lambda e: selector.clear_selection())
selector.root.bind("<Return>", lambda e: selector.analyze_region())
selector.root.bind("<Control-s>", lambda e: selector.save_regions())
selector.root.bind("<Control-l>", lambda e: selector.load_regions())
selector.root.bind("<Control-a>", lambda e: selector.show_all_regions())
def bind_canvas_events(selector) -> None:
"""绑定画布事件。"""
selector.canvas.bind("<Motion>", selector.on_move)
selector.canvas.bind("<Button-1>", selector.on_left_click)
selector.canvas.bind("<B1-Motion>", selector.on_left_drag)
selector.canvas.bind("<ButtonRelease-1>", selector.on_left_release)
selector.canvas.bind("<Button-3>", selector.on_right_click)
selector.canvas.bind("<B3-Motion>", selector.on_right_drag)
selector.canvas.bind("<ButtonRelease-3>", selector.on_right_release)
selector.canvas.bind("<MouseWheel>", selector.on_mousewheel)
selector.canvas.bind("<Button-4>", selector.on_mousewheel)
selector.canvas.bind("<Button-5>", selector.on_mousewheel)
selector.canvas.bind("<Control-MouseWheel>", 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("<<Drop>>", 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("<<Drop>>", selector.on_drop)
except Exception:
pass
+6 -48
View File
@@ -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("<Control-o>", lambda e: self.ask_for_image())
self.root.bind("<Control-s>", lambda e: self.save_regions())
self.root.bind("<Control-l>", lambda e: self.load_regions())
self.root.bind("<Delete>", lambda e: self.clear_selection())
self.root.bind("<Return>", lambda e: self.analyze_region())
# 视图相关快捷键
self.root.bind("<plus>", lambda e: self.zoom_in())
self.root.bind("<equal>", lambda e: self.zoom_in())
self.root.bind("<minus>", lambda e: self.zoom_out())
self.root.bind("<Control-0>", lambda e: self.reset_zoom())
self.root.bind("<Control-f>", 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("<Button-1>", self.on_canvas_click) # 左键添加点
self.canvas.bind("<Button-3>", self.on_canvas_right_click) # 右键完成多边形
self.canvas.bind("<B3-Motion>", self.on_canvas_drag) # 右键拖拽
self.canvas.bind("<MouseWheel>", self.on_mousewheel) # 滚轮缩放
self.root.bind("<space>", self.finish_polygon) # 空格键完成多边形
self.root.bind("<BackSpace>", self.remove_last_point) # 退格键删除最后一个点
bind_canvas_events(self)
def setup_control_panel(self, parent):
"""设置控制面板"""
+51
View File
@@ -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("<Control-o>", lambda e: selector.ask_for_image())
selector.root.bind("<Control-s>", lambda e: selector.save_regions())
selector.root.bind("<Control-l>", lambda e: selector.load_regions())
selector.root.bind("<Delete>", lambda e: selector.clear_selection())
selector.root.bind("<Return>", lambda e: selector.analyze_region())
selector.root.bind("<plus>", lambda e: selector.zoom_in())
selector.root.bind("<equal>", lambda e: selector.zoom_in())
selector.root.bind("<minus>", lambda e: selector.zoom_out())
selector.root.bind("<Control-0>", lambda e: selector.reset_zoom())
selector.root.bind("<Control-f>", lambda e: selector.fit_to_window())
selector.root.bind("<space>", selector.finish_polygon)
selector.root.bind("<BackSpace>", selector.remove_last_point)
def bind_canvas_events(selector) -> None:
selector.canvas.bind("<Button-1>", selector.on_canvas_click)
selector.canvas.bind("<Button-3>", selector.on_canvas_right_click)
selector.canvas.bind("<B3-Motion>", selector.on_canvas_drag)
selector.canvas.bind("<MouseWheel>", selector.on_mousewheel)
-99
View File
@@ -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",
+12
View File
@@ -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) {}
});
+17 -2
View File
@@ -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;
+24 -17
View File
@@ -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);
}