From ea1e3dd8768df8522c3229400b7430f99d7e66b6 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 16 Jan 2026 01:39:53 +0800 Subject: [PATCH] Refactor fudai detection and logging mechanisms - Improved logging for task count retrieval and warnings in `douyin_fudai_core.py` and `douyin_stage.py`. - Enhanced error handling and logging in `fudai_detail_reader.py` to provide clearer insights when task counts are not saved. - Updated template matching logic in `douyin_detection.py` to include detailed logging and error handling for template loading and matching processes. - Refactored screenshot handling and debugging paths to ensure better traceability and error reporting. - Adjusted default task count values to zero where applicable to prevent unintended behavior. --- config/config.json | 4 +- docs/完整技术文档.md | 62 +- douyin/core/douyin_flow_control.py | 14 + douyin/core/douyin_fudai.py | 16 + douyin/detection/douyin_detection.py | 782 +++++++++++++++++++- douyin/fudai/douyin_fudai_core.py | 108 +-- douyin/stage/douyin_stage.py | 51 +- fudai_detail_modules/fudai_detail_reader.py | 16 +- 8 files changed, 886 insertions(+), 167 deletions(-) diff --git a/config/config.json b/config/config.json index e78da46..b6dae52 100644 --- a/config/config.json +++ b/config/config.json @@ -1,5 +1,5 @@ { - "needswitch": false, + "needswitch": true, "infinite_loop_enabled": true, "wait_minutes": 5, "min_prize_value_yuan": 250.0, @@ -32,7 +32,7 @@ "fudai_icon_retry_delay_seconds": 0.1, "fudai_exit_after_misses": 10, "enable_back_on_misses": true, - "fudai_click_wait_seconds": 1.2, + "fudai_click_wait_seconds": 1.5, "fudai_detail_initial_wait_seconds": 0.8, "fudai_detail_verified_wait_seconds": 0.2, "fudai_detail_retry_delay_seconds": 0.5, diff --git a/docs/完整技术文档.md b/docs/完整技术文档.md index 89f6f2f..9f79712 100644 --- a/docs/完整技术文档.md +++ b/docs/完整技术文档.md @@ -1,51 +1,52 @@ # 抖音福袋挂机 — 完整技术文档(重构) -版本: V4.1 -最后更新: 2026-01-07 +版本: V4.2 +最后更新: 2026-01-16 目标读者: 开发者、维护者、运维与 AI 助手 说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。 -- 变更记录 +- 2026-01-16: V4.2 — 优化任务数量传递逻辑,统一日志时间戳格式,添加警告日志追踪。 - 2026-01-07: V4.1 — 删除所有预约抢占逻辑,包括配置项、代码实现和相关文档。 - 2026-01-03: V4.0 — 重构文档结构,补充快速上手、配置优先级、截图/OCR/日志说明、故障排查与验证清单。 -## 最近修复与配置变更(2026-01-07) +## 最近修复与配置变更(2026-01-16) 本小节记录最近完成的若干修复与功能开关,便于开发与运维快速验证和回滚。 -- 概要:增加能在运行时关闭对“福袋内容”和“福袋任务列表”两类 OCR 的识别开关(配置项与 GUI),并修复了在并行 OCR 失败后串行兜底不尊重配置而仍然触发 OCR 的问题;同时修复了 actions.log 轮转时的文件被占用错误(WinError 32),以及新增“连续未找到福袋时按返回退出直播间”的可配置行为。 +- 概要:优化福袋详情页任务计数检测,避免重复阶段诊断;统一日志时间戳格式为毫秒精度;增加任务计数未获取时的警告日志;修复截图复用逻辑,确保在详情页关闭前复用截图。 -- 主要变更点(代码 / 配置): - - 配置项:在 `config/config.json` 中添加 - - `fudai_disable_content_recognition`(布尔) — 关闭福袋内容 OCR - - `fudai_disable_task_recognition`(布尔) — 关闭福袋任务列表 OCR - - `fudai_exit_after_misses`(整数) — 连续未找到福袋 N 次后按返回退出直播间 - - GUI:`gui/gui_app.py` 增加对应复选框/数值输入,并在保存时写入 `config/config.json`。 - - 核心修复: - - `douyin/fudai/core/fudai_detail_reader.py`: - - 并行/备用并行/串行兜底分支均尊重 `fudai_disable_content_recognition` 与 `fudai_disable_task_recognition`,避免在配置启用时仍执行 OCR。 - - 在串行兜底中添加了跳过日志(例如:"跳过串行福袋内容OCR识别(配置启用)")。 - - `douyin/fudai/douyin_fudai_core.py`:保留并使用内容 OCR 开关的判定逻辑(跳过调度/提交)。 - - `douyin/core/douyin_flow_control.py`:修复了导致模块导入失败的语法错误,并实现了“连续未找到福袋按返回退出”的计数与触发逻辑。 - - 日志写法修正:将 ad-hoc 的直接写 actions.log 的行为替换为通过统一 logger 输出,避免 RotatingFileHandler 在 Windows 上轮转时报 WinError 32(文件被占用)。相关调整见 `douyin/handlers/douyin_screenshot_manager.py` / `douyin/logging/*`。 + - 任务计数检测优化: + - `douyin/stage/douyin_stage.py`:限制任务计数仅在触发原因 "find_and_open_fudai_detail_click_verification" 时设置,避免重复诊断。 + - `douyin/fudai/douyin_fudai_core.py`:删除备用阶段检测逻辑,默认任务计数为 0,增加警告日志。 + - `fudai_detail_modules/fudai_detail_reader.py`:默认任务计数为 0,增强警告日志输出。 + - 日志时间戳统一: + - `douyin/logging/douyin_logging.py`:新增 MillisecondFormatter 类。 + - `unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。 + - `douyin/logging/action_logger.py`:更新为使用 MillisecondFormatter。 + - 截图复用优化: + - 确保在福袋详情页关闭前复用截图,避免不必要的重复截图。 - 验证要点(运行时观察): - - 预约系统不再执行抢占行为,日志中不会出现抢占相关的处理信息 - - 配置文件中不再包含抢占相关配置项 - - 代码中不再有抢占逻辑的分支判断 + - 日志时间戳统一为毫秒精度格式(如 2026-01-16 01:34:52.333)。 + - 福袋详情页不再出现重复阶段诊断。 + - 任务计数未获取时输出 WARNING 级别日志,包含原因和建议。 + - 截图在详情页关闭前得到复用。 - 快速验证命令(仓库根目录,PowerShell): ```powershell # 语法检查 -python -m py_compile douyin/core/douyin_fudai.py +python -m py_compile douyin/stage/douyin_stage.py +python -m py_compile douyin/fudai/douyin_fudai_core.py +python -m py_compile fudai_detail_modules/fudai_detail_reader.py -# 运行短会话验证预约功能正常 +# 运行短会话验证 python run_cli.py --wait-minutes 0 --device-id -# 检查配置文件中是否删除了抢占相关配置项 -Select-String -Path config/config.json -Pattern "preempt|poll_before" +# 检查日志格式 +Get-Content logs/actions.log -Tail 10 | Select-String "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}" ``` 如果需要,我可以把这些验证步骤写成一键脚本 `tools/verify_fudai_disable.sh` / `tools/verify_fudai_disable.ps1` 以便 CI 调用。 @@ -263,7 +264,6 @@ text = op.analyse_pic_word(img) - 关键文件与含义速查表(便于 LLM 快速定位实现细节): - `path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。 - `douyin/logging/douyin_logging_wrapper.py`:业务日志封装——搜索 `traceId` 与 `stage`。 - - `douyin/fudai/douyin_fudai_core.py`:业务决策与福袋解析。 - 可观测数据(建议供 AI 检索): - 截图目录:`pic/`(按时间戳与文件名可映射运行步骤)。 @@ -304,7 +304,6 @@ text = op.analyse_pic_word(img) - `run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。 - `douyin/core/douyin_fudai.py`:主分析器/主循环(`fudai_choujiang`、`run_once_basic`)。 - `Underlying_Operations.py`:底层设备/截图/OCR/文件操作。 -- `douyin/fudai/douyin_fudai_core.py`:福袋详情解析(`get_fudai_contain`、`basic_join_decision`、`attend_choujiang`)。 - `douyin/detection/douyin_pixel.py`:像素检测与并行检测实现。 - `douyin/stage/douyin_stage.py`:阶段诊断入口(`diagnose_stage_from_current_screen`)。 - `douyin/reservation/douyin_reservation_logic.py`:预约加载与回退处理。 @@ -416,7 +415,6 @@ PY - 导出规则:只保留非空条目(title 或 title_raw 非空),`_meta` 仅写入 JSON(CSV/MD 不包含 `_meta`)。CSV 第一行为 `pos,title,title_raw`,Markdown 为简单表格带顶部注释 ``。 - 查找/写入时机:`ReservationHandler.record_room_title_and_pos()` 在首次进入/切换直播间后会调用,只有在 `record_room_title_mapping_enabled` 为 True 时才执行,写入发生于首次记录或标题变更时。 -## GUI:映射表页面说明 - 页面位置:映射表由 `gui/gui_app.py` 提供(TreeView),从导出文件读取并呈现(优先读取 JSON,然后 CSV/MD 作为回退)。 - UI 元素:列 `位置` / `标题` / `原始标题`;支持 `手动刷新` 按钮与 2s 自动刷新(可在 GUI 中关闭)。 @@ -1093,7 +1091,6 @@ def read_pixel_stage_state_from_screenshot( #### `douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) -> bool` -- **文件位置**: `douyin/core/douyin_flow_control.py` - **作用**: 查找并打开福袋详情页 - **参数**: - `analyser: Any`: 分析器对象 @@ -1185,7 +1182,6 @@ def find_and_open_fudai_detail(analyser: Any, room_pos_ref: List[int]) -> bool: #### `douyin_flow_control.handle_no_fudai_situation(analyser, ...) -> bool` -- **文件位置**: `douyin/core/douyin_flow_control.py` - **作用**: 处理未找到福袋的情况,包括预约回退和切换直播间 - **参数**: - `analyser: Any`: 分析器对象 @@ -1269,7 +1265,6 @@ def handle_no_fudai_situation( #### `douyin_fudai_core.get_fudai_contain(analyser, renwu: int = 2) -> Tuple` -- **文件位置**: `douyin/fudai/douyin_fudai_core.py` - **作用**: 获取福袋的完整信息(内容、倒计时、价值、参与人数),使用并行OCR提高效率 - **参数**: - `analyser: Any`: 分析器对象 @@ -1359,7 +1354,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo #### `douyin_fudai_core.basic_join_decision(analyser: Any, detail: Tuple) -> bool` -- **文件位置**: `douyin/fudai/douyin_fudai_core.py` - **作用**: 基础版参与决策,根据配置筛选福袋 - **参数**: - `analyser: Any`: 分析器对象 @@ -4413,7 +4407,6 @@ self.new_config_item = self.config.get("new_config_item", False) - **`douyin/core/douyin_fudai.py`**: 主调度器类 `fudai_analyse` - **`douyin/core/douyin_main_flow.py`**: 主流程控制 -- **`douyin/core/douyin_flow_control.py`**: 流程控制辅助函数 #### 15.1.3 阶段诊断 @@ -4427,7 +4420,6 @@ self.new_config_item = self.config.get("new_config_item", False) #### 15.1.5 福袋模块 -- **`douyin/fudai/douyin_fudai_core.py`**: 福袋核心逻辑 - **`douyin/fudai/douyin_fudai_detail.py`**: 福袋详情处理 - **`douyin/fudai/douyin_fudai_finder.py`**: 福袋查找器 - **`douyin/fudai/core/fudai_attend.py`**: 参与抽奖逻辑 @@ -5373,7 +5365,6 @@ _room_pos_to_title_map: Dict[int, Tuple[str, str]] = { #### 18.3.1 `douyin_flow_control.handle_stage_after_diagnosis(analyser, stage, seen, loop_count) -> bool` -- **文件位置**: `douyin/core/douyin_flow_control.py` - **作用**: 记录阶段诊断结果,当前不改变主流程走向 - **参数**: - `analyser: Any`: 分析器对象 @@ -5389,7 +5380,6 @@ _room_pos_to_title_map: Dict[int, Tuple[str, str]] = { #### 18.3.2 `douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) -> bool` -- **文件位置**: `douyin/core/douyin_flow_control.py` - **作用**: 在当前直播间查找福袋图标并尝试点击打开详情 - **参数**: - `analyser: Any`: 分析器对象 @@ -5421,7 +5411,6 @@ _room_pos_to_title_map: Dict[int, Tuple[str, str]] = { #### 18.3.3 `douyin_flow_control.handle_no_fudai_situation(analyser, ...) -> bool` -- **文件位置**: `douyin/core/douyin_flow_control.py` - **作用**: 在没有福袋时做简单的等待/上滑切换 - **参数**: 多个参数,包括 `needswitch`、`reservations`、回调函数等 - **返回值**: `bool` - 是否已处理 @@ -6956,7 +6945,6 @@ result = analyser.operation.analyse_pic_word(preprocessed_name, 0) #### 24.3.1 并行OCR实现 -**文件位置**: `douyin/fudai/core/fudai_detail_reader.py` **实现方式**: ```python diff --git a/douyin/core/douyin_flow_control.py b/douyin/core/douyin_flow_control.py index 1e14590..17e0d06 100644 --- a/douyin/core/douyin_flow_control.py +++ b/douyin/core/douyin_flow_control.py @@ -421,6 +421,20 @@ def find_and_open_fudai_detail( ) except Exception: pass + try: + # 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图 + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:阶段诊断后诊断结果状态", + task_count_from_stage=getattr( + analyser, "_fudai_detail_task_count_from_stage", None + ), + screenshot_ready_for_ocr=getattr( + analyser, "_screenshot_ready_for_ocr", False + ), + ) + except Exception: + pass try: analyser._fudai_detail_first_read = False analyser._last_fudai_detail_tuple = None diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 8949bd8..d477928 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -2027,6 +2027,22 @@ class fudai_analyse: ) return + # 结构化预日志,记录缓存的阶段诊断结果(若存在),便于排查为何后续没复用首次诊断结果 + 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" ) diff --git a/douyin/detection/douyin_detection.py b/douyin/detection/douyin_detection.py index 1daaf9c..e8ca5e3 100644 --- a/douyin/detection/douyin_detection.py +++ b/douyin/detection/douyin_detection.py @@ -490,9 +490,9 @@ def check_have_fudai_with_ready_screenshot( # 保存完整截图 debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb_full, - operation_type="detection", - picname="福袋图标", - step="检测前", + operation_type="pixel_detect", + picname="fudai_icon", + step="before_detect", coords=( (scan_x_start, scan_y - 3, scan_x_end, scan_y + 4) if scan_y >= 3 @@ -618,9 +618,9 @@ def check_have_fudai_with_ready_screenshot( pic_rgb_full = pic_new.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb_full, - operation_type="detection", - picname="福袋图标", - step="检测成功", + operation_type="pixel_detect", + picname="fudai_icon", + step="detected", coords=(x1, y_top, x2, y_bottom), extra_info={ "detected_x": detected_x, @@ -839,7 +839,240 @@ def check_have_fudai_with_ready_screenshot( # 像素检测失败,记录但不影响主流程 pass - # 像素检测未命中时,不再使用模板匹配作为兜底(已删除) + # 像素检测未命中时,使用模板匹配作为兜底 + if not detected or detected_x is None: + try: + import cv2 + import numpy as np + + # 获取模板路径 + try: + import path_config + + template_path = path_config.get_assets_dir() + "/fudai.png" + except Exception: + # 回退到旧路径(向后兼容) + base_dir = os.path.dirname(__file__) + template_path = os.path.join(base_dir, "assets", "fudai.png") + + if os.path.exists(template_path): + # 获取匹配阈值 + try: + template_threshold = float( + getattr(analyser, "fudai_template_match_threshold", 0.7) + or 0.7 + ) + except Exception: + template_threshold = 0.7 + + # 读取模板 + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is not None: + # 将PIL图片转换为OpenCV格式 + pic_rgb = pic_new.convert("RGB") + screenshot_bgr = cv2.cvtColor( + np.array(pic_rgb), cv2.COLOR_RGB2BGR + ) + + # 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准) + x1 = max(0, 156 * rx // 1080) + x2 = min(width, 269 * rx // 1080) + y_top = max(0, 351 * ry // 2400 + y_pianyi_val) + y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val) + + if x1 < x2 and y_top < y_bottom: + search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index] + + if search_roi.size > 0: + th, tw = template.shape[:2] + rh, rw = search_roi.shape[:2] + + # 保存搜索区域截图到 last_match.png + try: + base_dir = os.path.dirname(__file__) + pic_base = os.path.join(base_dir, "pic") + match_dir = os.path.join(pic_base, "template_match") + os.makedirs(match_dir, exist_ok=True) + last_match_path = os.path.join( + match_dir, "last_match.png" + ) + + # 保存截图并检查是否成功 + save_success = cv2.imwrite( + last_match_path, search_roi + ) + if save_success: + try: + analyser._log_kv( + "[找福袋图标] 已保存搜索区域截图", + loop=loop, + 文件路径=last_match_path, + 搜索区域尺寸=f"{rw}x{rh}", + 搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})", + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "[找福袋图标] 保存搜索区域截图失败", + loop=loop, + 文件路径=last_match_path, + ) + except Exception: + pass + except Exception as save_err: + try: + analyser._log_kv( + "[找福袋图标] 保存搜索区域截图异常", + loop=loop, + 错误类型=type(save_err).__name__, + 错误信息=str(save_err), + ) + except Exception: + pass + + # 如果模板太大,缩小模板 + if th > rh or tw > rw: + scale = min(rh / max(th, 1), rw / max(tw, 1)) + if scale > 0: + template = cv2.resize( + template, + ( + max(1, int(tw * scale)), + max(1, int(th * scale)), + ), + ) + th, tw = template.shape[:2] + + # 执行模板匹配 + if th <= rh and tw <= rw: + res = cv2.matchTemplate( + search_roi, template, cv2.TM_CCOEFF_NORMED + ) + _min_val, max_val, _min_loc, max_loc = ( + cv2.minMaxLoc(res) + ) + + # 双截图记录:保存实时操作截图(搜索区域) + try: + import importlib + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) + from PIL import Image as PILImage + + search_roi_pil = PILImage.fromarray( + cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB) + ) + douyin_screenshot_manager.save_latest_attempt( + search_roi_pil, + operation_type="template_match", + ) + except Exception: + pass + + try: + analyser._log_kv( + "[找福袋图标] 模板匹配兜底", + loop=loop, + 匹配分数=round(max_val, 4), + 阈值=template_threshold, + 是否通过=bool( + max_val >= template_threshold + ), + 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", + 搜索区域尺寸=f"{rw}x{rh}", + 模板尺寸=f"{tw}x{th}", + 截图尺寸=f"{width}x{height}", + 分辨率=f"{rx}x{ry}", + ) + except Exception: + pass + + if max_val >= template_threshold: + # 双截图记录:保存成功识别存档截图 + try: + import importlib + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) + from PIL import Image as PILImage + + search_roi_pil = PILImage.fromarray( + cv2.cvtColor( + search_roi, cv2.COLOR_BGR2RGB + ) + ) + douyin_screenshot_manager.save_last_success( + search_roi_pil, + operation_type="template_match", + ) + except Exception: + pass + # 计算检测到的X坐标(1080基准) + detected_x_in_roi = max_loc[0] + detected_x = int( + (x1 + detected_x_in_roi + tw // 2) + * 1080.0 + / max(1, rx) + ) + detected = True + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + else: + # 模板尺寸不匹配,记录调试信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-尺寸不匹配", + loop=loop, + 模板尺寸=f"{tw}x{th}", + 搜索区域尺寸=f"{rw}x{rh}", + 条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})", + ) + except Exception: + pass + else: + # 搜索区域为空,记录调试信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-搜索区域为空", + loop=loop, + 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", + 截图尺寸=f"{width}x{height}", + ) + except Exception: + pass + else: + # 搜索区域坐标无效,记录调试信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-坐标无效", + loop=loop, + x1=x1, + x2=x2, + y_top=y_top, + y_bottom=y_bottom, + 截图尺寸=f"{width}x{height}", + 分辨率=f"{rx}x{ry}", + ) + except Exception: + pass + except (ImportError, Exception) as e: + # OpenCV不可用或模板匹配失败,继续使用像素检测结果 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配异常", + loop=loop, + 错误类型=type(e).__name__, + 错误信息=str(e), + ) + except Exception: + pass if detected and detected_x is not None: # 重置连续失败计数 @@ -967,44 +1200,515 @@ def check_have_fudai_with_ready_screenshot( ) except Exception: pass + return False - # 保存完整截图用于调试(检测完成但未找到) try: - from douyin.handlers import douyin_screenshot_manager - - pic_rgb_full = pic_new.convert("RGB") - - # 保存完整截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb_full, - operation_type="detection", - picname="福袋图标", - step="检测完成未找到", - coords=( - (scan_x_start, scan_y - 3, scan_x_end, scan_y + 4) - if scan_y >= 3 - else None - ), - extra_info={ - "scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}", - "resolution": f"{rx}x{ry}", - "y_offset": y_pianyi_val, - "total_loops": loop, - "result": "not_found", - "elapsed_ms": total_elapsed_ms, - }, + retry_delay_s = float( + getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3 + ) + except Exception: + retry_delay_s = 0.3 + try: + max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 2.5) or 2.5) + except Exception: + max_wait_s = 2.5 + if retry_delay_s < 0.15: + retry_delay_s = 0.15 + if max_wait_s < 0: + max_wait_s = 0.0 + + try: + analyser._log_kv( + "[找福袋图标] 开始", + f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready},使用模板匹配", ) - if debug_path: - try: - analyser._log_kv( - "[调试图像]", "福袋图标检测完成保存完整截图", path=debug_path - ) - except Exception: - pass except Exception: pass - return False + detected_any = False + detected_x = None + + # 检查OpenCV是否可用 + try: + import cv2 + import numpy as np + except Exception: + try: + analyser._log_kv( + "[找福袋图标] 错误", "OpenCV/numpy不可用,无法使用模板匹配" + ) + except Exception: + pass + return False + + # 获取模板路径 + try: + import path_config + + template_path = path_config.get_assets_dir() + "/fudai.png" + except Exception: + # 回退到旧路径(向后兼容) + base_dir = os.path.dirname(__file__) + template_path = os.path.join(base_dir, "assets", "fudai.png") + if not os.path.exists(template_path): + try: + analyser._log_kv("[找福袋图标] 错误", f"模板文件不存在: {template_path}") + except Exception: + pass + return False + + # 获取匹配阈值 + try: + template_threshold = float( + getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 + ) + except Exception: + template_threshold = 0.7 + + # 完全基于时间限制,不使用次数限制 + while (time.time() - func_start) < max_wait_s: + attempt_start = time.time() + attempt_count += 1 + # Reuse external screenshot only on first attempt if provided + if not (screenshot_ready and attempt_count == 1): + try: + analyser._shot_and_diagnose( + "找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False + ) + except Exception: + pass + + try: + screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR) + if screenshot_img is None: + try: + analyser.operation.get_screenshot( + analyser.device_id, use_service=False + ) + screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR) + except Exception: + pass + if screenshot_img is None: + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + except Exception: + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + + # Resolution ratios + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + try: + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + except Exception: + y_pianyi_val = 0 + + # 定义搜索区域(仅在更小的范围内寻找福袋图标) + # X范围:157-269(1080基准) # 左上角 X 改为图片中的坐标 x=157(右下不变) + # Y范围:354-451(2400基准) # 左上角 Y 改为图片中的坐标 y=354(右下不变) + search_x1 = max(0, 157 * rx // 1080) + search_x2 = min(screenshot_img.shape[1], 269 * rx // 1080) + search_y1_base = 354 * ry // 2400 + y_pianyi_val + search_y2_base = 451 * ry // 2400 + y_pianyi_val + search_y1 = max(0, search_y1_base) + search_y2 = min(screenshot_img.shape[0], search_y2_base) + + if search_x1 >= search_x2 or search_y1 >= search_y2: + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + + # 裁剪搜索区域 + search_roi = screenshot_img[search_y1:search_y2, search_x1:search_x2] + + # 读取模板 + try: + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is None: + try: + analyser._log_kv( + "[找福袋图标] 错误", f"无法读取模板文件: {template_path}" + ) + except Exception: + pass + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + except Exception as e: + try: + analyser._log_kv("[找福袋图标] 错误", f"读取模板文件异常: {str(e)}") + except Exception: + pass + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + + # 检查模板和搜索区域尺寸 + th, tw = template.shape[:2] + rh, rw = search_roi.shape[:2] + + if th > rh or tw > rw: + # 模板太大,缩小模板 + scale = min(rh / max(th, 1), rw / max(tw, 1)) + if scale > 0: + template = cv2.resize( + template, (max(1, int(tw * scale)), max(1, int(th * scale))) + ) + th, tw = template.shape[:2] + + # 执行模板匹配(使用彩色匹配) + try: + template_match_start = time.time() + + # 详细日志:记录搜索区域和模板信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配开始", + f"搜索区域", + search_x1=search_x1, + search_x2=search_x2, + search_y1=search_y1, + search_y2=search_y2, + search_width=search_x2 - search_x1, + search_height=search_y2 - search_y1, + template_width=tw, + template_height=th, + template_path=template_path, + 阈值=template_threshold, + 匹配模式="彩色(BGR)", + ) + except Exception: + pass + + # 使用彩色匹配(BGR三通道) + res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + + # 双截图记录:保存实时操作截图(搜索区域) + try: + import importlib + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) + from PIL import Image as PILImage + + search_roi_pil = PILImage.fromarray( + cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB) + ) + douyin_screenshot_manager.save_latest_attempt( + search_roi_pil, operation_type="template_match" + ) + + # 保存调试图像(匹配前)- 使用完整截图 + screenshot_pil = PILImage.fromarray( + cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB) + ) + debug_path = douyin_screenshot_manager.save_debug_image( + screenshot_pil, + operation_type="template_match", + picname="fudai_icon", + step="before_match", + coords=(search_x1, search_y1, search_x2, search_y2), + extra_info={ + "template": ( + os.path.basename(template_path) if template_path else "" + ), + "template_size": f"{tw}x{th}", + "search_size": f"{search_x2-search_x1}x{search_y2-search_y1}", + "threshold": template_threshold, + }, + ) + if debug_path: + try: + analyser._log_kv( + "[调试图像]", + "模板匹配前保存", + path=debug_path, + coords=f"({search_x1},{search_y1})-({search_x2},{search_y2})", + ) + except Exception: + pass + except Exception: + pass + + template_match_elapsed = (time.time() - template_match_start) * 1000 + + # 详细日志:记录匹配结果 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配结果", + f"匹配分数={round(max_val, 4)},阈值={template_threshold}", + 耗时毫秒=round(template_match_elapsed, 2), + 是否通过=bool(max_val >= template_threshold), + 最小分数=round(_min_val, 4), + 最佳位置=f"({max_loc[0]}, {max_loc[1]})", + ) + except Exception: + pass + + if max_val >= template_threshold: + # 双截图记录:保存成功识别存档截图 + try: + import importlib + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) + from PIL import Image as PILImage + + search_roi_pil = PILImage.fromarray( + cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB) + ) + douyin_screenshot_manager.save_last_success( + search_roi_pil, operation_type="template_match" + ) + + # 保存带匹配结果的调试图像(带匹配框)- 使用完整截图 + screenshot_pil = PILImage.fromarray( + cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB) + ) + # 计算匹配位置在完整截图中的坐标 + match_x_in_roi = max_loc[0] + match_y_in_roi = max_loc[1] + match_x1 = search_x1 + match_x_in_roi + match_y1 = search_y1 + match_y_in_roi + match_x2 = search_x1 + match_x_in_roi + tw + match_y2 = search_y1 + match_y_in_roi + th + match_coords = (match_x1, match_y1, match_x2, match_y2) + + debug_path = douyin_screenshot_manager.save_debug_image( + screenshot_pil, + operation_type="template_match", + picname="fudai_icon", + step="matched", + coords=( + search_x1, + search_y1, + search_x2, + search_y2, + ), # 搜索区域坐标 + extra_info={ + "match_score": round(max_val, 4), + "match_location": f"({max_loc[0]},{max_loc[1]})", + "match_coords": match_coords, # 匹配位置坐标 + "template_size": f"{tw}x{th}", + "threshold": template_threshold, + "passed": True, + }, + ) + if debug_path: + try: + analyser._log_kv( + "[调试图像]", + "模板匹配成功保存", + path=debug_path, + score=round(max_val, 4), + location=f"({max_loc[0]},{max_loc[1]})", + ) + except Exception: + pass + except Exception: + pass + + # 计算检测到的X坐标(1080基准) + detected_x_in_roi = max_loc[0] + detected_x = int( + (search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx) + ) + detected_y_in_roi = max_loc[1] + detected_y = int( + (search_y1 + detected_y_in_roi + th // 2) * 2400.0 / max(1, ry) + ) + detected_any = True + + # 保存匹配位置的图片 + try: + # 计算匹配区域在原图中的坐标(扩大一些范围以便查看上下文) + margin = 20 # 扩大20像素的边距 + match_x1 = max(0, search_x1 + detected_x_in_roi - margin) + match_y1 = max(0, search_y1 + detected_y_in_roi - margin) + match_x2 = min( + screenshot_img.shape[1], + search_x1 + detected_x_in_roi + tw + margin, + ) + match_y2 = min( + screenshot_img.shape[0], + search_y1 + detected_y_in_roi + th + margin, + ) + + # 裁剪匹配区域 + match_roi = screenshot_img[match_y1:match_y2, match_x1:match_x2] + + # 保存到 pic/template_match/ 目录 + base_dir = os.path.dirname(__file__) + pic_base = os.path.join(base_dir, "pic") + match_dir = os.path.join(pic_base, "template_match") + os.makedirs(match_dir, exist_ok=True) + + # 文件名包含时间戳和匹配分数 + timestamp = int(time.time() * 1000) + score_str = f"{max_val:.4f}".replace(".", "_") + match_filename = f"fudai_match_{timestamp}_score_{score_str}.png" + match_path = os.path.join(match_dir, match_filename) + + # 检查裁剪区域是否有效 + if match_roi.size == 0: + analyser._log_kv( + "[找福袋图标] 警告", + "匹配区域裁剪后为空,跳过保存", + 区域坐标=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})", + ) + else: + # 保存图片 + save_success = cv2.imwrite(match_path, match_roi) + + # 验证文件是否真的保存成功 + file_exists = os.path.exists(match_path) + file_size = os.path.getsize(match_path) if file_exists else 0 + + analyser._log_kv( + "[找福袋图标] 已保存匹配位置图片", + f"路径: {match_path}", + 匹配区域=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})", + 区域大小=f"{match_x2 - match_x1}x{match_y2 - match_y1}", + ROI尺寸=f"{match_roi.shape[1]}x{match_roi.shape[0]}", + cv2保存返回值=save_success, + 文件存在=file_exists, + 文件大小字节=file_size, + ) + + if not file_exists or file_size == 0: + analyser._log_kv( + "[找福袋图标] 警告", + "保存的图片文件不存在或大小为0", + 路径=match_path, + ) + else: + # 保存成功,输出绝对路径方便查看 + abs_path = os.path.abspath(match_path) + analyser._log_kv( + "[找福袋图标] 图片保存成功", + f"绝对路径: {abs_path}", + ) + except Exception as e: + try: + analyser._log_kv( + "[找福袋图标] 保存匹配位置图片失败", + f"异常: {str(e)}", + ) + except Exception: + pass + + try: + analyser.last_find_fudai_time = time.time() + analyser._log_kv( + "[找福袋图标] 模板匹配命中", + f"检测到福袋图标", + x=detected_x, + y=detected_y, + 匹配分数=round(max_val, 4), + x_in_roi=detected_x_in_roi, + y_in_roi=detected_y_in_roi, + 模板中心偏移=f"({tw//2}, {th//2})", + 实际屏幕坐标=f"({detected_x}, {detected_y})", + ) + except Exception: + pass + break + else: + # 未命中时也记录日志 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配未命中", + f"匹配分数={round(max_val, 4)} < 阈值={template_threshold}", + 差值=round(template_threshold - max_val, 4), + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "[找福袋图标] 模板匹配异常", + f"异常: {str(e)}", + 异常类型=type(e).__name__, + ) + except Exception: + pass + + # 检查是否还有剩余时间 + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + + try: + total_elapsed = time.time() - func_start + analyser._log_kv( + "[找福袋图标] 结束", + "检测完成", + detected=bool(detected_any and detected_x is not None), + elapsed_ms=int(total_elapsed * 1000), + ) + except Exception: + pass + + # 与原始 fudai.py 的 check_have_fudai 行为保持一致: + # 返回福袋图标的 x 坐标(1080 基准坐标),未找到返回 False。 + return int(detected_x) if detected_x is not None else False + + +# ========== 以下为旧的像素检测代码,已暂时禁用 ========== +# 像素检测代码已删除,使用模板匹配替代 +# 如需恢复像素检测,请参考 git 历史记录 def check_in_fudai_detail(analyser: Any) -> bool: diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 567ed69..1068fc4 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -5500,92 +5500,38 @@ def basic_join_decision( analyser, "_fudai_detail_task_count_from_stage", None ) if task_count_from_stage is not None: - task_count = int(task_count_from_stage or 2) + task_count = int(task_count_from_stage or 0) + try: + analyser._log_kv( + "福袋详情", + "douyin_fudai_core:从阶段检测获取任务数量", + log_type="OP", + 任务数量=task_count, + 原始值=task_count_from_stage, + ) + except Exception: + pass # 清除标志,避免影响后续调用 analyser._fudai_detail_task_count_from_stage = None - else: - # 如果阶段检测未保存任务数量,尝试通过阶段检测获取 try: - from douyin.stage import douyin_stage - - analyser.operation.get_screenshot( - analyser.device_id, use_service=False + analyser._log_kv( + "福袋详情", + "douyin_fudai_core:清除任务数量标志", + log_type="DEBUG", ) - result = ( - douyin_stage.diagnose_stage_from_current_screen( - analyser - ) + except Exception: + pass + else: + # 警告:未获取到任务数量,使用默认值0 + task_count = 0 + try: + analyser._log_kv( + "福袋详情", + "douyin_fudai_core:警告:未从阶段检测获取任务数量,使用默认值0", + log_type="WARNING", + 可能原因="阶段检测未触发或像素检测失败", + 建议="检查点击验证阶段检测是否正常执行", ) - if result: - stage, _ = result - if stage == "FUDai_DETAIL": - # 尝试通过像素检测获取任务数量 - try: - from douyin.detection import ( - douyin_pixel, - ) - - pic_path = os.path.join( - os.path.dirname(__file__), - "pic", - "screenshot.png", - ) - if os.path.exists(pic_path): - pic = Image.open(pic_path) - pic_rgb = pic.convert("RGB") - rx = int( - getattr( - analyser, - "resolution_ratio_x", - 1080, - ) - or 1080 - ) - ry = int( - getattr( - analyser, - "resolution_ratio_y", - 2400, - ) - or 2400 - ) - y_pianyi = int( - getattr(analyser, "y_pianyi", 0) - or 0 - ) - result = douyin_pixel.detect_fudai_detail_page( - pic_rgb, - rx, - ry, - y_pianyi, - float( - getattr( - analyser, - "fudai_detail_template_threshold", - 0.7, - ) - or 0.7 - ), - return_info=True, - analyser=analyser, - ) - if isinstance(result, tuple): - _, detect_info = result - detected_task_count = ( - detect_info.get( - "task_count", 0 - ) - ) - if detected_task_count in ( - 1, - 2, - 3, - ): - task_count = ( - detected_task_count - ) - except Exception: - pass except Exception: pass diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index e431f4c..ce44b85 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -83,6 +83,22 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t # 输出开始分隔符与起始信息 print(f"[DEBUG] 阶段诊断开始: trigger_reason={trigger_reason}") _log_separator("开始阶段诊断") + # 结构化日志:确保将触发原因、以及可能来自此前阶段诊断的缓存信息写入统一日志 + try: + analyser._log_kv( + "阶段诊断", + "开始阶段诊断", + trigger_reason=trigger_reason, + fudai_detail_task_count_from_stage=getattr( + analyser, "_fudai_detail_task_count_from_stage", None + ), + screenshot_ready_for_ocr=bool( + getattr(analyser, "_screenshot_ready_for_ocr", False) + ), + log_type="DEBUG", + ) + except Exception: + pass _log_summary( "开始阶段诊断", 最大诊断时间秒=max_diag_time, @@ -721,10 +737,21 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t if "has_fudai_detail" in pixel_details: detail_task_count = pixel_details["has_fudai_detail"].get("task_count") # 保存任务数量到 analyser 对象,供后续读取详情时使用 - # 确保 detail_task_count 不是 None 时才保存 - if detail_task_count is not None: + # 确保 detail_task_count 不是 None 且触发原因是点击验证时才保存 + if ( + detail_task_count is not None + and trigger_reason == "find_and_open_fudai_detail_click_verification" + ): try: analyser._fudai_detail_task_count_from_stage = detail_task_count + try: + _log( # type: ignore[misc] + "阶段检测:设置任务数量到 analyser", + 任务数量=detail_task_count, + 触发原因=trigger_reason, + ) + except Exception: + pass # 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图 if detail_task_count > 0: analyser._screenshot_ready_for_ocr = True @@ -736,16 +763,30 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t ) except Exception: pass + except Exception: + pass + else: + # 如果未检测到任务数量或触发原因不匹配,设置为空 + try: + analyser._fudai_detail_task_count_from_stage = None try: _log( # type: ignore[misc] - "保存任务数量到 analyser 对象", - 任务数量=detail_task_count, - has_fudai_detail=detail_detected, + "阶段检测:任务数量未检测到或触发原因不匹配,设置为空", + 检测到的任务数量=detail_task_count, + 触发原因=trigger_reason, ) except Exception: pass except Exception: pass + try: + _log( # type: ignore[misc] + "保存任务数量到 analyser 对象", + 任务数量=detail_task_count, + has_fudai_detail=detail_detected, + ) + except Exception: + pass else: # detail_task_count 为 None,记录警告日志 try: diff --git a/fudai_detail_modules/fudai_detail_reader.py b/fudai_detail_modules/fudai_detail_reader.py index b9c3a8a..48305ba 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/fudai_detail_modules/fudai_detail_reader.py @@ -87,19 +87,29 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: try: analyser._log_kv( "福袋详情", - "read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)", - log_type="DEBUG", + "read_fudai_detail_once:警告:阶段检测未保存任务数量,使用默认值0", + log_type="WARNING", + 可能原因="点击验证阶段检测未执行或像素检测失败", + 建议="检查阶段检测日志,确认触发原因和检测结果", task_count_from_stage=task_count_from_stage, ) except Exception: pass pass # 使用默认值 - task_count = 2 + task_count = 0 # 清除任务数量标志,截图复用标志留给后续OCR阶段使用 try: analyser._fudai_detail_task_count_from_stage = None + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once:清除任务数量标志", + log_type="DEBUG", + ) + except Exception: + pass except Exception: # 忽略异常,继续处理 pass