Author SHA1 Message Date
CodexandClaude Opus 4.7 c4b6a8e5f0 refactor(reservation): 拆出回退成功后的锁定期 + 完成日志(530→467,-63 行)
enter_lock_period_and_log_success:进入锁定期 + 写运行日志 + 行为日志 +
状态文件 + 完成日志,把回退成功后的所有善后动作集中处理。

新增 3 个单元测试,1343 → 1346 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 05:15:49 +08:00
CodexandClaude Opus 4.7 30a66e955c refactor(stage): 拆出可疑弹窗 OCR 二次确认(814→676,-138 行)
把 douyin_stage 末尾"像素检测到弹窗背景但未匹配 → OCR 二次确认"的 156 行块抽到
detect_suspicious_popup_via_ocr:
- _detect_coupon_popup_via_ocr:优惠券弹窗 OCR 确认(含并行 mode 0+1)
- _detect_redpacket_popup_via_ocr_simple:购物红包简单 OCR 确认(仅 mode 0)

新增 4 个单元测试覆盖:无背景 / 优惠券命中 / 红包命中 / 关键词未匹配。
1339 → 1343 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 05:12:17 +08:00
CodexandClaude Opus 4.7 9423ddbfef refactor(reservation): 拆出回退校验失败二次回退逻辑(853→530,-323 行)
把 attend_window 中"回退校验失败 → 通过映射表二次回退"的 343 行复杂逻辑抽到
attend_window_helpers:
- _resolve_target_pos_via_mapping:通过映射表查找目标位置
- _resolve_current_pos_via_mapping:查找当前位置(必要时重读标题)
- _decide_retry_seek:根据 mapped_pos_diff 决定是否需要纠偏 + 方向提示
- handle_verify_failure_retry_via_mapping:组合调用 → 调用 seek_callback →
  根据结果设置/清理锁定期标志 + 写状态文件

新增 8 个单元测试覆盖:seek 成功/失败/异常/无回调 / 各种 mapped_pos_diff 分支。
1330 → 1338 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 05:07:48 +08:00
CodexandClaude Opus 4.7 d24bc85902 refactor(detection): 拆出 finder.py numpy + 逐像素扫描(719→428,-291 行)
把 finder.py 中两个像素扫描兜底块抽到 template_match_helpers:
- numpy_pixel_scan:numpy 加速水平带扫描(126 行)
- per_pixel_scan_fallback:numpy 失败时的逐像素扫描(166 行)
- _is_target_pixel / _scan_one_row / _save_per_pixel_success:辅助函数

新增 10 个单元测试覆盖:无匹配 / 命中 / 无效 ROI / last_fudai_x 复用 /
异常吞噬 / 目标颜色范围判定。1320 → 1330 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:59:38 +08:00
CodexandClaude Opus 4.7 a391c21f47 refactor(detection): 拆出 finder.py 模板匹配兜底(936→719,-217 行)
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"块(226 行)抽到
template_match_helpers.template_match_fallback:
- 模板加载与缩放
- 搜索区域裁剪 + 边界保护
- cv2.matchTemplate + 双阈值判定
- 调试截图保存(last_match.png + 双截图记录)

新增 5 个单元测试覆盖:模板缺失 / 模板读取失败 / 阈值异常 / 不可达阈值 / 完美匹配。
1315 → 1320 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:55:08 +08:00
CodexandClaude Opus 4.7 27110446c2 refactor(reservation): 拆出回退后等待 + 成功/失败日志(937→853,-84 行)
- wait_for_live_room_load_after_back:回退后等待加载完成(钳到 [0.1, 10] 秒)
- log_back_success_pre_verify:回退成功进入校验前的诊断日志
- log_back_failure_and_finish:回退失败的善后(日志 + 写状态文件 + 完成日志)

新增 8 个单元测试,1307 → 1315 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:48:04 +08:00
CodexandClaude Opus 4.7 3192c8b5c7 refactor(reservation): 拆出参与窗口入口日志 + 回退回调(988→937,-51 行)
- log_entering_attend_window:写"进入预约参与窗口"诊断日志
- execute_seek_reservation_callback:调用 seek_reservation_room_callback +
  前置日志 + 异常吞噬

新增 5 个单元测试,1302 → 1307 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:43:27 +08:00
CodexandClaude Opus 4.7 02e685ba20 refactor(reservation): 拆出锁定期同预约位置/窗口复杂检查(1118→988,-130 行)
handle_lock_period_same_reservation_check:把"锁定期内 + 同一预约 + 是否在目标
位置 + 时间窗口"的 139 行复杂逻辑抽到 helper。返回 True/False/None 让主流程
精确控制后续行为:
- True:直接参与
- False:跳过回退
- None:继续走后续时间窗口检查

attend_window.py 跌破 1000 行(988)。

新增 6 个单元测试覆盖各分支组合,1296 → 1302 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:39:39 +08:00
CodexandClaude Opus 4.7 f46f9dc23e refactor(reservation): 拆出时间窗口早返回 + 队列满标志检查(1163→1118,-45 行)
- check_queue_full_immediate_attend:检查队列满立即参与模式
- handle_time_window_early_returns:时间窗口未到/已错过两种早返回(含 cleanup 调度)

新增 7 个单元测试,1289 → 1296 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:35:51 +08:00
CodexandClaude Opus 4.7 daddabd8cf refactor(stage): 拆出步骤3 OCR 推荐/关注/直播列表检测(1066→814,-252 行)
把 douyin_stage 步骤3 中的"OCR 推荐页/关注列表/直播列表标签栏"检测块(269 行)抽到
detect_recommend_follow_live_tabs。三个相似的"裁剪 + mode0+mode1 双 OCR + 关键词
匹配"块共享 _ocr_with_dual_modes 辅助。

新增 5 个单元测试覆盖 RECOMMEND/FOLLOW/LIVE 命中 + 全部不命中 + 外层异常吞噬。
1284 → 1289 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:31:50 +08:00
CodexandClaude Opus 4.7 c2654d60aa refactor(stage): 拆出"非直播间购物红包 OCR 复查"块(1204→1066,-138 行)
把 douyin_stage 步骤2.5 中的"非直播间购物红包 OCR 复查"逻辑(含 mode0+mode1
双 OCR、置信度兜底、154 行)抽到 detect_redpacket_ocr_recheck_outside_live。

新增 5 个单元测试(无背景跳过 / 关键词命中 / 高置信度命中 / 无匹配 / 异常吞噬)。
1279 → 1284 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:25:14 +08:00
CodexandClaude Opus 4.7 4cb5daa79e refactor(stage): 拆出抽奖结果弹窗 + 购物红包弹窗 OCR 检测(1284→1204,-80 行)
把 douyin_stage 中两个独立的"像素初筛 + OCR 二次确认"块抽到 douyin_stage_helpers:
- detect_lottery_result_popup:优先级1,抽奖结果弹窗(FUDai_RESULT)
- detect_shopping_redpacket_popup:优先级1.5,购物红包弹窗(SHOPPING_REDPACKET_POPUP)

两者都返回 (matched, stage, reason),命中时主流程直接 return。

新增 6 个单元测试,1273 → 1279 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:21:35 +08:00
CodexandClaude Opus 4.7 feaf555657 refactor(reservation): 拆出 attend_window 排序+超时检查(1222→1163,-59 行)
- sort_reservations_with_logging:就地排序 + 前后写日志(含异常吞噬)
- check_total_timeout:超时检查 + 写日志(含异常吞噬)

修复一个真实 bug:拆出 attend_window_helpers.py 时遗漏 import time,导致
check_total_timeout 内的 time.time() 抛 NameError,被外层 try/except 吞噬,
函数永远返回 False。原主文件不存在该 bug。

新增 6 个单元测试(含 import time 缺失场景的 swallow exception 验证),
1267 → 1273 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:17:29 +08:00
CodexandClaude Opus 4.7 89f001e5a4 refactor(reservation): 拆出 attend_window 已参与/无效ft/目标日志(1309→1222,-87 行)
- check_already_participated:检测是否已参与过该预约(5s 误差),命中则弹出队头
- discard_invalid_future_ts:future_ts 无效时丢弃队头
- log_target_reservation_details:记录目标预约的 future_ts/value/pos_seen/content

新增 11 个单元测试,1256 → 1267 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:10:24 +08:00
CodexandClaude Opus 4.7 e9e8e322c6 refactor(reservation): 拆出 attend_window 等待开奖检查 + 锁定期晋升(1375→1309,-66 行)
- check_waiting_for_reservation_lottery:等待预约福袋开奖时不抢占其他预约
- maybe_promote_locked_reservation:锁定期内把锁定预约移到队头,
  若已不在队列则清除锁定期

新增 8 个单元测试,1248 → 1256 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:06:28 +08:00
CodexandClaude Opus 4.7 b8a35656a0 refactor(fudai): 拆出额外验证 + 兜底无效详情检查(1121→1084,-37 行)
- handle_extra_validation:调用 validate_fudai_detail,失败时关闭详情 + 写日志
- handle_invalid_detail_fallback:价值=0 且内容空时判定为"无效详情"提前 return

新增 9 个单元测试,1239 → 1248 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:02:01 +08:00
CodexandClaude Opus 4.7 f075f94b31 refactor(fudai): 拆出第一次打开读取/验证/筛选 + 第二次重读详情(1212→1121,-91 行)
- reread_detail_for_second_open_fallthrough:第二次打开兜底重读
- perform_first_open_read_validate_filter:第一次打开整套(读取 → 验证失败兜底 →
  筛选 → 高价值决策 → 通过则保存)

新增 8 个单元测试覆盖各分支。1231 → 1239 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:58:19 +08:00
CodexandClaude Opus 4.7 df8424b706 refactor(fudai): 拆出高价值预约总调度(1273→1212,-61 行)
把 run_once_basic 中"高价值预约 + 闭包构造 + 6 个子块串联"的 67 行块抽到
fudai_run_blocks.process_high_value_reservation_check:
- 内部构造 _swipe_down_once / _sort_reservations / _write_state /
  _seek_reservation_room 4 个闭包
- 串联 handle_queue_full_wait_at_earliest / log_skip_reservation_check_for_state /
  handle_all_reservations_completed_reset / log_needswitch_check_details /
  execute_reservation_attend_or_cleanup

新增 4 个单元测试,1227 → 1231 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:53:33 +08:00
CodexandClaude Opus 4.7 e567948ec9 refactor(fudai): 拆出 _match_icon_template 到 fudai_image_helpers(1400→1273,-127 行)
把 _match_icon_template(135 行)的模板匹配逻辑抽到独立模块:
- _correlation_score:归一化相关系数(去均值后点积/范数乘积)
- _sliding_search_best_score:以模板边长 // 6 为步长滑动搜索
- match_icon_template:等尺寸直接算 / 模板小于 ROI 时先中心裁剪 + 滑动兜底

新增 8 个单元测试(同图完美匹配 / 反相关 / 模板缩放 / threshold 覆盖等)。
1219 → 1227 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:50:09 +08:00
CodexandClaude Opus 4.7 f3d4621686 refactor(fudai): 拆出 _capture_roi_screenshot 到 fudai_image_helpers(1529→1400,-129 行)
把 _capture_roi_screenshot(141 行)的 PNG 读取/校验/裁剪逻辑抽到独立模块:
- _read_screenshot_with_validation:6 次重试 + PNG 头/尾/PIL.verify 校验
- _open_image_or_retry:解析失败时重读一次再解析
- capture_roi_screenshot:组合上述步骤,裁剪 ROI 后保存到 pic 目录

新增 11 个单元测试(端到端 PNG 读写 + 各种异常分支)。1208 → 1219 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:46:27 +08:00
CodexandClaude Opus 4.7 cc164a192f refactor(fudai): 拆出保存详情成功 + 提取 future_ts(1556→1529,-27 行)
- save_first_read_detail_success:筛选通过后保存 detail + 标记 first_read + 写日志
- extract_future_ts_from_detail:从 detail 的 countdown_tuple 中提取 future_ts

新增 7 个单元测试,1201 → 1208 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:41:42 +08:00
CodexandClaude Opus 4.7 be95d9c279 refactor(fudai): 拆出 _handle_in_fudai_detail 入口诊断日志(1572→1556,-16 行)
log_entry_flags:进入 _handle_in_fudai_detail 时记录关键 flags 的诊断日志。

新增 2 个单元测试,1199 → 1201 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:38:23 +08:00
CodexandClaude Opus 4.7 1b4dc477fd refactor(fudai): 拆出阶段诊断 + stage 分发块(1652→1572,-80 行)
- diagnose_stage_with_logging:前置预日志 + _diagnose_stage_from_current_screen +
  缓存到 _last_diag_* + 写诊断结果日志
- dispatch_stage:根据 stage 分发到对应 handler,返回 bool 决定主流程是否 return

run_once_basic 主体只剩调用 + 早返回链。

新增 11 个单元测试覆盖各 stage 分支。1188 → 1199 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:34:56 +08:00
CodexandClaude Opus 4.7 47d31d34fd refactor(fudai): 拆出队列满等待 + 状态跳过日志(1704→1652,-52 行)
- handle_queue_full_wait_at_earliest:队列已满时回退到最早开奖直播间等待
- log_skip_reservation_check_for_state:等待开奖/参与预约/队列满三种状态下跳过日志

新增 7 个单元测试。1181 → 1188 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:31:15 +08:00
CodexandClaude Opus 4.7 9dee41b976 refactor(fudai): 拆出 fudai_choujiang 入口的 5 个子块(1879→1704,-175 行)
把 fudai_choujiang 中互相独立的初始化与循环子块抽到 fudai_run_blocks:
- cleanup_old_screenshot_at_startup:启动时清理旧截图
- resolve_device_resolution:分辨率重试(含默认回退)
- write_actions_log_separator:actions.log 分隔符写入
- run_basic_loop_with_timeout:定时循环模式
- run_basic_loop_forever:无限循环模式(含 KeyboardInterrupt 处理)

主入口从 237 行降到 ~60 行。新增 9 个单元测试覆盖各分支。
1172 → 1181 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:27:34 +08:00
CodexandClaude Opus 4.7 cdcabb665d refactor(fudai): 拆出步骤4参与成功善后处理(1939→1879,-60 行)
handle_attend_success_post_processing:参与决策成功后从 detail 提取倒计时、
设置等待开奖标志、调用预约善后/关闭详情/重置状态、写步骤4完成日志。

新增 5 个单元测试覆盖:join_result=False / 时间戳无变化 / 正常路径 /
remain_seconds=0 / detail 异常吞噬。1167 → 1172 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:24:02 +08:00
CodexandClaude Opus 4.7 9700813a33 refactor(fudai): 拆出高价值福袋"立即参与/记录预约"决策(2067→1939,-128 行)
把 _handle_in_fudai_detail 中"高价值福袋且 countdown_gt_*"的 130 行决策块抽到
fudai_detail_blocks.handle_high_value_skip_decide:
- 启用阈值检查 + 价值检查 + skip_reason 前缀检查
- 剩余秒数 ≤ join_ahead → return (False, False) 让外层走立即参与
- 剩余秒数 > join_ahead → 调用 basic_join_decision 记录预约后 return (True, True)
- 异常时 return (False, True) 让外层走默认筛选关闭路径

douyin_fudai.py 跌破 2000 行(1939)。

新增 7 个单元测试覆盖:未启用 / 价值不足 / 非倒计时 reason / 立即参与 /
记录预约 / join_decision 异常 / 外层异常吞噬。1160 → 1167 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:21:07 +08:00
CodexandClaude Opus 4.7 c75635f519 refactor(fudai): 拆出筛选不通过的关闭+切换块(2185→2067,-118 行)
把 _handle_in_fudai_detail 中"筛选不通过"分支(120 行 close + ADB swipe + cleanup)
抽到 fudai_detail_blocks.handle_filter_skip_close_and_switch。复用已有的
_force_swipe_to_next_live_with_adb_fallback 切换逻辑。

新增 3 个单元测试覆盖:切换 / 不切换 / close 异常吞噬。1157 → 1160 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:17:53 +08:00
CodexandClaude Opus 4.7 25c7a0440d refactor(fudai): 拆出"第二次打开福袋详情"分支(2318→2185,-133 行)
把 _handle_in_fudai_detail 中"is_second_open"分支(156 行)抽到
fudai_detail_blocks.handle_second_open_attend:
- 若 _fudai_detail_first_read=True 且有保存的详情数据:直接调用 attend_choujiang
- 参与成功重置计数器;失败累加;attend_result 写入完成日志
- 异常时返回 False 让主流程落到第一次打开路径

新增 5 个单元测试覆盖:非二次打开 / 无详情 fallthrough / 有效详情参与成功 /
参与失败计数 / attend 异常 fallthrough。1152 → 1157 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:15:01 +08:00
CodexandClaude Opus 4.7 03e509ac25 refactor(fudai): 拆出预约抢占调度块(2429→2318,-111 行)
execute_reservation_attend_or_cleanup:根据 needswitch 分支处理:
- 多间模式:调用 process_reservation_attend_window 抢占回退
- 单间模式:仅清理过期预约

新增 4 个单元测试覆盖正/负回报值、ref 同步、cleanup 异常吞噬。
1148 → 1152 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:11:29 +08:00
CodexandClaude Opus 4.7 28f91b2aaf refactor(fudai): 拆出 needswitch 诊断日志(2429→2390,-39 行)
把 run_once_basic 中"needswitch 配置 + 第一个预约详情"的诊断日志(48 行)
抽到 fudai_run_blocks.log_needswitch_check_details。纯日志辅助函数。

新增 2 个单元测试覆盖正常队列与空队列。1146 → 1148 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:08:07 +08:00
CodexandClaude Opus 4.7 970e9043cb refactor(fudai): 拆出"所有预约完成后重置到第一个直播间"块(2460→2429,-31 行)
handle_all_reservations_completed_reset:当队列满等待标志开启且队列已空时,
清除 focus + 按 room_pos 次数下滑回退到第一个直播间(最多 100 次防死循环)。

新增 5 个单元测试,1141 → 1146 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:05:18 +08:00
CodexandClaude Opus 4.7 c6a4d5fb99 refactor(fudai): 拆出预约队列状态文件写入(2545→2460,-85 行)
把 run_once_basic 中嵌套的 _write_state 闭包(87 行 JSON 写文件 + 节流)抽到
fudai_run_blocks.write_reservations_state_throttled。原闭包改为单行调用。

新增 3 个单元测试覆盖:1秒节流跳过 / 节流过后写入 / IO 错误吞噬。
1138 → 1141 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 03:02:45 +08:00
CodexandClaude Opus 4.7 a317b38b25 refactor(fudai): 拆出预约触发条件诊断日志(2602→2545,-57 行)
把 run_once_basic 中"预约触发条件诊断 + 跳过原因日志"的 60 行块抽到
fudai_run_blocks.log_reservation_trigger_check。纯日志辅助函数。

新增 4 个单元测试覆盖:disabled / 空队列 / 正常队列 / 超过 3 项截断。
1134 → 1138 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:59:35 +08:00
CodexandClaude Opus 4.7 3473e2bd5e refactor(fudai): 拆出 just_recorded_reservation + skip_stage_diagnosis 早返回(2661→2602,-59 行)
把 run_once_basic 中两个互相独立的早返回块抽到 fudai_run_blocks:
- handle_just_recorded_reservation:刚记录预约后按 needswitch 决定是否上滑切换
- handle_skip_stage_diagnosis:跳过阶段检测标志触发时直接查找福袋

新增 7 个单元测试,1127 → 1134 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:56:49 +08:00
CodexandClaude Opus 4.7 41fc4ecbe0 refactor(fudai): 拆出首次运行清空预约队列块(2783→2661,-122 行)
把 run_once_basic 中"首次运行清空预约队列与写空状态文件"的 130 行块抽到
fudai_run_blocks.maybe_clear_reservation_queue_on_first_run:
- 首次运行:清空 reservations / 写空状态文件 / 标记 _first_run_once_basic=False
- 非首次:仅记录日志保持当前队列

新增 4 个单元测试覆盖:首次清空 / 非首次保持 / 无 state_path 兜底 / 日志异常吞噬。
1123 → 1127 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:53:46 +08:00
CodexandClaude Opus 4.7 e6da24c2a6 refactor(fudai): 拆出截图重试块(2822→2783,-39 行)
把 run_once_basic 中 '截图 + 重试 + 失败诊断日志' 的 45 行块抽到
fudai_run_blocks.take_screenshot_with_retries:
- 失败时自动写入完整诊断日志(含 reservation flags / room_pos 等)
- 返回 (ok, elapsed);ok=False 时主流程直接 return

新增 4 个单元测试覆盖:首次成功 / 二次成功 / 全失败写诊断 / get_screenshot 抛错。
1119 → 1123 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:49:36 +08:00
CodexandClaude Opus 4.7 6cf3ce9a72 refactor(fudai): 拆出 IN_LIVE_ROOM + RECOMMEND_PAGE stage 处理(2915→2822,-93 行)
把 run_once_basic 中两个 stage 分支抽到 fudai_run_blocks:
- handle_in_live_room_stage:等待福袋加载(如刚切换)+ 查找福袋
- handle_recommend_page_stage:点击直播页 + 进入直播间(连点两次)

新增 5 个单元测试覆盖:刚切换 / 未切换 / 点击失败回退 / 完成日志。
1114 → 1119 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:46:21 +08:00
CodexandClaude Opus 4.7 992db1e161 refactor(fudai): 拆出 4 个 stage 弹窗/结束分支(2975→2915,-60 行)
把 run_once_basic 中 4 个 stage 分支抽到 fudai_run_blocks:
- handle_coupon_popup_stage:优惠券弹窗按返回键
- handle_shopping_redpacket_popup_stage:购物红包弹窗点击关闭
- handle_lottery_result_stage:开奖结果 OCR 识别 + 处理或回退
- handle_live_closed_stage:直播结束下滑切换

新增 7 个单元测试覆盖每个分支主路径 + 异常吞噬。1107 → 1114 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:43:10 +08:00
CodexandClaude Opus 4.7 1604ad1904 refactor(fudai): 拆出 FANSCLUB_JOIN stage 处理(3135→2975,-160 行)
把 run_once_basic 中 FANSCLUB_JOIN 分支(166 行)抽到
fudai_run_blocks.handle_fansclub_join_stage:
- 主路径:点参与按钮 + 2 次预设位置 + 关详情
- 异常路径:按 auto_join_fansclub 决定重试或等待 15s + 按 fansclub_fail_action 决定切换

douyin_fudai.py 终于跌破 3000 行(2975)。

新增 5 个单元测试覆盖:正常路径 / 自动加入重试 / 等待手动 / 失败切换 / 完成日志。
1102 → 1107 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:39:50 +08:00
CodexandClaude Opus 4.7 878a4c2fd9 refactor(fudai): 拆出锁定期跳过搜索块(3181→3135,-46 行)
把 _handle_live_room_has_or_not_fudai 中锁定期内时间窗口未到的早返回块抽到
fudai_detail_blocks.should_skip_search_in_lock_period:
- 检查 focus_until + queue_full_waiting + 队头预约时间窗口三者
- 若都满足跳过条件,记录日志后返回 True

新增 6 个单元测试覆盖各种边界(无锁定期 / 队列未满 / 队列空 / 窗口已开始 /
窗口未开始 / 无效 ft)。1096 → 1102 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:35:39 +08:00
CodexandClaude Opus 4.7 9c823f4874 refactor(fudai): 拆出参与成功后善后逻辑(3334→3181,-153 行)
把 _handle_in_fudai_detail 中参与成功分支的善后动作抽到 fudai_detail_blocks:
- handle_reservation_post_attend:清/延锁定期 + 移除完成的预约 + 重排队列
- close_detail_after_successful_attend:按 _detail_closed_by_attend 决定是否点返回键
- reset_fudai_detail_state_after_attend:清除 first_read / last_tuple / task_count 标志

主流程的参与成功分支从 ~180 行简化到 ~25 行。

新增 8 个单元测试覆盖:pending=False 跳过 / 无其他预约清 focus / 有其他预约设
保护期 / 移除已完成预约 / detail 已关闭跳过点返回 / 状态标志重置等。
1088 → 1096 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:32:39 +08:00
CodexandClaude Opus 4.7 c5f2bbee9c refactor(fudai): 拆出 task_count_zero 错误分支(3502→3334,-168 行)
把 _handle_in_fudai_detail 中 'last_status==error 且 reason==task_count_zero'
的 165 行处理逻辑抽到 fudai_detail_blocks.handle_task_count_zero_error:
- 累加 _fudai_detail_consecutive_failures 计数
- 第 3 次连续失败:关闭详情 + 强制切换直播间(含 ADB swipe 兜底)+ 重置计数
- 单次失败:清除任务数量标志后跳过本次

新增 6 个单元测试覆盖:第 1/3 次失败 / needswitch 开关 / status 不匹配 /
extra 不是 dict 等边界。1082 → 1088 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:26:18 +08:00
CodexandClaude Opus 4.7 17f1977a65 refactor(fudai): 抽出 _handle_in_fudai_detail 通用清理 + 状态分支(3632→3502,-130 行)
发现 _handle_in_fudai_detail 中有 4 个分支重复着同一套清理动作:
  '清除任务数量标志 → 写完成日志 → return'

抽出两个辅助函数到 fudai_detail_blocks:
- cleanup_and_log_completion:通用清理 + 完成日志(取代原 30+ 行重复代码块)
- handle_status_based_early_return:根据 _last_fudai_detail_status 分发到
  优惠券弹窗 / 观看任务 / 验证失败三个分支(error 分支因含 ADB 调用与计数
  逻辑较复杂,留在主流程)

应用到 4 处早返回:coupon_popup / watch_task / validation_failed / 验证失败 / 无效详情。

新增 9 个单元测试覆盖各分支与边界,1073 → 1082 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:22:16 +08:00
CodexandClaude Opus 4.7 2d971ca7d8 refactor(fudai): 拆出 _handle_in_fudai_detail 数据验证失败善后(3663→3632,-31 行)
handle_validation_failure_cleanup:步骤2 数据验证失败时关闭详情页 + 写日志 +
清除任务数量标志(与 detail_is_none 共享同一套清理动作)。

新增 2 个单元测试覆盖正常路径与 close 异常分支,1071 → 1073 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:18:08 +08:00
CodexandClaude Opus 4.7 b6cd3ac8a3 refactor(fudai): 拆出 _handle_in_fudai_detail 详情为None早返回(3687→3663,-24 行)
handle_detail_is_none:detail==None 时清除任务数量标志 + 写完成日志 + 早返回。
新增 3 个单元测试,1068 → 1071 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:15:30 +08:00
CodexandClaude Opus 4.7 18c6f7b025 refactor(fudai): 拆出 _handle_in_fudai_detail 失败计数子块(3732→3687,-45 行)
把 _handle_in_fudai_detail 中连续参与失败次数过多的早返回块抽到
fudai_detail_blocks.handle_too_many_consecutive_failures:
- 检查 _consecutive_attend_failures 是否超阈值
- 关闭详情页 → 按 needswitch 决定切换 → 重置计数器
- 返回 True 让主流程 return

新增 5 个单元测试覆盖阈值边界 / 切换开关 / 异常兜底,1063 → 1068 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:11:44 +08:00
CodexandClaude Opus 4.7 c7c6c51d20 refactor(reservation): 拆出 attend_window 计算+日志辅助(1437→1375,-62 行)
process_reservation_attend_window 中两个互不依赖的子块抽到 attend_window_helpers:
- compute_dynamic_ahead:根据回退步数 + 单步延迟动态计算提前进入参与窗口秒数(纯函数)
- log_attend_window_check_details:输出锁定期 / 时间窗口诊断结构化日志

新增 13 个单元测试覆盖各种边界(零步 / 截断 / 大延迟 / 异常兜底 / 锁定期内外)。
1050 → 1063 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:08:11 +08:00
CodexandClaude Opus 4.7 189d24255d refactor(stage): 拆出 douyin_stage 日志格式化辅助(1385→1284,-101 行)
diagnose_stage_from_current_screen 中并行检测后的详细日志记录块(108 行)
是纯日志格式化逻辑,依赖 pixel_state / pixel_details,不修改业务状态。
拆到 douyin_stage_helpers:
- _format_detail_log_fields:单 detail 字典 → 日志字段映射
- log_pixel_detection_details:遍历 pixel_details 写日志(含 has_fudai_detail
  的 task_count 矛盾告警)
- summarize_pixel_state:pixel_state 摘要写一行日志

新增 12 个单元测试覆盖纯函数行为,1038 → 1050 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 02:04:10 +08:00
CodexandClaude Opus 4.7 20e48d6a51 refactor(fudai): 拆出粉丝团门槛分支到独立模块(1629→577,-1052 行)
attend_choujiang 中加入粉丝团门槛分支占了 1057 行(520-1576),
内含 OCR 识别按钮位置 + 多次点击 + 详情页恢复递归等复杂逻辑。
该分支只依赖 analyser 和 attend_button_text 两个参数,自包含性强。

整段提取到 douyin/fudai/core/fudai_attend_fansclub.handle_fansclub_branch,
原方法只剩 elif 调用。粉丝团模块本身是 1075 行,但与其他分支解耦后
未来可针对粉丝团逻辑做独立优化、独立测试。

冒烟测试覆盖 import + 签名 + 公开 API,1034 → 1038 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 01:59:09 +08:00
CodexandClaude Opus 4.7 053ffa3469 refactor(gui): 拆出 mapping_table.py 5 个 UI 辅助子函数(659→482,-177 行)
mapping_table.create_mapping_tab 是单个 632 行的 tkinter 闭包巨型函数,
把其中相对独立的 5 个块抽到 mapping_table_helpers:
- open_entry_detail_window:弹出条目详情(原代码出现 2 次)
- compute_card_layout:根据画布宽度计算列数和卡片宽度
- set_card_bg:批量切换 widget + 子 widget 背景色
- make_card_event_handlers:单卡片的 click/dbl/enter/leave 处理器工厂
- render_card_labels:渲染单卡片内的 title + meta + body label

逻辑保持等价,只是提取闭包消除重复嵌套。新增 8 个单元测试覆盖
compute_card_layout / API 表面,1026 → 1034 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 01:51:52 +08:00
CodexandClaude Opus 4.7 9c1540b3ea refactor(detection): 删除 finder.py 中 502 行不可达死代码
check_have_fudai_with_ready_screenshot 在 936 行 `return False` 之后
仍有 938-1431 行的旧像素检测代码残留,由 AST 静态分析确认完全不可达
(早期重构时只加了新逻辑、没删旧逻辑造成的)。

仅删除死代码,无逻辑变更,1026 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 01:46:08 +08:00
CodexandClaude Opus 4.7 0bdc378252 refactor(fudai): 拆出 run_once_basic 4 个独立子块(4121→3732,-389 行)
把 run_once_basic 中互相独立的 4 个块抽到 fudai_run_blocks:
- handle_waiting_for_lottery_result(等待开奖期间的持续 OCR 检测)
- handle_no_attend_timeout(30 分钟未参与超时回到推荐页)
- handle_desktop_recovery(误返回桌面后的自救路径)
- handle_high_value_room_revisit(高价值房间重访检查)

每个函数返回 bool:True=主流程应 return,False=继续下一阶段。
原方法只剩调用 + 早返回,可读性大幅提升。

新增 13 个单元测试覆盖 4 个块的核心分支,1013 → 1026 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 01:40:23 +08:00
23 changed files with 11811 additions and 7301 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
+6
View File
@@ -10,6 +10,9 @@ from .fudai_popup_handler import PopupHandlerMixin
from .fudai_lottery_result import LotteryResultMixin
from .fudai_room_utils import RoomUtilsMixin
from .fudai_main_logic import MainLogicMixin
from . import fudai_run_blocks
from . import fudai_detail_blocks
from . import fudai_image_helpers
__all__ = [
"BaseFudaiMixin",
@@ -20,4 +23,7 @@ __all__ = [
"LotteryResultMixin",
"RoomUtilsMixin",
"MainLogicMixin",
"fudai_run_blocks",
"fudai_detail_blocks",
"fudai_image_helpers",
]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,279 @@
"""douyin_fudai 实例方法的辅助函数(图片/截图等)。
把 fudai_analyse 里相对独立的图片处理逻辑抽出来,便于单测与复用。
"""
from __future__ import annotations
import io
import logging
import os
import time
from typing import Any, Optional
from PIL import Image # type: ignore[import]
_LOGGER = logging.getLogger("douyin.core.fudai_modules.fudai_image_helpers")
def _read_screenshot_with_validation(
analyser: Any, pic_path: str, max_attempts: int = 6
) -> Optional[bytes]:
"""以原子方式读取截图字节,最多重试 max_attempts 次。
每次读取后用 PNG 头/IEND 尾 + PIL.verify 做基本校验,避免读到半写入文件。
返回完整字节,或 None(多次重试仍未读到完整文件)。
"""
data: Optional[bytes] = None
for _attempt in range(max_attempts):
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
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
if 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)
return data
def _open_image_or_retry(
analyser: Any, data: bytes, pic_path: str
) -> Optional[Image.Image]:
"""先用 data 解析图片;失败则尝试重新读取一次 pic_path 再解析。"""
from PIL import UnidentifiedImageError # type: ignore[import]
try:
img = Image.open(io.BytesIO(data))
img.load()
return img
except UnidentifiedImageError:
return None
except Exception:
pass
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 (
data2
and data2.startswith(b"\x89PNG")
and b"IEND" in data2[-512:]
):
try:
img = Image.open(io.BytesIO(data2))
img.load()
return img
except Exception:
return None
return None
except Exception:
return None
def capture_roi_screenshot(
analyser: Any,
label: str,
sx: int,
sy: int,
size: int,
screenshot_path: Optional[str] = None,
) -> str:
"""捕获以 (sx,sy) 为中心、边长为 size 的 ROI 截图,保存到 ``pic/`` 并返回路径。
返回 ROI 图片路径(绝对路径),失败返回空字符串。
"""
try:
from douyin.core import path_config
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 = _read_screenshot_with_validation(analyser, pic_path)
if not data:
return ""
img = _open_image_or_retry(analyser, data, pic_path)
if img is None:
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))
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 ""
def _correlation_score(a_flat, b_flat) -> float:
"""计算两个等长 1D 数组的归一化相关系数(去均值后点积/范数乘积)。"""
import numpy as np
a = a_flat - a_flat.mean()
b = b_flat - b_flat.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom <= 1e-6:
return -1.0
return float(np.dot(a, b) / denom)
def _sliding_search_best_score(roi_gray, tpl_gray) -> float:
"""以 step ≈ 模板边长 // 6 的步长在 ROI 中滑动搜索最佳相关系数。"""
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]
score = _correlation_score(window.flatten(), tpl_gray.flatten())
if score > best:
best = score
return best
def match_icon_template(
analyser: Any,
roi_path: str,
template_path: str,
threshold: Optional[float] = None,
):
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
threshold 不传时使用 analyser.yanghao_icon_match_threshold(默认 0.70)。
出错或文件缺失返回 (False, 0.0)。
"""
import numpy as np
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
roi_img = Image.open(roi_path).convert("RGB")
tpl_img = Image.open(template_path).convert("RGB")
rw, rh = roi_img.size
tw, th = tpl_img.size
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)
used_thr = (
float(threshold)
if threshold is not None
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
)
# 同尺寸:直接计算
if roi_gray.shape == tpl_gray.shape:
score = _correlation_score(roi_gray.flatten(), tpl_gray.flatten())
return bool(score >= used_thr), float(score)
# 模板小于 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]
score = _correlation_score(window.flatten(), tpl_gray.flatten())
if score >= 0.55:
return bool(score >= used_thr), float(score)
# 退回到滑动搜索
best = _sliding_search_best_score(roi_gray, tpl_gray)
if best < -0.5:
return False, 0.0
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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,547 @@
"""finder.py 的辅助函数:模板匹配兜底。
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"逻辑(226 行)
抽出来,便于独立测试与维护。
同时包含 numpy 加速像素扫描 + 逐像素扫描兜底的辅助函数。
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional
def numpy_pixel_scan(
analyser: Any,
pic_new: Any, # PIL.Image (RGBA)
rx: int,
ry: int,
width: int,
height: int,
y_pianyi_val: int,
optimal_x_scaled: int,
) -> tuple[bool, Optional[int]]:
"""先尝试 numpy 加速扫描水平带(性能优化:批量处理)。
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
"""
try:
import numpy as _np
y0 = 354 * ry // 2400 + y_pianyi_val
x1 = max(0, 157 * rx // 1080)
x2 = min(width, 410 * rx // 1080)
y_top = max(0, y0 - 3)
y_bottom = min(height, y0 + 4)
if not (x1 < x2 and y_top < y_bottom):
return False, None
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
)
except Exception:
pass
arr = _np.array(roi)
if arr.size == 0:
return False, None
r = arr[:, :, 0]
g = arr[:, :, 1]
b = arr[:, :, 2]
mask_center = (
(r >= 190) & (r <= 206)
& (g >= 173) & (g <= 196)
& (b >= 234) & (b <= 250)
)
cols = _np.sum(mask_center, axis=0)
valid_cols = cols >= 2
if not valid_cols.any():
return False, None
roi_width = x2 - x1
optimal_col = max(0, min(optimal_x_scaled - x1, roi_width - 1))
# 从最优位置开始,向左右两侧交替搜索
found_col = None
search_range = max(optimal_col, roi_width - optimal_col)
if valid_cols[optimal_col]:
found_col = optimal_col
else:
for offset in range(1, search_range + 1):
right_col = optimal_col + offset
if right_col < roi_width and valid_cols[right_col]:
found_col = right_col
break
left_col = optimal_col - offset
if left_col >= 0 and valid_cols[left_col]:
found_col = left_col
break
if found_col is None:
found_col = int(_np.argmax(valid_cols))
col_idx = found_col
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_last_success(
roi, operation_type="pixel_detect"
)
pic_rgb_full = pic_new.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=(x1, y_top, x2, y_bottom),
extra_info={
"detected_x": detected_x,
"detected_x_scaled": x1 + col_idx,
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
"resolution": f"{rx}x{ry}",
"result": "success",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x,
)
except Exception:
pass
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
def _is_target_pixel(px: Any) -> bool:
"""检查像素是否在目标颜色范围内。"""
if not (isinstance(px, tuple) and len(px) >= 3):
return False
return (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
)
def per_pixel_scan_fallback(
analyser: Any,
pic_new: Any,
rx: int,
ry: int,
y_pianyi_val: int,
) -> tuple[bool, Optional[int]]:
"""numpy 不可用或未命中时的逐像素扫描兜底。"""
try:
pix = pic_new.load()
pic_width, pic_height = pic_new.size
scan_x_start = 41 * rx // 1080
scan_x_end = min(410 * rx // 1080, pic_width)
scan_y = 403 * ry // 2400 + y_pianyi_val
try:
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
if (
last_fudai_x > 0
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
):
optimal_x_scaled = last_fudai_x * rx // 1080
else:
optimal_x_scaled = 169 * rx // 1080
except Exception:
optimal_x_scaled = 169 * rx // 1080
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
if not (0 <= scan_y < pic_height):
return False, None
for offset_y in [0, -1, 1, -2, 2]:
check_y = scan_y + offset_y
if not (0 <= check_y < pic_height):
continue
found_x = _scan_one_row(
pix, check_y, scan_x_start, scan_x_end, optimal_x_scaled
)
if found_x is not None:
detected_x = int(found_x * 1080.0 / max(1, rx))
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
_save_per_pixel_success(
analyser, pic_new, scan_x_start, scan_y, scan_x_end,
pic_height, detected_x, found_x, rx, ry,
)
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
return False, None
except Exception:
return False, None
def _scan_one_row(
pix: Any,
check_y: int,
scan_x_start: int,
scan_x_end: int,
optimal_x_scaled: int,
) -> Optional[int]:
"""在单行扫描目标像素:先查最优位置,然后左右交替,最后从左到右兜底。"""
# 先检查最优位置
try:
if _is_target_pixel(pix[optimal_x_scaled, check_y]):
return optimal_x_scaled
except (IndexError, TypeError):
pass
# 向左右两侧交替搜索
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
for offset in range(1, search_range + 1):
right_x = optimal_x_scaled + offset
if right_x < scan_x_end:
try:
if _is_target_pixel(pix[right_x, check_y]):
return right_x
except (IndexError, TypeError):
pass
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start:
try:
if _is_target_pixel(pix[left_x, check_y]):
return left_x
except (IndexError, TypeError):
pass
# 兜底:从左到右
for x_scaled in range(scan_x_start, scan_x_end):
try:
if _is_target_pixel(pix[x_scaled, check_y]):
return x_scaled
except (IndexError, TypeError):
continue
return None
def _save_per_pixel_success(
analyser: Any, pic_new: Any, scan_x_start: int, scan_y: int,
scan_x_end: int, pic_height: int, detected_x: int, found_x: int,
rx: int, ry: int,
) -> None:
try:
from douyin.handlers import douyin_screenshot_manager
detect_roi = pic_new.crop(
(scan_x_start, max(0, scan_y - 3), scan_x_end, min(pic_height, scan_y + 4))
).convert("RGB")
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect",
)
pic_rgb_full = pic_new.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=(
scan_x_start, max(0, scan_y - 3),
scan_x_end, min(pic_height, scan_y + 4),
),
extra_info={
"detected_x": detected_x,
"detected_x_scaled": found_x,
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"resolution": f"{rx}x{ry}",
"result": "success",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x,
)
except Exception:
pass
except Exception:
pass
def template_match_fallback(
analyser: Any,
pic_new: Any, # PIL.Image (RGBA)
rx: int,
ry: int,
width: int,
height: int,
y_pianyi_val: int,
loop: int,
) -> tuple[bool, Optional[int]]:
"""像素检测未命中时使用 OpenCV 模板匹配作为兜底。
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
"""
try:
import cv2
import numpy as np
# 获取模板路径
try:
from douyin.core import path_config
template_path = path_config.get_assets_dir() + "/fudai.png"
except Exception:
base_dir = os.path.dirname(os.path.abspath(__file__))
template_path = os.path.join(base_dir, "assets", "fudai.png")
if not os.path.exists(template_path):
return False, None
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 None:
return False, None
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 not (x1 < x2 and y_top < y_bottom):
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
return False, None
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2]
if search_roi.size <= 0:
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-搜索区域为空",
loop=loop,
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
截图尺寸=f"{width}x{height}",
)
except Exception:
pass
return False, None
th, tw = template.shape[:2]
rh, rw = search_roi.shape[:2]
# 保存搜索区域截图到 last_match.png(仅用于调试)
_save_last_match_debug(analyser, search_roi, loop, x1, x2, y_top, y_bottom, rw, rh)
# 如果模板太大,缩小模板
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 not (th <= rh and tw <= rw):
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
return False, None
# 执行模板匹配
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
_save_template_match_attempt_log(analyser, search_roi)
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:
return False, None
_save_template_match_success(analyser, search_roi)
# 命中:计算 1080 基准 x 坐标
detected_x_in_roi = max_loc[0]
detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx))
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
except Exception as e:
try:
analyser._log_kv(
"[找福袋图标] 模板匹配异常",
loop=loop,
错误类型=type(e).__name__,
错误信息=str(e),
)
except Exception:
pass
return False, None
def _save_last_match_debug(
analyser: Any, search_roi: Any, loop: int, x1: int, x2: int,
y_top: int, y_bottom: int, rw: int, rh: int,
) -> None:
try:
import cv2
base_dir = os.path.dirname(os.path.abspath(__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
def _save_template_match_attempt_log(analyser: Any, search_roi: Any) -> None:
"""保存"实时尝试"截图(双截图记录用)。"""
try:
import cv2
from PIL import Image as PILImage
from douyin.handlers import douyin_screenshot_manager
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
def _save_template_match_success(analyser: Any, search_roi: Any) -> None:
"""命中时保存成功识别存档截图。"""
try:
import cv2
from PIL import Image as PILImage
from douyin.handlers import douyin_screenshot_manager
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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+71 -780
View File
@@ -14,6 +14,15 @@ from douyin.fudai.core.coords import (
STAGE_RED_PACKET_OCR,
COUPON_PARTICIPATE_BUTTON_ALT,
)
from douyin.stage.douyin_stage_helpers import (
detect_lottery_result_popup,
detect_recommend_follow_live_tabs,
detect_redpacket_ocr_recheck_outside_live,
detect_shopping_redpacket_popup,
detect_suspicious_popup_via_ocr,
log_pixel_detection_details,
summarize_pixel_state,
)
# 模块级 logger:原代码用 print 输出阶段诊断起始信息,统一走 logging。
_LOGGER = logging.getLogger("douyin.stage.douyin_stage")
@@ -208,114 +217,9 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
)
# 记录每个检测步骤的详细信息
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_pixel_detection_details(pixel_details, analyser, _log)
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)),
)
summarize_pixel_state(pixel_state, pixel_detection_elapsed, _log)
except Exception as e:
import traceback
@@ -338,429 +242,37 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
# 购物红包像素命中:不在直播间也必须进行OCR复查
if pixel_state.get("has_redpacket_bg", False):
step_redpacket_ocr_start = time.time()
red_ratio = None
red_threshold = None
try:
redpacket_detail = (
pixel_details.get("has_redpacket_bg", {})
if isinstance(pixel_details, dict)
else {}
)
red_ratio = redpacket_detail.get("red_ratio")
red_threshold = redpacket_detail.get("effective_threshold")
except Exception:
red_ratio = None
red_threshold = None
_log(
"步骤2.5[购物红包OCR复查]-开始",
说明="不在直播间也执行红包OCR复查",
红色比例=(
round(float(red_ratio), 4) if red_ratio is not None else None
),
阈值=(
round(float(red_threshold), 4)
if red_threshold is not None
else None
),
)
redpacket_verified = False
try:
if time.time() - step_redpacket_ocr_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(
*SHOPPING_REDPACKET_AREA,
"",
"診斷購物紅包-非直播间复查",
)
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_redpacket_ocr_start < max_step_time:
ocr_start = time.time()
name_rp0 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
ocr_result = analyser.operation.analyse_pic_word(
name_rp0, 0, return_confidence=True
)
if isinstance(ocr_result, tuple):
redpacket_text, ocr_confidence_info = ocr_result
else:
redpacket_text = str(ocr_result or "")
ocr_confidence_info = None
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤2.5[购物红包OCR复查]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if enable_ocr_mode1 and (
not redpacket_text
or not any(
kw in redpacket_text for kw in redpacket_keywords
)
):
if time.time() - step_redpacket_ocr_start < max_step_time:
ocr_start_1 = time.time()
name_rp1 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
ocr_result_1 = analyser.operation.analyse_pic_word(
name_rp1, 1, return_confidence=True
)
if isinstance(ocr_result_1, tuple):
redpacket_text, ocr_confidence_info = ocr_result_1
else:
redpacket_text = str(ocr_result_1 or "")
ocr_confidence_info = None
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤2.5[购物红包OCR复查]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(redpacket_text),
文本预览=(
redpacket_text[:50] if redpacket_text else ""
),
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
# 检查关键词匹配或置信度阈值
has_keyword_match = redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
)
has_high_confidence = (
ocr_confidence_info
and ocr_confidence_info.get("max_confidence", 0)
>= analyser.shopping_redpacket_ocr_confidence_threshold
)
if has_keyword_match or has_high_confidence:
redpacket_verified = True
_log(
"步骤2.5[购物红包OCR复查]-命中",
关键词匹配=has_keyword_match,
高置信度匹配=has_high_confidence,
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
_log(
"步骤2.5[购物红包OCR复查]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
if redpacket_verified:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
_log_summary(
"阶段诊断完成(购物红包弹窗-非直播间复查)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(不在直播间)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
else:
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
_log("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
matched, stage, reason = detect_redpacket_ocr_recheck_outside_live(
analyser,
pixel_state,
pixel_details,
SHOPPING_REDPACKET_AREA,
diag_start,
max_step_time,
enable_ocr_mode1,
preprocess_for_ocr,
_log,
_log_summary,
)
if matched:
return stage, reason
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
matched, stage, reason = detect_recommend_follow_live_tabs(
analyser,
RECOMMEND_TAB,
FOLLOW_TAB,
LIVE_LIST_TAB,
diag_start,
max_step_time,
enable_ocr_mode1,
preprocess_for_ocr,
_log,
_log_summary,
_log_separator,
)
t_recommend = ""
t_follow = ""
t_list = ""
try:
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*RECOMMEND_TAB, "", "推荐页标签栏")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
t_recommend = str(
analyser.operation.analyse_pic_word(name0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_recommend),
文本预览=t_recommend[:50] if t_recommend else "",
)
if (
enable_ocr_mode1
and (time.time() - step_start < max_step_time)
and (
not t_recommend
or (
"推荐" not in t_recommend
and "关注" not in t_recommend
and "直播" not in t_recommend
)
)
):
ocr_start_1 = time.time()
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
t_recommend = str(
analyser.operation.analyse_pic_word(name1, 1) or ""
)
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_recommend),
文本预览=t_recommend[:50] if t_recommend else "",
)
elapsed_recommend = (time.time() - step_start) * 1000
# 如果识别到"推荐",直接返回推荐页面
if "推荐" in t_recommend:
total_elapsed = (time.time() - diag_start) * 1000
seen_text = t_recommend[:50] if t_recommend else "-"
_log(
"步骤3[OCR推荐页标签栏]-命中推荐",
耗时毫秒=elapsed_recommend,
总耗时毫秒=total_elapsed,
识别文本=seen_text,
)
_log_summary(
"阶段诊断完成",
阶段="RECOMMEND_PAGE",
原因=f"标题='{t_recommend}'",
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:RECOMMEND_PAGE(推荐页)")
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果识别到"关注"但没有"推荐",可能是关注列表
if "关注" in t_recommend and "推荐" not in t_recommend:
_log(
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
精确区域="(658,147)-(765,194)",
)
step_start_follow = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
t_follow = str(
analyser.operation.analyse_pic_word(namef0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
if (
enable_ocr_mode1
and (time.time() - step_start < max_step_time)
and ("关注" not in t_follow)
):
ocr_start_1 = time.time()
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
t_follow = str(
analyser.operation.analyse_pic_word(namef1, 1) or ""
)
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
except Exception as e:
import traceback
_log(
"步骤3[OCR关注列表]-异常",
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
elapsed_follow = (time.time() - step_start_follow) * 1000
if "关注" in t_follow:
total_elapsed = (time.time() - diag_start) * 1000
follow_text = t_follow[:50] if t_follow else "-"
_log(
"步骤3[OCR关注列表]-命中",
耗时毫秒=elapsed_follow,
总耗时毫秒=total_elapsed,
识别文本=follow_text,
)
try:
analyser._last_follow_list_title_text = str(
t_follow or ""
).strip()
except Exception:
analyser._last_follow_list_title_text = ""
_log_summary(
"阶段诊断完成",
阶段="FOLLOW_LIST",
原因=f"标题='{t_follow}'",
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:FOLLOW_LIST(关注列表)")
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
# 如果识别到"正在直播"标签,判定为直播列表
if "正在直播" in t_recommend or (
"直播" in t_recommend
and "推荐" not in t_recommend
and "关注" not in t_recommend
):
_log(
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
精确区域="(650,145)-(800,195)",
)
step_start_list = time.time()
try:
ocr_start = time.time() # 初始化ocr_start
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
# else分支不需要,因为ocr_start已经在上面初始化了
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR直播列表]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
if (
enable_ocr_mode1
and (time.time() - step_start < max_step_time)
and ("正在直播" not in t_list)
):
ocr_start_1 = time.time()
namel1 = preprocess_for_ocr(analyser, "直播列表标签")
t_list = str(
analyser.operation.analyse_pic_word(namel1, 1) or ""
)
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR直播列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
except Exception as e:
import traceback
_log(
"步骤3[OCR直播列表]-异常",
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
elapsed_list = (time.time() - step_start_list) * 1000
if "正在直播" in t_list:
total_elapsed = (time.time() - diag_start) * 1000
list_text = t_list[:50] if t_list else "-"
_log(
"步骤3[OCR直播列表]-命中",
耗时毫秒=elapsed_list,
总耗时毫秒=total_elapsed,
识别文本=list_text,
)
_log_summary(
"阶段诊断完成",
阶段="LIVE_LIST",
原因=f"标题='{t_list}'",
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:LIVE_LIST(直播列表)")
return "LIVE_LIST", "标题='{}'".format(t_list)
# 记录诊断时看到的"关注页标题"
try:
analyser._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
analyser._last_follow_list_title_text = ""
elapsed_total = (time.time() - step_start) * 1000
if elapsed_total > max_step_time * 1000:
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
耗时毫秒=elapsed_total,
阈值毫秒=max_step_time * 1000,
)
else:
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
耗时毫秒=elapsed_total,
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
)
except Exception as e:
elapsed_total = (time.time() - step_start) * 1000
import traceback
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
耗时毫秒=elapsed_total,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
# 步骤3结束计时
step3_elapsed = (time.time() - step_start) * 1000
_log("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
if matched:
return stage, reason
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
@@ -782,109 +294,27 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
# 优先级1:抽奖结果弹窗(像素检测 + 按钮OCR确认)
if pixel_state.get("has_lucky_draw_result", False):
step1_start = time.time()
_log_separator("步骤1:检测抽奖结果弹窗(简化)")
try:
from douyin.utils.douyin_helpers import HelperFunctions
detected = HelperFunctions.check_lottery_result_by_ocr(analyser)
if detected:
total_elapsed = (time.time() - diag_start) * 1000
_log_summary(
"阶段诊断完成(抽奖结果弹窗)",
阶段="FUDai_RESULT",
原因="像素检测+按钮OCR确认",
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:FUDai_RESULT(抽奖结果弹窗)")
return "FUDai_RESULT", "像素检测+按钮OCR确认"
else:
_log("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测")
except Exception as e:
_log(
"步骤1[检测抽奖结果弹窗]-简化OCR异常",
异常类型=type(e).__name__,
异常信息=str(e),
)
# 步骤1结束计时
step1_elapsed = (time.time() - step1_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed)
matched, stage, reason = detect_lottery_result_popup(
analyser, diag_start, _log, _log_summary, _log_separator
)
if matched:
return stage, reason
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
if pixel_state.get("has_redpacket_bg", False):
_log_separator("步骤1.5:检测购物红包弹窗")
step_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log(
"步骤1.5[检测购物红包弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到购物红包背景",
matched, stage, reason = detect_shopping_redpacket_popup(
analyser,
SHOPPING_REDPACKET_AREA,
diag_start,
max_diag_time,
max_step_time,
preprocess_for_ocr,
_log,
_log_summary,
_log_separator,
)
redpacket_detected = False
try:
if time.time() - step_redpacket_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_redpacket_start < max_step_time:
ocr_start = time.time()
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1.5[检测购物红包弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
# 检查是否包含购物红包关键词
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
redpacket_detected = True
else:
# OCR未识别到关键词,不判定为购物红包弹窗(以OCR为准)
_log(
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
说明="OCR未匹配,不判定为购物红包弹窗",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log(
"步骤1.5[检测购物红包弹窗]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
_log(
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
说明="需要OCR确认才能判定",
)
if redpacket_detected:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log_summary(
"阶段诊断完成(购物红包弹窗)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="检测到购物红包弹窗",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
# 步骤1.5结束计时
step15_elapsed = (time.time() - step_redpacket_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed)
if matched:
return stage, reason
# ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)==========
step1_fudai_start = time.time()
@@ -1202,160 +632,21 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
has_suspicious_popup_pixel = pixel_state.get(
"has_coupon_bg", False
) or pixel_state.get("has_redpacket_bg", False)
if has_suspicious_popup_pixel:
step_ocr_verify_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log(
"步骤3[OCR确认弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
)
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
if pixel_state.get("has_coupon_bg", False):
coupon_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start < max_step_time:
ocr_start = time.time()
# 如果启用模式1,并行执行两个OCR模式
if enable_ocr_mode1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
future_mode0 = executor.submit(
analyser.operation.analyse_pic_word, name_part0, 0
)
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
future_mode1 = executor.submit(
analyser.operation.analyse_pic_word, name_part1, 1
)
text_mode0 = str(future_mode0.result() or "")
text_mode1 = str(future_mode1.result() or "")
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
if text_mode0 and "开心收下" in text_mode0:
coupon_text = text_mode0
elif text_mode1 and "开心收下" in text_mode1:
coupon_text = text_mode1
elif text_mode0:
coupon_text = text_mode0
else:
coupon_text = text_mode1
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
else:
pname = preprocess_for_ocr(analyser, "参与按钮")
coupon_text = str(
analyser.operation.analyse_pic_word(pname, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
if coupon_text and "开心收下" in coupon_text:
coupon_verified = True
except Exception as e:
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券异常",
耗时毫秒=coupon_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
if coupon_verified:
total_elapsed = (time.time() - diag_start) * 1000
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log_summary(
"阶段诊断完成(优惠券弹窗-OCR确认)",
阶段="COUPON_POPUP",
原因="像素检测到背景+OCR确认(开心收下)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
return "COUPON_POPUP", "OCR确认(开心收下)"
# 检测购物红包弹窗
if pixel_state.get("has_redpacket_bg", False):
redpacket_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start < max_step_time:
ocr_start = time.time()
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp2, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
redpacket_verified = True
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log(
"步骤3[OCR确认弹窗]-购物红包异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
if redpacket_verified:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log_summary(
"阶段诊断完成(购物红包弹窗-OCR确认)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(购物红包)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log(
"步骤3[OCR确认弹窗]-未匹配到弹窗",
耗时毫秒=ocr_verify_elapsed,
说明="OCR确认后未匹配,判定为直播间背景颜色",
)
# 步骤3结束计时(OCR确认弹窗)
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
matched, stage, reason = detect_suspicious_popup_via_ocr(
analyser,
pixel_state,
COUPON_PARTICIPATE_BUTTON_ALT,
SHOPPING_REDPACKET_AREA,
diag_start,
max_diag_time,
max_step_time,
enable_ocr_mode1,
preprocess_for_ocr,
_log,
_log_summary,
)
if matched:
return stage, reason
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
if in_live_room:
+930
View File
@@ -0,0 +1,930 @@
"""douyin_stage.py 内部用到的辅助函数。
把 diagnose_stage_from_current_screen 中纯日志格式化、纯映射查询的子块抽出来:
- log_pixel_detection_details:把 pixel_details 里每个 key 的检测详情格式化并写入日志
- summarize_pixel_state:把 pixel_state 摘要写入日志(一次调用替代 9 行字段构造)
"""
from __future__ import annotations
from typing import Any, Callable, Dict
_STEP_NAME_MAP: Dict[str, str] = {
"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": "直播间图标(像素检测-多边形区域白色像素)",
}
def _format_detail_log_fields(key: str, detail: Dict[str, Any], analyser: Any) -> Dict[str, Any]:
"""把单个 detail 字典格式化成日志字段。"""
step_name = _STEP_NAME_MAP.get(key, key)
detected = detail.get("detected", False)
method = detail.get("method", "unknown")
log_fields: Dict[str, Any] = {
"步骤": 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"]
if threshold_val is not None:
log_fields["阈值"] = round(threshold_val, 4)
else:
log_fields["阈值"] = "未设置"
if key == "has_fudai_detail":
if "task_count" in detail:
log_fields["任务数量"] = detail["task_count"]
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"]
return log_fields
def _ocr_with_dual_modes(
analyser: Any,
crop_name: str,
preprocess_for_ocr: Callable[[Any, str], str],
enable_ocr_mode1: bool,
step_start: float,
max_step_time: float,
keywords_for_mode1: tuple,
log_callback: Callable[..., None],
log_prefix: str,
) -> str:
"""对已经裁剪好的图片做双 OCR(mode 0 + 可选 mode 1)。
若 mode 0 文本含 ``keywords_for_mode1`` 中任意一个关键词,则不再跑 mode 1。
返回 OCR 文本(mode 1 优先,缺失时退到 mode 0)。
"""
import time
if time.time() - step_start >= max_step_time:
return ""
ocr_start = time.time()
name0 = preprocess_for_ocr(analyser, crop_name)
text = str(analyser.operation.analyse_pic_word(name0, 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
log_callback(
f"{log_prefix}-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(text),
文本预览=text[:50] if text else "",
)
# 是否需要 mode 1:mode 0 没匹配到任意关键词
needs_mode1 = enable_ocr_mode1 and (
time.time() - step_start < max_step_time
) and (
not text or not any(kw in text for kw in keywords_for_mode1)
)
if needs_mode1:
ocr_start_1 = time.time()
name1 = preprocess_for_ocr(analyser, crop_name)
text = str(analyser.operation.analyse_pic_word(name1, 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
log_callback(
f"{log_prefix}-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(text),
文本预览=text[:50] if text else "",
)
return text
def _detect_coupon_popup_via_ocr(
analyser: Any,
coupon_button_area: tuple,
step_ocr_verify_start: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable[[Any, str], str],
log_callback: Callable[..., None],
) -> bool:
"""OCR 确认优惠券弹窗("开心收下" 关键词)。返回是否命中。"""
import time
coupon_verified = False
try:
if time.time() - step_ocr_verify_start >= max_step_time:
return False
cut_start = time.time()
analyser.cut_pic(*coupon_button_area, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
log_callback("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start >= max_step_time:
return False
ocr_start = time.time()
if enable_ocr_mode1:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
future_mode0 = executor.submit(
analyser.operation.analyse_pic_word, name_part0, 0
)
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
future_mode1 = executor.submit(
analyser.operation.analyse_pic_word, name_part1, 1
)
text_mode0 = str(future_mode0.result() or "")
text_mode1 = str(future_mode1.result() or "")
if text_mode0 and "开心收下" in text_mode0:
coupon_text = text_mode0
elif text_mode1 and "开心收下" in text_mode1:
coupon_text = text_mode1
elif text_mode0:
coupon_text = text_mode0
else:
coupon_text = text_mode1
ocr_elapsed = (time.time() - ocr_start) * 1000
log_callback(
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
else:
pname = preprocess_for_ocr(analyser, "参与按钮")
coupon_text = str(analyser.operation.analyse_pic_word(pname, 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
log_callback(
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
if coupon_text and "开心收下" in coupon_text:
coupon_verified = True
except Exception as e:
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
log_callback(
"步骤3[OCR确认弹窗]-优惠券异常",
耗时毫秒=coupon_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
return coupon_verified
def _detect_redpacket_popup_via_ocr_simple(
analyser: Any,
shopping_redpacket_area: tuple,
step_ocr_verify_start: float,
max_step_time: float,
preprocess_for_ocr: Callable[[Any, str], str],
log_callback: Callable[..., None],
) -> bool:
"""OCR 简单确认购物红包弹窗(仅 mode 0)。返回是否命中。"""
import time
redpacket_verified = False
try:
if time.time() - step_ocr_verify_start >= max_step_time:
return False
cut_start = time.time()
analyser.cut_pic(*shopping_redpacket_area, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
log_callback("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start >= max_step_time:
return False
ocr_start = time.time()
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
redpacket_text = str(analyser.operation.analyse_pic_word(name_rp2, 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
log_callback(
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
redpacket_verified = True
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
log_callback(
"步骤3[OCR确认弹窗]-购物红包异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
return redpacket_verified
def detect_suspicious_popup_via_ocr(
analyser: Any,
pixel_state: Dict[str, Any],
coupon_button_area: tuple,
shopping_redpacket_area: tuple,
diag_start: float,
max_diag_time: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable[[Any, str], str],
log_callback: Callable[..., None],
log_summary_callback: Callable[..., None],
) -> tuple[bool, str, str]:
"""像素检测到弹窗背景但未匹配到弹窗阶段时,OCR 二次确认。
返回 (matched, stage, reason)。matched=True 时主流程应直接 return。
"""
import time
has_suspicious_popup_pixel = pixel_state.get(
"has_coupon_bg", False
) or pixel_state.get("has_redpacket_bg", False)
if not has_suspicious_popup_pixel:
return False, "", ""
step_ocr_verify_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
log_callback(
"步骤3[OCR确认弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
)
# 优惠券弹窗确认
if pixel_state.get("has_coupon_bg", False):
if _detect_coupon_popup_via_ocr(
analyser, coupon_button_area, step_ocr_verify_start,
max_step_time, enable_ocr_mode1, preprocess_for_ocr, log_callback,
):
total_elapsed = (time.time() - diag_start) * 1000
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
log_summary_callback(
"阶段诊断完成(优惠券弹窗-OCR确认)",
阶段="COUPON_POPUP",
原因="像素检测到背景+OCR确认(开心收下)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
return True, "COUPON_POPUP", "OCR确认(开心收下)"
# 购物红包弹窗确认
if pixel_state.get("has_redpacket_bg", False):
if _detect_redpacket_popup_via_ocr_simple(
analyser, shopping_redpacket_area, step_ocr_verify_start,
max_step_time, preprocess_for_ocr, log_callback,
):
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
log_summary_callback(
"阶段诊断完成(购物红包弹窗-OCR确认)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(购物红包)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return True, "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
log_callback(
"步骤3[OCR确认弹窗]-未匹配到弹窗",
耗时毫秒=ocr_verify_elapsed,
说明="OCR确认后未匹配,判定为直播间背景颜色",
)
log_callback(
"步骤3[OCR确认弹窗]-完成", 总耗时毫秒=ocr_verify_elapsed
)
return False, "", ""
def detect_recommend_follow_live_tabs(
analyser: Any,
recommend_tab_area: tuple,
follow_tab_area: tuple,
live_list_tab_area: tuple,
diag_start: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable[[Any, str], str],
log_callback: Callable[..., None],
log_summary_callback: Callable[..., None],
log_separator_callback: Callable[..., None],
) -> tuple[bool, str, str]:
"""步骤3:OCR 检测推荐页/关注列表/直播列表标签栏。
返回 (matched, stage, reason):matched=True 时主流程应直接 return。
matched=False 表示三个标签都没命中(main flow 会回退到默认 IN_LIVE_ROOM)。
"""
import time
step_start = time.time()
remaining_time_before = float("inf") # 这里不强制超出 diag 时间限制
log_callback(
"步骤3[OCR推荐页/关注列表/直播列表]-开始",
剩余时间秒=remaining_time_before,
)
t_recommend = ""
t_follow = ""
t_list = ""
try:
# 推荐页标签栏
log_callback("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*recommend_tab_area, "", "推荐页标签栏")
cut_elapsed = (time.time() - cut_start) * 1000
log_callback("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
t_recommend = _ocr_with_dual_modes(
analyser, "推荐页标签栏",
preprocess_for_ocr, enable_ocr_mode1,
step_start, max_step_time,
keywords_for_mode1=("推荐", "关注", "直播"),
log_callback=log_callback,
log_prefix="步骤3[OCR推荐页标签栏]",
)
elapsed_recommend = (time.time() - step_start) * 1000
if "推荐" in t_recommend:
total_elapsed = (time.time() - diag_start) * 1000
seen_text = t_recommend[:50] if t_recommend else "-"
log_callback(
"步骤3[OCR推荐页标签栏]-命中推荐",
耗时毫秒=elapsed_recommend,
总耗时毫秒=total_elapsed,
识别文本=seen_text,
)
log_summary_callback(
"阶段诊断完成",
阶段="RECOMMEND_PAGE",
原因=f"标题='{t_recommend}'",
总耗时毫秒=total_elapsed,
)
log_separator_callback("最终结果:RECOMMEND_PAGE(推荐页)")
return True, "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 关注列表
if "关注" in t_recommend and "推荐" not in t_recommend:
log_callback(
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
精确区域="(658,147)-(765,194)",
)
step_start_follow = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*follow_tab_area, "", "关注列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
log_callback("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
t_follow = _ocr_with_dual_modes(
analyser, "关注列表标签",
preprocess_for_ocr, enable_ocr_mode1,
step_start, max_step_time,
keywords_for_mode1=("关注",),
log_callback=log_callback,
log_prefix="步骤3[OCR关注列表]",
)
except Exception as e:
import traceback
log_callback(
"步骤3[OCR关注列表]-异常",
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
elapsed_follow = (time.time() - step_start_follow) * 1000
if "关注" in t_follow:
total_elapsed = (time.time() - diag_start) * 1000
follow_text = t_follow[:50] if t_follow else "-"
log_callback(
"步骤3[OCR关注列表]-命中",
耗时毫秒=elapsed_follow,
总耗时毫秒=total_elapsed,
识别文本=follow_text,
)
try:
analyser._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
analyser._last_follow_list_title_text = ""
log_summary_callback(
"阶段诊断完成",
阶段="FOLLOW_LIST",
原因=f"标题='{t_follow}'",
总耗时毫秒=total_elapsed,
)
log_separator_callback("最终结果:FOLLOW_LIST(关注列表)")
return True, "FOLLOW_LIST", "标题='{}'".format(t_follow)
# 直播列表
if "正在直播" in t_recommend or (
"直播" in t_recommend
and "推荐" not in t_recommend
and "关注" not in t_recommend
):
log_callback(
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
精确区域="(650,145)-(800,195)",
)
step_start_list = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*live_list_tab_area, "", "直播列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
log_callback(
"步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed
)
t_list = _ocr_with_dual_modes(
analyser, "直播列表标签",
preprocess_for_ocr, enable_ocr_mode1,
step_start, max_step_time,
keywords_for_mode1=("正在直播",),
log_callback=log_callback,
log_prefix="步骤3[OCR直播列表]",
)
except Exception as e:
import traceback
log_callback(
"步骤3[OCR直播列表]-异常",
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
elapsed_list = (time.time() - step_start_list) * 1000
if "正在直播" in t_list:
total_elapsed = (time.time() - diag_start) * 1000
list_text = t_list[:50] if t_list else "-"
log_callback(
"步骤3[OCR直播列表]-命中",
耗时毫秒=elapsed_list,
总耗时毫秒=total_elapsed,
识别文本=list_text,
)
log_summary_callback(
"阶段诊断完成",
阶段="LIVE_LIST",
原因=f"标题='{t_list}'",
总耗时毫秒=total_elapsed,
)
log_separator_callback("最终结果:LIVE_LIST(直播列表)")
return True, "LIVE_LIST", "标题='{}'".format(t_list)
# 记录诊断时看到的"关注页标题"
try:
analyser._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
analyser._last_follow_list_title_text = ""
elapsed_total = (time.time() - step_start) * 1000
if elapsed_total > max_step_time * 1000:
log_callback(
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
耗时毫秒=elapsed_total,
阈值毫秒=max_step_time * 1000,
)
else:
log_callback(
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
耗时毫秒=elapsed_total,
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
)
except Exception as e:
elapsed_total = (time.time() - step_start) * 1000
import traceback
log_callback(
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
耗时毫秒=elapsed_total,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
step3_elapsed = (time.time() - step_start) * 1000
log_callback("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
return False, "", ""
def detect_redpacket_ocr_recheck_outside_live(
analyser: Any,
pixel_state: Dict[str, Any],
pixel_details: Dict[str, Any],
shopping_redpacket_area: tuple,
diag_start: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable[[Any, str], str],
log_callback: Callable[..., None],
log_summary_callback: Callable[..., None],
) -> tuple[bool, str, str]:
"""步骤2.5:不在直播间时的"购物红包"像素 + OCR 复查(含 mode0 / mode1 双 OCR + 置信度兜底)。
若 ``pixel_state.has_redpacket_bg`` 为 False,直接返回 (False, "", "")。
返回 (matched, stage, reason):matched=True 时主流程应直接 return。
"""
import time
if not pixel_state.get("has_redpacket_bg", False):
return False, "", ""
step_redpacket_ocr_start = time.time()
red_ratio = None
red_threshold = None
try:
redpacket_detail = (
pixel_details.get("has_redpacket_bg", {})
if isinstance(pixel_details, dict)
else {}
)
red_ratio = redpacket_detail.get("red_ratio")
red_threshold = redpacket_detail.get("effective_threshold")
except Exception:
red_ratio = None
red_threshold = None
log_callback(
"步骤2.5[购物红包OCR复查]-开始",
说明="不在直播间也执行红包OCR复查",
红色比例=(
round(float(red_ratio), 4) if red_ratio is not None else None
),
阈值=(
round(float(red_threshold), 4)
if red_threshold is not None
else None
),
)
redpacket_verified = False
try:
if time.time() - step_redpacket_ocr_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(
*shopping_redpacket_area,
"",
"診斷購物紅包-非直播间复查",
)
cut_elapsed = (time.time() - cut_start) * 1000
log_callback(
"步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed
)
if time.time() - step_redpacket_ocr_start < max_step_time:
ocr_start = time.time()
name_rp0 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
ocr_result = analyser.operation.analyse_pic_word(
name_rp0, 0, return_confidence=True
)
if isinstance(ocr_result, tuple):
redpacket_text, ocr_confidence_info = ocr_result
else:
redpacket_text = str(ocr_result or "")
ocr_confidence_info = None
ocr_elapsed = (time.time() - ocr_start) * 1000
log_callback(
"步骤2.5[购物红包OCR复查]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if enable_ocr_mode1 and (
not redpacket_text
or not any(
kw in redpacket_text for kw in redpacket_keywords
)
):
if time.time() - step_redpacket_ocr_start < max_step_time:
ocr_start_1 = time.time()
name_rp1 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
ocr_result_1 = analyser.operation.analyse_pic_word(
name_rp1, 1, return_confidence=True
)
if isinstance(ocr_result_1, tuple):
redpacket_text, ocr_confidence_info = ocr_result_1
else:
redpacket_text = str(ocr_result_1 or "")
ocr_confidence_info = None
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
log_callback(
"步骤2.5[购物红包OCR复查]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(redpacket_text),
文本预览=(
redpacket_text[:50] if redpacket_text else ""
),
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
has_keyword_match = redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
)
has_high_confidence = (
ocr_confidence_info
and ocr_confidence_info.get("max_confidence", 0)
>= analyser.shopping_redpacket_ocr_confidence_threshold
)
if has_keyword_match or has_high_confidence:
redpacket_verified = True
log_callback(
"步骤2.5[购物红包OCR复查]-命中",
关键词匹配=has_keyword_match,
高置信度匹配=has_high_confidence,
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
log_callback(
"步骤2.5[购物红包OCR复查]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
if redpacket_verified:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
log_summary_callback(
"阶段诊断完成(购物红包弹窗-非直播间复查)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(不在直播间)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return True, "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
log_callback("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
return False, "", ""
def detect_lottery_result_popup(
analyser: Any,
diag_start: float,
log_callback: Callable[..., None],
log_summary_callback: Callable[..., None],
log_separator_callback: Callable[..., None],
) -> tuple[bool, str, str]:
"""优先级1:通过 OCR 确认抽奖结果弹窗。
返回 (matched, stage, reason):
- matched=True:已确认是 FUDai_RESULT,主流程应直接 return (stage, reason)
- matched=False:继续后续检测
"""
import time
step1_start = time.time()
log_separator_callback("步骤1:检测抽奖结果弹窗(简化)")
try:
from douyin.utils.douyin_helpers import HelperFunctions
detected = HelperFunctions.check_lottery_result_by_ocr(analyser)
if detected:
total_elapsed = (time.time() - diag_start) * 1000
log_summary_callback(
"阶段诊断完成(抽奖结果弹窗)",
阶段="FUDai_RESULT",
原因="像素检测+按钮OCR确认",
总耗时毫秒=total_elapsed,
)
log_separator_callback("最终结果:FUDai_RESULT(抽奖结果弹窗)")
return True, "FUDai_RESULT", "像素检测+按钮OCR确认"
else:
log_callback("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测")
except Exception as e:
log_callback(
"步骤1[检测抽奖结果弹窗]-简化OCR异常",
异常类型=type(e).__name__,
异常信息=str(e),
)
step1_elapsed = (time.time() - step1_start) * 1000
log_callback("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed)
return False, "", ""
def detect_shopping_redpacket_popup(
analyser: Any,
shopping_redpacket_area: tuple,
diag_start: float,
max_diag_time: float,
max_step_time: float,
preprocess_for_ocr: Callable[[Any, str], str],
log_callback: Callable[..., None],
log_summary_callback: Callable[..., None],
log_separator_callback: Callable[..., None],
) -> tuple[bool, str, str]:
"""优先级1.5:通过 OCR 确认购物红包弹窗。
返回 (matched, stage, reason)。
"""
import time
log_separator_callback("步骤1.5:检测购物红包弹窗")
step_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
log_callback(
"步骤1.5[检测购物红包弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到购物红包背景",
)
redpacket_detected = False
try:
if time.time() - step_redpacket_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*shopping_redpacket_area, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
log_callback("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_redpacket_start < max_step_time:
ocr_start = time.time()
name_rp = preprocess_for_ocr(analyser, "診斷購物紅包")
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
log_callback(
"步骤1.5[检测购物红包弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
redpacket_detected = True
else:
log_callback(
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
说明="OCR未匹配,不判定为购物红包弹窗",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
log_callback(
"步骤1.5[检测购物红包弹窗]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
log_callback(
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
说明="需要OCR确认才能判定",
)
if redpacket_detected:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
log_summary_callback(
"阶段诊断完成(购物红包弹窗)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="检测到购物红包弹窗",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return True, "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
step15_elapsed = (time.time() - step_redpacket_start) * 1000
log_callback("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed)
return False, "", ""
def log_pixel_detection_details(
pixel_details: Dict[str, Dict[str, Any]],
analyser: Any,
log_callback: Callable[..., None],
) -> None:
"""记录并行像素检测每个步骤的详细日志。"""
for key, detail in (pixel_details or {}).items():
log_fields = _format_detail_log_fields(key, detail, analyser)
# has_fudai_detail 单独保留任务数量与 detected 矛盾的告警分支
if key == "has_fudai_detail":
task_count_val = detail.get("task_count")
detected = detail.get("detected", False)
if (
task_count_val is not None
and task_count_val > 0
and not detected
):
try:
log_callback(
"警告:检测到任务数量但 has_fudai_detail 为 False",
任务数量=task_count_val,
detected=detected,
)
except Exception:
pass
step_name = _STEP_NAME_MAP.get(key, key)
try:
log_callback(f"并行检测-{step_name}", **log_fields)
except Exception:
pass
def summarize_pixel_state(
pixel_state: Dict[str, Any],
pixel_detection_elapsed_ms: float,
log_callback: Callable[..., None],
) -> None:
"""把 pixel_state 摘要写到日志,方便排查命中/未命中分布。"""
try:
log_callback(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed_ms,
直播间图标像素检测=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:
pass
+30 -207
View File
@@ -14,6 +14,11 @@ except Exception:
except Exception:
mapping_utils = None
try:
from . import mapping_table_helpers as _mt_helpers
except Exception:
import gui.components.mapping_table_helpers as _mt_helpers
try:
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
@@ -278,14 +283,8 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
canvas_w = canvas.winfo_width() or 800
except Exception:
canvas_w = 800
min_card_w = 300
columns, col_width = _mt_helpers.compute_card_layout(canvas_w)
h_gap = 12
try:
columns = max(1, int((canvas_w + h_gap) / (min_card_w + h_gap)))
except Exception:
columns = 1
# 限制最大列数以避免过窄(可根据实际需求调整)
columns = min(columns, 3)
# 配置列权重
try:
@@ -326,88 +325,18 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
except Exception:
pass
# 计算每列可用宽度用于 wraplength
try:
col_total_gap = columns * 12
col_width = max(220, int((canvas_w - col_total_gap) / columns))
card_wraplen = max(160, col_width - 40)
except Exception:
card_wraplen = wraplen
# 标题行(紧凑)
try:
lbl_title = tk.Label(
card,
text=lines[0],
font=title_font,
bg=normal_bg,
fg="#0b3d91",
anchor="w",
justify="left",
wraplength=card_wraplen,
)
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
except Exception:
lbl_title = tk.Label(card, text=lines[0], bg=normal_bg)
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
# 其余行逐行显示(meta/body 区分),行间距更小
for li, ln in enumerate(lines[1:], start=1):
try:
if show_title_raw_var.get():
if li in (1, 2, 3):
lbl = tk.Label(
card,
text=ln,
font=meta_font,
fg="#555555",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
lbl = tk.Label(
card,
text=ln,
font=body_font,
fg="#222222",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
if li in (1, 2):
lbl = tk.Label(
card,
text=ln,
font=meta_font,
fg="#555555",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
lbl = tk.Label(
card,
text=ln,
font=body_font,
fg="#222222",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
lbl.pack(fill="x", padx=10, pady=(0, 1))
except Exception:
try:
tk.Label(card, text=ln, bg=normal_bg).pack(
fill="x", padx=10, pady=(0, 1)
)
except Exception:
pass
# 渲染标题 + meta + body 行
card_wraplen = max(160, col_width - 40)
_mt_helpers.render_card_labels(
card=card,
lines=lines,
title_font=title_font,
meta_font=meta_font,
body_font=body_font,
bg=normal_bg,
wraplength=card_wraplen,
show_title_raw=show_title_raw_var.get(),
)
# 分隔线
try:
@@ -420,108 +349,17 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
mapping_entries_widgets.append(card)
# 绑定点击/双击以及 hover 事件
def _make_bind_handlers(ci: int, cframe: tk.Widget):
def _on_click(e: object | None = None) -> None:
try:
# 取消其他选中并高亮当前
for i, w in enumerate(mapping_entries_widgets):
bg = normal_bg if i != ci else selected_bg
try:
try:
w.configure(**{"bg": bg})
except Exception:
w.configure(**{"background": bg})
except Exception:
pass
for ch in w.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
last_selected_entry["idx"] = ci
except Exception:
pass
def _on_dbl(e: object | None = None) -> None:
try:
content = mapping_entries_text[ci]
except Exception:
content = ""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if ScrolledText:
st = ScrolledText(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
else:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
def _on_enter(e: object | None = None) -> None:
try:
# 悬停时改变背景(若已选中则保持选中色)
bg = (
selected_bg
if last_selected_entry.get("idx") == ci
else hover_bg
)
try:
try:
cframe.configure(**{"bg": bg})
except Exception:
cframe.configure(**{"background": bg})
except Exception:
pass
for ch in cframe.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
except Exception:
pass
def _on_leave(e: object | None = None) -> None:
try:
bg = (
selected_bg
if last_selected_entry.get("idx") == ci
else normal_bg
)
try:
try:
cframe.configure(**{"bg": bg})
except Exception:
cframe.configure(**{"background": bg})
except Exception:
pass
for ch in cframe.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
except Exception:
pass
return _on_click, _on_dbl, _on_enter, _on_leave
on_click, on_dbl, on_enter, on_leave = _make_bind_handlers(
len(mapping_entries_widgets) - 1, card
on_click, on_dbl, on_enter, on_leave = _mt_helpers.make_card_event_handlers(
card_index=len(mapping_entries_widgets) - 1,
card=card,
cards=mapping_entries_widgets,
last_selected=last_selected_entry,
entries_text=mapping_entries_text,
root=root,
normal_bg=normal_bg,
hover_bg=hover_bg,
selected_bg=selected_bg,
scrolled_text_cls=ScrolledText,
)
try:
card.bind("<Button-1>", on_click)
@@ -594,22 +432,7 @@ def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Fr
content = mapping_entries_text[idx]
except Exception:
content = ""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if ScrolledText:
st = ScrolledText(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
else:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
_mt_helpers.open_entry_detail_window(root, content, ScrolledText)
except Exception:
pass
+182
View File
@@ -0,0 +1,182 @@
"""mapping_table 内部辅助函数。
把 mapping_table.create_mapping_tab 中重复或自包含的子块抽出来:
- 弹出条目详情窗口(在两处出现,逻辑完全一致)
- 计算自适应列数与卡片宽度
- 卡片背景色批量切换
- card hover/click/dbl 事件处理器工厂
- 渲染单张卡片内的标题 + 多行 label
"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Any, Callable, List, Optional
def open_entry_detail_window(
root: tk.Tk,
content: str,
scrolled_text_cls: Optional[type] = None,
) -> None:
"""打开"条目详情"弹窗。如果 ScrolledText 不可用则退化成 Label。"""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if scrolled_text_cls is not None:
st = scrolled_text_cls(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
return
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
def compute_card_layout(canvas_width: int, min_card_w: int = 300, h_gap: int = 12,
max_columns: int = 3) -> tuple[int, int]:
"""根据画布宽度计算列数与单卡片可用宽度。
返回 (columns, card_width)。
"""
try:
columns = max(1, int((canvas_width + h_gap) / (min_card_w + h_gap)))
except Exception:
columns = 1
columns = min(columns, max_columns)
try:
col_total_gap = columns * h_gap
col_width = max(220, int((canvas_width - col_total_gap) / columns))
except Exception:
col_width = 800
return columns, col_width
def set_card_bg(widget: tk.Widget, bg: str) -> None:
"""把 widget 自身和所有直接子 widget 的背景色改为 bg。"""
try:
try:
widget.configure(**{"bg": bg})
except Exception:
widget.configure(**{"background": bg})
except Exception:
pass
for ch in widget.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
def make_card_event_handlers(
card_index: int,
card: tk.Widget,
cards: List[tk.Widget],
last_selected: dict,
entries_text: List[str],
root: tk.Tk,
normal_bg: str,
hover_bg: str,
selected_bg: str,
scrolled_text_cls: Optional[type] = None,
) -> tuple[Callable, Callable, Callable, Callable]:
"""生成单张卡片的 click / dblclick / enter / leave 事件处理器。"""
def on_click(_e: object | None = None) -> None:
try:
for i, w in enumerate(cards):
bg = normal_bg if i != card_index else selected_bg
set_card_bg(w, bg)
last_selected["idx"] = card_index
except Exception:
pass
def on_dbl(_e: object | None = None) -> None:
try:
content = entries_text[card_index]
except Exception:
content = ""
open_entry_detail_window(root, content, scrolled_text_cls)
def on_enter(_e: object | None = None) -> None:
try:
bg = (
selected_bg if last_selected.get("idx") == card_index else hover_bg
)
set_card_bg(card, bg)
except Exception:
pass
def on_leave(_e: object | None = None) -> None:
try:
bg = (
selected_bg if last_selected.get("idx") == card_index else normal_bg
)
set_card_bg(card, bg)
except Exception:
pass
return on_click, on_dbl, on_enter, on_leave
def render_card_labels(
card: tk.Widget,
lines: List[str],
title_font: Any,
meta_font: Any,
body_font: Any,
bg: str,
wraplength: int,
show_title_raw: bool,
) -> None:
"""在单张 card 内逐行渲染 title + meta + body label。"""
if not lines:
return
# 标题行
try:
tk.Label(
card,
text=lines[0],
font=title_font,
bg=bg,
fg="#0b3d91",
anchor="w",
justify="left",
wraplength=wraplength,
).pack(fill="x", padx=10, pady=(6, 1))
except Exception:
try:
tk.Label(card, text=lines[0], bg=bg).pack(fill="x", padx=10, pady=(6, 1))
except Exception:
pass
meta_line_count = 3 if show_title_raw else 2
for li, ln in enumerate(lines[1:], start=1):
try:
is_meta = li in tuple(range(1, meta_line_count + 1))
font = meta_font if is_meta else body_font
fg = "#555555" if is_meta else "#222222"
tk.Label(
card,
text=ln,
font=font,
fg=fg,
bg=bg,
anchor="w",
justify="left",
wraplength=wraplength,
).pack(fill="x", padx=10, pady=(0, 1))
except Exception:
try:
tk.Label(card, text=ln, bg=bg).pack(fill="x", padx=10, pady=(0, 1))
except Exception:
pass
+905
View File
@@ -0,0 +1,905 @@
"""单元测试:douyin/reservation/reservation_logic/attend_window_helpers.py"""
from __future__ import annotations
import time
from unittest.mock import MagicMock
from douyin.reservation.reservation_logic import attend_window_helpers as h
def _make_analyser(**overrides):
a = MagicMock()
a.high_value_fudai_join_ahead_seconds = 100
a.high_value_fudai_max_swipe_back = 60
for k, v in overrides.items():
setattr(a, k, v)
return a
# ---- compute_dynamic_ahead ---- #
def test_compute_dynamic_ahead_zero_back_steps():
"""target_pos == room_pos → 不需要回退,提前量保持 join_ahead"""
a = _make_analyser()
target = {"pos_seen": 5}
da, est = h.compute_dynamic_ahead(a, target, room_pos=5, reservation_back_swipe_delay_s=0.6)
assert est == 0
assert da == 100 # join_ahead 默认值
def test_compute_dynamic_ahead_with_back_steps():
"""需要回退 50 步,每步 0.6s → 50*0.6+18 = 48s,仍小于 join_ahead=100,所以保持 100"""
a = _make_analyser()
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=50, reservation_back_swipe_delay_s=0.6)
assert est == 50
assert da == 100
def test_compute_dynamic_ahead_back_steps_dominate():
"""需要回退 200 步但被 max_back=60 截断 → 60*0.6+18 = 54,仍 < 100"""
a = _make_analyser()
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=200, reservation_back_swipe_delay_s=0.6)
assert est == 60 # 截断到 max_back
def test_compute_dynamic_ahead_huge_delay_dominates():
"""delay=5s 时 60*5+18=318 > join_ahead,dynamic_ahead 取大值"""
a = _make_analyser()
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=60, reservation_back_swipe_delay_s=5.0)
assert est == 60
assert da == 318 # 60*5+18
def test_compute_dynamic_ahead_no_max_back_uncapped():
"""high_value_fudai_max_swipe_back=0 时,由于 `or 60` 会被兜底成 60"""
a = _make_analyser(high_value_fudai_max_swipe_back=0)
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=100, reservation_back_swipe_delay_s=2.0)
assert est == 60 # 0 被 `or 60` 兜底
assert da == 138 # 60*2+18
def test_compute_dynamic_ahead_handles_bad_target_pos():
"""target.pos_seen 缺失时按 0 处理"""
a = _make_analyser()
target = {}
da, est = h.compute_dynamic_ahead(a, target, room_pos=10, reservation_back_swipe_delay_s=0.6)
assert est == 10
def test_compute_dynamic_ahead_negative_back_steps_clamped():
"""target_pos > room_pos(不正常)时 est_back_times 被钳到 0"""
a = _make_analyser()
target = {"pos_seen": 100}
da, est = h.compute_dynamic_ahead(a, target, room_pos=10, reservation_back_swipe_delay_s=0.6)
assert est == 0
def test_compute_dynamic_ahead_handles_bad_join_ahead():
"""getattr 抛错时回退到 100.0"""
a = MagicMock()
type(a).high_value_fudai_join_ahead_seconds = property(
lambda self: (_ for _ in ()).throw(RuntimeError("boom"))
)
a.high_value_fudai_max_swipe_back = 60
target = {"pos_seen": 5}
da, est = h.compute_dynamic_ahead(a, target, room_pos=5, reservation_back_swipe_delay_s=0.6)
# join_ahead 兜底为 100.0
assert da == 100
# ---- _ts_to_str ---- #
def test_ts_to_str_invalid():
assert h._ts_to_str(0) == "无效"
assert h._ts_to_str(-100) == "无效"
def test_ts_to_str_valid():
s = h._ts_to_str(1700000000) # 2023-11-14 22:13:20 UTC, 本地时区
assert len(s) == 19 # YYYY-MM-DD HH:MM:SS
# ---- log_attend_window_check_details ---- #
def test_log_attend_window_check_details_writes_one_line():
a = MagicMock()
h.log_attend_window_check_details(
a,
now_ts=1700000000,
focus_until=0,
ft=1700000100,
dynamic_ahead=100,
join_ahead=100.0,
poll_before=10.0,
est_back_times=0,
)
assert a._log_kv.call_count == 1
args, kwargs = a._log_kv.call_args
assert args[0] == "预约"
assert "process_reservation_attend_window 详细检查" in args[1]
assert kwargs["target_future_ts"] == 1700000100
assert kwargs["dynamic_ahead"] == 100
assert kwargs["in_lock_period"] is False # focus_until=0
def test_log_attend_window_check_details_in_lock_period():
a = MagicMock()
h.log_attend_window_check_details(
a,
now_ts=1700000000,
focus_until=1700000050, # > now_ts
ft=1700000100,
dynamic_ahead=100,
join_ahead=100.0,
poll_before=10.0,
est_back_times=0,
)
args, kwargs = a._log_kv.call_args
assert kwargs["in_lock_period"] is True
def test_log_attend_window_check_details_swallows_exceptions():
bad = MagicMock()
bad._log_kv.side_effect = RuntimeError("boom")
h.log_attend_window_check_details(
bad, now_ts=0, focus_until=0, ft=0, dynamic_ahead=0,
join_ahead=0.0, poll_before=0.0, est_back_times=0,
)
# ---- check_waiting_for_reservation_lottery ---- #
def test_waiting_lottery_with_reservation_returns_true():
a = MagicMock()
a._waiting_for_lottery_result = True
a._current_attending_reservation_fudai = True
assert h.check_waiting_for_reservation_lottery(a) is True
def test_waiting_lottery_only_one_flag_returns_false():
a = MagicMock()
a._waiting_for_lottery_result = True
a._current_attending_reservation_fudai = False
assert h.check_waiting_for_reservation_lottery(a) is False
a._waiting_for_lottery_result = False
a._current_attending_reservation_fudai = True
assert h.check_waiting_for_reservation_lottery(a) is False
def test_waiting_lottery_neither_flag_returns_false():
a = MagicMock()
a._waiting_for_lottery_result = False
a._current_attending_reservation_fudai = False
assert h.check_waiting_for_reservation_lottery(a) is False
# ---- maybe_promote_locked_reservation ---- #
def test_promote_locked_no_lock_period_returns_unchanged():
a = MagicMock()
reservations = [{"future_ts": 100}]
ref = [0.0]
result = h.maybe_promote_locked_reservation(
a, reservations, ref, focus_until=0.0, now_ts=200.0, poll_before=10.0
)
assert result == 0.0
def test_promote_locked_expired_returns_unchanged():
"""now_ts >= focus_until → 锁定期已过,不修改"""
a = MagicMock()
reservations = [{"future_ts": 100}]
ref = [50.0]
result = h.maybe_promote_locked_reservation(
a, reservations, ref, focus_until=50.0, now_ts=100.0, poll_before=10.0
)
assert result == 50.0
def test_promote_locked_target_not_in_queue_clears_focus():
"""锁定期对应的预约已不在队列 → 清除锁定期"""
a = MagicMock()
reservations = [{"future_ts": 200}, {"future_ts": 300}]
# focus_until = 1000,但队列里没有 ft+10 = 1000 的预约
ref = [1000.0]
now = 500.0
result = h.maybe_promote_locked_reservation(
a, reservations, ref, focus_until=1000.0, now_ts=now, poll_before=10.0
)
assert result == 0.0
assert ref[0] == 0.0
def test_promote_locked_already_at_head_no_swap():
"""锁定预约已在队头 → 不调整顺序"""
a = MagicMock()
# focus_until = 200 + 10 = 210,正好是第一个预约的"预期 focus"
reservations = [{"future_ts": 200}, {"future_ts": 300}]
ref = [210.0]
result = h.maybe_promote_locked_reservation(
a, reservations, ref, focus_until=210.0, now_ts=100.0, poll_before=10.0
)
assert result == 210.0
# 顺序未变
assert reservations[0]["future_ts"] == 200
def test_promote_locked_swaps_to_head():
"""锁定预约不在队头 → 移到队头"""
a = MagicMock()
# focus_until = 300 + 10 = 310,对应队列中第二个预约
reservations = [
{"future_ts": 200},
{"future_ts": 300},
]
ref = [310.0]
result = h.maybe_promote_locked_reservation(
a, reservations, ref, focus_until=310.0, now_ts=100.0, poll_before=10.0
)
assert result == 310.0
# 锁定预约(300)已被移到队头
assert reservations[0]["future_ts"] == 300
# ---- check_already_participated ---- #
def test_already_participated_with_match_pops_and_returns_true():
a = MagicMock()
a._participated_fudai_future_ts = {100.0, 200.0}
reservations = [{"future_ts": 100.0}, {"future_ts": 300.0}]
target = reservations[0]
write_cb = MagicMock()
result = h.check_already_participated(a, reservations, target, 100.0, write_cb)
assert result is True
assert len(reservations) == 1 # 队头被弹出
write_cb.assert_called_once()
def test_already_participated_no_match_returns_false():
a = MagicMock()
a._participated_fudai_future_ts = {500.0}
reservations = [{"future_ts": 100.0}]
write_cb = MagicMock()
result = h.check_already_participated(a, reservations, reservations[0], 100.0, write_cb)
assert result is False
assert len(reservations) == 1
write_cb.assert_not_called()
def test_already_participated_within_5s_tolerance():
"""允许 5 秒误差 → 95-105 之间也算已参与"""
a = MagicMock()
a._participated_fudai_future_ts = {100.0}
reservations = [{"future_ts": 103.0}]
write_cb = MagicMock()
result = h.check_already_participated(a, reservations, reservations[0], 103.0, write_cb)
assert result is True
def test_already_participated_outside_5s_returns_false():
a = MagicMock()
a._participated_fudai_future_ts = {100.0}
reservations = [{"future_ts": 110.0}] # 差 10 秒,超出误差
write_cb = MagicMock()
result = h.check_already_participated(a, reservations, reservations[0], 110.0, write_cb)
assert result is False
def test_already_participated_non_set_attr_treated_as_empty():
a = MagicMock()
a._participated_fudai_future_ts = "not_a_set"
reservations = [{"future_ts": 100.0}]
write_cb = MagicMock()
result = h.check_already_participated(a, reservations, reservations[0], 100.0, write_cb)
assert result is False
# ---- discard_invalid_future_ts ---- #
def test_discard_invalid_ft_zero_returns_true():
a = MagicMock()
reservations = [{"future_ts": 0}, {"future_ts": 100}]
write_cb = MagicMock()
result = h.discard_invalid_future_ts(a, reservations, reservations[0], 0.0, write_cb)
assert result is True
assert len(reservations) == 1
write_cb.assert_called_once()
def test_discard_invalid_ft_negative_returns_true():
a = MagicMock()
reservations = [{"future_ts": -5}]
write_cb = MagicMock()
result = h.discard_invalid_future_ts(a, reservations, reservations[0], -5.0, write_cb)
assert result is True
def test_discard_invalid_ft_positive_returns_false():
a = MagicMock()
reservations = [{"future_ts": 100}]
write_cb = MagicMock()
result = h.discard_invalid_future_ts(a, reservations, reservations[0], 100.0, write_cb)
assert result is False
assert len(reservations) == 1
write_cb.assert_not_called()
# ---- log_target_reservation_details ---- #
def test_log_target_reservation_details_writes_one_line():
a = MagicMock()
target = {"prize_value_yuan": 5.0, "pos_seen": 3, "content": "test"}
h.log_target_reservation_details(a, target, ft=1700000000.0)
a._log_kv.assert_called_once()
args, kwargs = a._log_kv.call_args
assert args[0] == "预约"
assert kwargs["target_future_ts"] == 1700000000
assert kwargs["target_value"] == 5.0
def test_log_target_reservation_details_invalid_ft():
a = MagicMock()
h.log_target_reservation_details(a, {}, ft=0.0)
a._log_kv.assert_called_once()
_, kwargs = a._log_kv.call_args
assert kwargs["target_future_str"] == "无效"
def test_log_target_reservation_details_swallows_exception():
a = MagicMock()
a._log_kv.side_effect = RuntimeError("boom")
# 不应抛错
h.log_target_reservation_details(a, {}, ft=100.0)
# ---- sort_reservations_with_logging ---- #
def test_sort_reservations_logs_before_and_after():
a = MagicMock()
reservations = [{"future_ts": 200}, {"future_ts": 100}]
sort_cb = MagicMock(side_effect=lambda lst: lst.sort(key=lambda x: x["future_ts"]))
h.sort_reservations_with_logging(a, reservations, sort_cb)
# 至少 2 次日志:开始排序 / 排序完成
assert a._log_kv.call_count >= 2
# 排序后队头是 100
assert reservations[0]["future_ts"] == 100
def test_sort_reservations_swallows_sort_exception():
a = MagicMock()
reservations = [{"future_ts": 100}]
sort_cb = MagicMock(side_effect=RuntimeError("boom"))
# 不应抛错
h.sort_reservations_with_logging(a, reservations, sort_cb)
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
assert any("队列排序异常" in m for m in msgs)
def test_sort_reservations_empty_queue():
a = MagicMock()
sort_cb = MagicMock()
h.sort_reservations_with_logging(a, [], sort_cb)
sort_cb.assert_called_once_with([])
# ---- check_total_timeout ---- #
def test_check_timeout_not_exceeded_returns_false():
a = MagicMock()
now = time.time()
assert h.check_total_timeout(a, now, total_timeout_s=10.0, stage="测试") is False
def test_check_timeout_exceeded_returns_true():
a = MagicMock()
past = time.time() - 100
assert h.check_total_timeout(a, past, total_timeout_s=10.0, stage="测试") is True
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
assert any("超时退出(测试)" in m for m in msgs)
def test_check_timeout_swallows_exception():
a = MagicMock()
a._log_kv.side_effect = RuntimeError("boom")
past = time.time() - 100
# 应不抛错
result = h.check_total_timeout(a, past, total_timeout_s=10.0, stage="测试")
assert result is True
# ---- check_queue_full_immediate_attend ---- #
def test_queue_full_immediate_attend_true():
a = MagicMock()
a.queue_full_waiting_at_earliest = True
assert h.check_queue_full_immediate_attend(a) is True
def test_queue_full_immediate_attend_false():
a = MagicMock()
a.queue_full_waiting_at_earliest = False
assert h.check_queue_full_immediate_attend(a) is False
def test_queue_full_immediate_swallows_attr_error():
a = MagicMock()
type(a).queue_full_waiting_at_earliest = property(
lambda _self: (_ for _ in ()).throw(RuntimeError("boom"))
)
assert h.check_queue_full_immediate_attend(a) is False
# ---- handle_time_window_early_returns ---- #
def test_time_window_not_yet_arrived_returns_false():
a = MagicMock()
cleanup = MagicMock()
write_cb = MagicMock()
now = 1700000000.0
ft = now + 500 # 500s 后
result = h.handle_time_window_early_returns(
a, [], now, ft, dynamic_ahead=100,
poll_before=10.0, is_queue_full_immediate_attend=False,
cleanup_expired_callback=cleanup, write_state_callback=write_cb,
)
assert result is False
cleanup.assert_not_called()
def test_time_window_missed_calls_cleanup_and_returns_true():
a = MagicMock()
cleanup = MagicMock()
write_cb = MagicMock()
now = 1700000000.0
ft = now - 1000 # 已过去
result = h.handle_time_window_early_returns(
a, [{"future_ts": ft}], now, ft, dynamic_ahead=100,
poll_before=10.0, is_queue_full_immediate_attend=False,
cleanup_expired_callback=cleanup, write_state_callback=write_cb,
)
assert result is True
cleanup.assert_called_once()
def test_time_window_in_range_returns_none():
"""在窗口内 → 返回 None 让主流程继续"""
a = MagicMock()
cleanup = MagicMock()
now = 1700000000.0
ft = now + 50 # 50s 内
result = h.handle_time_window_early_returns(
a, [], now, ft, dynamic_ahead=100,
poll_before=10.0, is_queue_full_immediate_attend=False,
cleanup_expired_callback=cleanup, write_state_callback=MagicMock(),
)
assert result is None
cleanup.assert_not_called()
def test_time_window_queue_full_skips_not_yet_check():
"""队列满立即参与模式 → 即使时间未到也不返回 False"""
a = MagicMock()
cleanup = MagicMock()
now = 1700000000.0
ft = now + 500 # 远未到
result = h.handle_time_window_early_returns(
a, [], now, ft, dynamic_ahead=100,
poll_before=10.0, is_queue_full_immediate_attend=True,
cleanup_expired_callback=cleanup, write_state_callback=MagicMock(),
)
# 队列满模式下时间未到也算"在窗口内"
assert result is None
# ---- handle_lock_period_same_reservation_check ---- #
def _make_lock_check_args(**overrides):
"""构造 handle_lock_period_same_reservation_check 的默认参数。"""
a = MagicMock()
a.queue_full_waiting_at_earliest = False
a.room_pos = 5
target = {"pos_seen": 5, "future_ts": 1700000100}
base = {
"analyser": a,
"target": target,
"ft": 1700000100.0,
"now_ts": 1700000000.0,
"focus_until": 0.0,
"poll_before": 10.0,
"dynamic_ahead": 100,
"room_pos": 5,
"reservation_focus_until_ts_ref": [0.0],
"reservation_after_action_pending_ref": [False],
"write_state_callback": MagicMock(),
}
base.update(overrides)
return base
def test_lock_check_no_lock_period_returns_none():
args = _make_lock_check_args(focus_until=0.0)
assert h.handle_lock_period_same_reservation_check(**args) is None
def test_lock_check_queue_full_mode_returns_none():
a = MagicMock()
a.queue_full_waiting_at_earliest = True
args = _make_lock_check_args(
focus_until=1700000050.0, # 锁定期内
analyser=a,
)
args["analyser"].room_pos = 5
assert h.handle_lock_period_same_reservation_check(**args) is None
def test_lock_check_different_reservation_returns_false():
"""锁定期内但不是当前预约 → False"""
args = _make_lock_check_args(
focus_until=1700000050.0, # 远不是 1700000100 + 10 = 1700000110
ft=1700000100.0,
poll_before=10.0,
)
assert h.handle_lock_period_same_reservation_check(**args) is False
def test_lock_check_same_reservation_at_target_in_window_returns_true():
"""同一预约 + 已在目标位置 + 时间窗口内 → True"""
a = MagicMock()
a.queue_full_waiting_at_earliest = False
a.room_pos = 5
write_cb = MagicMock()
args = _make_lock_check_args(
analyser=a,
focus_until=1700000110.0, # = ft + poll_before = 1700000100 + 10
ft=1700000100.0,
now_ts=1700000050.0, # 在窗口内 [ft-100=1700000000, ft+10=1700000110]
write_state_callback=write_cb,
)
result = h.handle_lock_period_same_reservation_check(**args)
assert result is True
write_cb.assert_called_once()
assert args["reservation_focus_until_ts_ref"][0] == 1700000110.0
assert args["reservation_after_action_pending_ref"][0] is True
def test_lock_check_same_reservation_at_target_window_not_yet_returns_false():
"""同一预约 + 已在目标位置 + 时间窗口未到 → False(清除待处理标志)"""
a = MagicMock()
a.queue_full_waiting_at_earliest = False
a.room_pos = 5
args = _make_lock_check_args(
analyser=a,
focus_until=1700000110.0,
ft=1700000100.0,
now_ts=1699999800.0, # 在窗口前 [1700000000-100, 1700000110]
reservation_after_action_pending_ref=[True],
)
result = h.handle_lock_period_same_reservation_check(**args)
assert result is False
assert args["reservation_after_action_pending_ref"][0] is False
def test_lock_check_same_reservation_not_at_target_returns_none():
"""同一预约 + 不在目标位置 → None(让主流程继续走时间窗口检查)"""
a = MagicMock()
a.queue_full_waiting_at_earliest = False
a.room_pos = 10 # 不等于 target.pos_seen=5
args = _make_lock_check_args(
analyser=a,
focus_until=1700000110.0,
ft=1700000100.0,
room_pos=10,
)
result = h.handle_lock_period_same_reservation_check(**args)
assert result is None
# ---- log_entering_attend_window ---- #
def test_log_entering_attend_window_writes_one_line():
a = MagicMock()
h.log_entering_attend_window(
a, ft=1700000100.0, now_ts=1700000050.0,
room_pos=5, queue_len=3, dynamic_ahead=100, est_back_times=2, poll_before=10.0,
)
a._log_kv.assert_called_once()
_, kwargs = a._log_kv.call_args
assert kwargs["queue_len"] == 3
assert kwargs["est_back_times"] == 2
def test_log_entering_attend_window_swallows_exception():
a = MagicMock()
a._log_kv.side_effect = RuntimeError("boom")
h.log_entering_attend_window(
a, ft=0, now_ts=0, room_pos=0, queue_len=0,
dynamic_ahead=0, est_back_times=0, poll_before=0,
)
# ---- execute_seek_reservation_callback ---- #
def test_execute_seek_callback_returns_true():
a = MagicMock()
cb = MagicMock(return_value=True)
target = {"pos_seen": 5}
result = h.execute_seek_reservation_callback(
a, target, current_room_pos=10, target_pos=5, pos_diff=5,
seek_reservation_room_callback=cb,
)
assert result is True
cb.assert_called_once_with(target)
def test_execute_seek_callback_returns_false():
a = MagicMock()
cb = MagicMock(return_value=False)
result = h.execute_seek_reservation_callback(
a, {}, 0, 0, 0, cb,
)
assert result is False
def test_execute_seek_callback_exception_returns_false():
a = MagicMock()
cb = MagicMock(side_effect=RuntimeError("boom"))
result = h.execute_seek_reservation_callback(
a, {}, 0, 0, 0, cb,
)
assert result is False
# 应记录异常日志
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
assert any("执行回退时发生异常" in m for m in msgs)
# ---- wait_for_live_room_load_after_back ---- #
def test_wait_for_live_room_load_uses_default(monkeypatch):
a = MagicMock()
a.reservation_back_verify_wait_seconds = 5.0
monkeypatch.setattr("time.sleep", lambda _s: None)
h.wait_for_live_room_load_after_back(a)
a.operation.delay.assert_called_once_with(5.0)
def test_wait_for_live_room_load_clamps_below_min(monkeypatch):
a = MagicMock()
a.reservation_back_verify_wait_seconds = 0.05 # < 0.1
monkeypatch.setattr("time.sleep", lambda _s: None)
h.wait_for_live_room_load_after_back(a)
a.operation.delay.assert_called_once_with(0.1)
def test_wait_for_live_room_load_clamps_above_max(monkeypatch):
a = MagicMock()
a.reservation_back_verify_wait_seconds = 100.0 # > 10
monkeypatch.setattr("time.sleep", lambda _s: None)
h.wait_for_live_room_load_after_back(a)
a.operation.delay.assert_called_once_with(10.0)
def test_wait_for_live_room_load_falls_back_to_sleep(monkeypatch):
a = MagicMock()
a.reservation_back_verify_wait_seconds = 5.0
a.operation.delay.side_effect = RuntimeError("boom")
sleep_called = []
monkeypatch.setattr("time.sleep", lambda s: sleep_called.append(s))
h.wait_for_live_room_load_after_back(a)
# 异常时回退到 time.sleep
assert 5.0 in sleep_called
# ---- log_back_success_pre_verify ---- #
def test_log_back_success_pre_verify_writes_one_line():
a = MagicMock()
target = {"pos_seen": 5}
h.log_back_success_pre_verify(
a, target, "标题", "原始", "内容", 100.0, 7,
)
a._log_kv.assert_called_once()
_, kwargs = a._log_kv.call_args
assert kwargs["target_pos"] == 5
assert kwargs["target_value_yuan"] == 100.0
assert kwargs["current_room_pos"] == 7
def test_log_back_success_swallows_exception():
a = MagicMock()
a._log_kv.side_effect = RuntimeError("boom")
h.log_back_success_pre_verify(a, {}, "", "", "", 0.0, 0)
# ---- log_back_failure_and_finish ---- #
def test_log_back_failure_writes_logs_and_calls_write_state():
a = MagicMock()
write_cb = MagicMock()
h.log_back_failure_and_finish(
a, {"pos_seen": 5}, ft=time.time() + 100, now_ts=time.time(),
room_pos=3, start_time=time.time() - 1.0, write_state_callback=write_cb,
)
write_cb.assert_called_once()
msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2]
assert any("回退到预约直播间失败" in m for m in msgs)
assert any("返回结果" in m for m in msgs)
def test_log_back_failure_swallows_write_state_exception():
a = MagicMock()
write_cb = MagicMock(side_effect=RuntimeError("boom"))
h.log_back_failure_and_finish(
a, {}, ft=0, now_ts=0, room_pos=0,
start_time=time.time(), write_state_callback=write_cb,
)
# ---- handle_verify_failure_retry_via_mapping ---- #
def test_verify_retry_seek_callback_succeeds_returns_true():
"""二次回退 seek 成功 → 设置锁定期 + return True"""
a = MagicMock()
target = {"pos_seen": 5, "future_ts": 1700000100}
focus_ref = [0.0]
pending_ref = [False]
write_cb = MagicMock()
seek_cb = MagicMock(return_value=True)
# _resolve_*_via_mapping 都返回 None → mapped_pos_diff 不计算 → should_retry_seek=True
# 然后调用 seek_cb(updated_target) 返回 True
result = h.handle_verify_failure_retry_via_mapping(
a, target, "标题", "原始", ft=1700000100.0, poll_before=10.0,
reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=pending_ref,
seek_reservation_room_callback=seek_cb,
write_state_callback=write_cb,
)
assert result is True
assert focus_ref[0] == 1700000110.0
assert pending_ref[0] is True
seek_cb.assert_called_once()
write_cb.assert_called_once()
def test_verify_retry_seek_callback_fails_returns_false():
"""二次回退 seek 失败 → 清理标志 + return False"""
a = MagicMock()
target = {"pos_seen": 5}
focus_ref = [12345.0] # 已设置的锁定期
pending_ref = [True]
write_cb = MagicMock()
seek_cb = MagicMock(return_value=False)
result = h.handle_verify_failure_retry_via_mapping(
a, target, "标题", "原始", ft=1700000100.0, poll_before=10.0,
reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=pending_ref,
seek_reservation_room_callback=seek_cb,
write_state_callback=write_cb,
)
assert result is False
# 清理了标志
assert focus_ref[0] == 0.0
assert pending_ref[0] is False
write_cb.assert_called_once()
def test_verify_retry_seek_exception_returns_false():
"""seek_callback 抛错 → ok2=False → return False"""
a = MagicMock()
target = {"pos_seen": 5}
focus_ref = [0.0]
pending_ref = [False]
seek_cb = MagicMock(side_effect=RuntimeError("boom"))
result = h.handle_verify_failure_retry_via_mapping(
a, target, "", "", ft=1700000100.0, poll_before=10.0,
reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=pending_ref,
seek_reservation_room_callback=seek_cb,
write_state_callback=MagicMock(),
)
assert result is False
def test_verify_retry_no_seek_callback_returns_false():
"""seek_callback=None → ok2=False → return False"""
a = MagicMock()
result = h.handle_verify_failure_retry_via_mapping(
a, {"pos_seen": 0}, "", "", ft=0, poll_before=0,
reservation_focus_until_ts_ref=[0.0],
reservation_after_action_pending_ref=[False],
seek_reservation_room_callback=None,
write_state_callback=MagicMock(),
)
assert result is False
# ---- _decide_retry_seek ---- #
def test_decide_retry_seek_no_mapping_returns_true():
"""mapped_current_pos=None → 默认 True"""
a = MagicMock()
assert h._decide_retry_seek(a, {}, None, 5, 0) is True
assert h._decide_retry_seek(a, {}, 5, None, 0) is True
def test_decide_retry_seek_diff_nonzero_returns_true():
a = MagicMock()
assert h._decide_retry_seek(a, {}, 3, 7, 0) is True
def test_decide_retry_seek_diff_zero_with_correction_returns_true():
"""diff=0 但回退前位置 != 目标位置 → 启用方向提示并 return True"""
a = MagicMock()
target = {}
# mapped_current=mapped_target=5,但 room_pos_before=10 != 5
result = h._decide_retry_seek(a, target, 5, 5, 10)
assert result is True
assert target["_seek_direction_hint"] == "down" # 10 > 5
def test_decide_retry_seek_diff_zero_at_correct_pos_returns_false():
"""diff=0 且回退前位置 == 目标位置 → 跳过二次回退"""
a = MagicMock()
assert h._decide_retry_seek(a, {}, 5, 5, 5) is False
def test_decide_retry_seek_correction_up_direction():
"""room_pos_before < mapped_target → direction_hint = up"""
a = MagicMock()
target = {}
h._decide_retry_seek(a, target, 5, 5, 2) # 2 < 5
assert target["_seek_direction_hint"] == "up"
# ---- enter_lock_period_and_log_success ---- #
def test_enter_lock_period_sets_focus_and_pending():
a = MagicMock()
focus_ref = [0.0]
pending_ref = [False]
write_cb = MagicMock()
h.enter_lock_period_and_log_success(
a, target={"pos_seen": 5}, target_room_title="标题", target_room_title_raw="raw",
target_content="内容", target_value=99.9,
ft=1700000100.0, now_ts=1700000050.0, poll_before=10.0,
start_time=time.time(), reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=pending_ref,
write_state_callback=write_cb, now_ts_func=lambda: 1700000050.0,
)
assert focus_ref[0] == 1700000110.0 # ft + poll_before
assert pending_ref[0] is True
write_cb.assert_called_once()
def test_enter_lock_period_appends_to_empty_refs():
a = MagicMock()
focus_ref = []
pending_ref = []
h.enter_lock_period_and_log_success(
a, target={}, target_room_title="", target_room_title_raw="", target_content="",
target_value=0.0, ft=1700000100.0, now_ts=0, poll_before=10.0,
start_time=time.time(), reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=pending_ref,
write_state_callback=MagicMock(), now_ts_func=lambda: 0,
)
assert focus_ref == [1700000110.0]
assert pending_ref == [True]
def test_enter_lock_period_swallows_log_exception():
a = MagicMock()
a._log_kv.side_effect = RuntimeError("boom")
h.enter_lock_period_and_log_success(
a, target={}, target_room_title="", target_room_title_raw="", target_content="",
target_value=0.0, ft=0, now_ts=0, poll_before=0,
start_time=time.time(), reservation_focus_until_ts_ref=[0.0],
reservation_after_action_pending_ref=[False],
write_state_callback=MagicMock(), now_ts_func=lambda: 0,
)
+411
View File
@@ -0,0 +1,411 @@
"""单元测试:douyin/stage/douyin_stage_helpers.py
只测纯日志格式化函数 _format_detail_log_fields 的输入→输出映射。
更上层的 log_pixel_detection_details / summarize_pixel_state 用 callback
桩做行为验证。
"""
from __future__ import annotations
import time as _time
from unittest.mock import MagicMock, patch
from douyin.stage import douyin_stage_helpers as h
def test_format_basic_detail():
detail = {"detected": True, "method": "pixel"}
fields = h._format_detail_log_fields("has_coupon_bg", detail, MagicMock())
assert fields["步骤"] == "优惠券背景"
assert fields["检测结果"] == "命中"
assert fields["检测方法"] == "pixel"
def test_format_unknown_key_falls_back_to_key():
detail = {"detected": False, "method": "x"}
fields = h._format_detail_log_fields("unknown_key", detail, MagicMock())
assert fields["步骤"] == "unknown_key"
assert fields["检测结果"] == "未命中"
def test_format_with_template_score():
detail = {"detected": True, "method": "tpl", "template_score": 0.876543}
fields = h._format_detail_log_fields("has_lucky_draw_result", detail, MagicMock())
assert fields["分数"] == 0.8765
assert fields["模板匹配分数"] == 0.8765
def test_format_with_confidence_only():
detail = {"detected": True, "method": "px", "confidence": 0.5}
fields = h._format_detail_log_fields("has_live_room_pixel", detail, MagicMock())
assert fields["置信度"] == 0.5
assert fields["分数"] == 0.5
def test_format_threshold_none_shows_text():
detail = {"detected": False, "method": "x", "effective_threshold": None}
fields = h._format_detail_log_fields("has_redpacket_bg", detail, MagicMock())
assert fields["阈值"] == "未设置"
def test_format_fudai_detail_with_task_count():
analyser = MagicMock()
analyser.fudai_detail_template_threshold = 0.6
analyser.fudai_template_match_threshold = 0.7
detail = {"detected": True, "method": "tpl", "task_count": 3}
fields = h._format_detail_log_fields("has_fudai_detail", detail, analyser)
assert fields["任务数量"] == 3
assert fields["配置阈值"] == 0.6
def test_format_fudai_detail_missing_task_count():
detail = {"detected": False, "method": "tpl"}
fields = h._format_detail_log_fields("has_fudai_detail", detail, MagicMock())
assert fields["任务数量"] == "未获取"
def test_log_pixel_detection_details_iterates_all_keys():
log = MagicMock()
pixel_details = {
"has_coupon_bg": {"detected": True, "method": "px"},
"has_redpacket_bg": {"detected": False, "method": "px"},
}
h.log_pixel_detection_details(pixel_details, MagicMock(), log)
assert log.call_count == 2 # 一个 key 一次
def test_log_pixel_detection_details_warns_on_task_count_mismatch():
"""has_fudai_detail 检测为 False 但 task_count > 0 时应额外告警"""
log = MagicMock()
pixel_details = {
"has_fudai_detail": {"detected": False, "method": "tpl", "task_count": 5},
}
h.log_pixel_detection_details(pixel_details, MagicMock(), log)
# 一次告警 + 一次普通日志 = 2 次
assert log.call_count == 2
def test_log_pixel_detection_details_handles_empty():
log = MagicMock()
h.log_pixel_detection_details({}, MagicMock(), log)
assert log.call_count == 0
def test_summarize_pixel_state_writes_one_log_line():
log = MagicMock()
h.summarize_pixel_state({"has_live_room_pixel": True}, 12.3, log)
assert log.call_count == 1
args, kwargs = log.call_args
assert args[0] == "像素状态(并行检测完成)"
assert kwargs["直播间图标像素检测"] is True
def test_summarize_pixel_state_swallows_exceptions():
"""log_callback 抛错也不应传播"""
bad_log = MagicMock(side_effect=RuntimeError("boom"))
h.summarize_pixel_state({}, 0.0, bad_log)
# ---- detect_lottery_result_popup ---- #
def test_detect_lottery_result_matched_returns_true():
a = MagicMock()
log = MagicMock()
log_summary = MagicMock()
log_sep = MagicMock()
from douyin.utils import douyin_helpers
with patch.object(
douyin_helpers.HelperFunctions,
"check_lottery_result_by_ocr",
return_value=True,
):
matched, stage, reason = h.detect_lottery_result_popup(
a, _time.time(), log, log_summary, log_sep
)
assert matched is True
assert stage == "FUDai_RESULT"
def test_detect_lottery_result_not_matched_returns_false():
a = MagicMock()
log = MagicMock()
log_summary = MagicMock()
log_sep = MagicMock()
from douyin.utils import douyin_helpers
with patch.object(
douyin_helpers.HelperFunctions,
"check_lottery_result_by_ocr",
return_value=False,
):
matched, _, _ = h.detect_lottery_result_popup(
a, _time.time(), log, log_summary, log_sep
)
assert matched is False
def test_detect_lottery_result_exception_returns_false():
a = MagicMock()
log = MagicMock()
log_summary = MagicMock()
log_sep = MagicMock()
from douyin.utils import douyin_helpers
with patch.object(
douyin_helpers.HelperFunctions,
"check_lottery_result_by_ocr",
side_effect=RuntimeError("boom"),
):
matched, _, _ = h.detect_lottery_result_popup(
a, _time.time(), log, log_summary, log_sep
)
assert matched is False
# ---- detect_shopping_redpacket_popup ---- #
def test_detect_shopping_redpacket_keyword_match():
"""OCR 文本含关键词 → 命中"""
a = MagicMock()
a.operation.analyse_pic_word.return_value = "邀你抢红包啦"
log = MagicMock()
log_summary = MagicMock()
log_sep = MagicMock()
matched, stage, _ = h.detect_shopping_redpacket_popup(
a, (10, 20, 30, 40), _time.time(), 30.0, 5.0,
lambda _x, _y: "preprocessed", log, log_summary, log_sep,
)
assert matched is True
assert stage == "SHOPPING_REDPACKET_POPUP"
def test_detect_shopping_redpacket_no_keyword_returns_false():
a = MagicMock()
a.operation.analyse_pic_word.return_value = "随便的文本"
log = MagicMock()
matched, _, _ = h.detect_shopping_redpacket_popup(
a, (10, 20, 30, 40), _time.time(), 30.0, 5.0,
lambda _x, _y: "p", log, MagicMock(), MagicMock(),
)
assert matched is False
def test_detect_shopping_redpacket_ocr_exception_returns_false():
a = MagicMock()
a.cut_pic.side_effect = RuntimeError("boom")
log = MagicMock()
matched, _, _ = h.detect_shopping_redpacket_popup(
a, (10, 20, 30, 40), _time.time(), 30.0, 5.0,
lambda _x, _y: "p", log, MagicMock(), MagicMock(),
)
assert matched is False
# ---- detect_redpacket_ocr_recheck_outside_live ---- #
def test_redpacket_recheck_no_pixel_bg_returns_false():
"""像素未命中红包背景 → 直接返回 False,不做 OCR"""
a = MagicMock()
log = MagicMock()
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
a, {"has_redpacket_bg": False}, {},
(10, 20, 30, 40), _time.time(), 5.0, True,
lambda _x, _y: "p", log, MagicMock(),
)
assert matched is False
a.cut_pic.assert_not_called()
def test_redpacket_recheck_keyword_match_returns_true():
a = MagicMock()
a.operation.analyse_pic_word.return_value = ("邀你抢红包", None)
a.shopping_redpacket_ocr_confidence_threshold = 0.99
log = MagicMock()
matched, stage, _ = h.detect_redpacket_ocr_recheck_outside_live(
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
(10, 20, 30, 40), _time.time(), 30.0, True,
lambda _x, _y: "p", log, MagicMock(),
)
assert matched is True
assert stage == "SHOPPING_REDPACKET_POPUP"
def test_redpacket_recheck_high_confidence_match():
"""无关键词但置信度高 → 命中"""
a = MagicMock()
a.operation.analyse_pic_word.return_value = (
"无关文本",
{"avg_confidence": 0.9, "max_confidence": 0.95},
)
a.shopping_redpacket_ocr_confidence_threshold = 0.9
log = MagicMock()
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
(10, 20, 30, 40), _time.time(), 30.0, False,
lambda _x, _y: "p", log, MagicMock(),
)
assert matched is True
def test_redpacket_recheck_no_match_returns_false():
a = MagicMock()
a.operation.analyse_pic_word.return_value = (
"无关文本",
{"avg_confidence": 0.3, "max_confidence": 0.4},
)
a.shopping_redpacket_ocr_confidence_threshold = 0.9
log = MagicMock()
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
(10, 20, 30, 40), _time.time(), 30.0, False,
lambda _x, _y: "p", log, MagicMock(),
)
assert matched is False
def test_redpacket_recheck_exception_returns_false():
a = MagicMock()
a.cut_pic.side_effect = RuntimeError("adb")
log = MagicMock()
matched, _, _ = h.detect_redpacket_ocr_recheck_outside_live(
a, {"has_redpacket_bg": True}, {"has_redpacket_bg": {}},
(10, 20, 30, 40), _time.time(), 30.0, True,
lambda _x, _y: "p", log, MagicMock(),
)
assert matched is False
# ---- detect_recommend_follow_live_tabs ---- #
def _make_tab_analyser(recommend_text="", follow_text="", live_text=""):
"""构造一个 mock analyser,按 cut_pic 的 crop_name 返回不同 OCR 文本。"""
a = MagicMock()
text_map = {
"推荐页标签栏": recommend_text,
"关注列表标签": follow_text,
"直播列表标签": live_text,
}
def fake_analyse(name, mode):
# name 经过 preprocess_for_ocr 处理后我们让它直接返回 crop_name
return text_map.get(name, "")
a.operation.analyse_pic_word.side_effect = fake_analyse
return a
def test_recommend_follow_live_tabs_recommend_match():
a = _make_tab_analyser(recommend_text="推荐 关注 直播")
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
matched, stage, _ = h.detect_recommend_follow_live_tabs(
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
_time.time(), 30.0, False,
lambda _a, name: name, log, log_sum, log_sep,
)
assert matched is True
assert stage == "RECOMMEND_PAGE"
def test_recommend_follow_live_tabs_follow_match():
a = _make_tab_analyser(recommend_text="关注", follow_text="关注")
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
matched, stage, _ = h.detect_recommend_follow_live_tabs(
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
_time.time(), 30.0, False,
lambda _a, name: name, log, log_sum, log_sep,
)
assert matched is True
assert stage == "FOLLOW_LIST"
def test_recommend_follow_live_tabs_live_match():
a = _make_tab_analyser(recommend_text="直播", live_text="正在直播")
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
matched, stage, _ = h.detect_recommend_follow_live_tabs(
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
_time.time(), 30.0, False,
lambda _a, name: name, log, log_sum, log_sep,
)
assert matched is True
assert stage == "LIVE_LIST"
def test_recommend_follow_live_tabs_no_match_returns_false():
a = _make_tab_analyser(recommend_text="无关文本")
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
matched, _, _ = h.detect_recommend_follow_live_tabs(
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
_time.time(), 30.0, False,
lambda _a, name: name, log, log_sum, log_sep,
)
assert matched is False
def test_recommend_follow_live_tabs_outer_exception_returns_false():
a = MagicMock()
a.cut_pic.side_effect = RuntimeError("boom")
log, log_sum, log_sep = MagicMock(), MagicMock(), MagicMock()
matched, _, _ = h.detect_recommend_follow_live_tabs(
a, (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
_time.time(), 30.0, False,
lambda _a, name: name, log, log_sum, log_sep,
)
assert matched is False
# ---- detect_suspicious_popup_via_ocr ---- #
def test_suspicious_popup_no_pixel_returns_false():
"""has_coupon_bg=False 且 has_redpacket_bg=False → 直接返回 False"""
a = MagicMock()
matched, _, _ = h.detect_suspicious_popup_via_ocr(
a, {"has_coupon_bg": False, "has_redpacket_bg": False},
(1, 2, 3, 4), (5, 6, 7, 8),
_time.time(), 30.0, 5.0, False,
lambda _a, name: name,
MagicMock(), MagicMock(),
)
assert matched is False
def test_suspicious_popup_coupon_match():
"""coupon_bg=True + OCR 命中"开心收下" → 返回 COUPON_POPUP"""
a = MagicMock()
a.operation.analyse_pic_word.return_value = "请开心收下你的红包"
matched, stage, _ = h.detect_suspicious_popup_via_ocr(
a, {"has_coupon_bg": True, "has_redpacket_bg": False},
(1, 2, 3, 4), (5, 6, 7, 8),
_time.time(), 30.0, 5.0, False, # enable_ocr_mode1=False 走简单路径
lambda _a, name: name,
MagicMock(), MagicMock(),
)
assert matched is True
assert stage == "COUPON_POPUP"
def test_suspicious_popup_redpacket_match():
a = MagicMock()
a.operation.analyse_pic_word.return_value = "邀你抢红包"
matched, stage, _ = h.detect_suspicious_popup_via_ocr(
a, {"has_coupon_bg": False, "has_redpacket_bg": True},
(1, 2, 3, 4), (5, 6, 7, 8),
_time.time(), 30.0, 5.0, False,
lambda _a, name: name,
MagicMock(), MagicMock(),
)
assert matched is True
assert stage == "SHOPPING_REDPACKET_POPUP"
def test_suspicious_popup_no_keyword_returns_false():
a = MagicMock()
a.operation.analyse_pic_word.return_value = "无关文本"
matched, _, _ = h.detect_suspicious_popup_via_ocr(
a, {"has_coupon_bg": True, "has_redpacket_bg": True},
(1, 2, 3, 4), (5, 6, 7, 8),
_time.time(), 30.0, 5.0, False,
lambda _a, name: name,
MagicMock(), MagicMock(),
)
assert matched is False
+37
View File
@@ -0,0 +1,37 @@
"""单元测试:douyin/fudai/core/fudai_attend_fansclub.py
只做最小冒烟:能 import + 函数签名正确。
完整业务测试需要大量 OCR / ADB / 截图桩,性价比低。
"""
from __future__ import annotations
import inspect
from douyin.fudai.core import fudai_attend_fansclub
def test_module_import():
assert fudai_attend_fansclub is not None
def test_handle_fansclub_branch_signature():
fn = fudai_attend_fansclub.handle_fansclub_branch
sig = inspect.signature(fn)
params = list(sig.parameters.keys())
assert params == ["analyser", "attend_button_text"]
def test_handle_fansclub_branch_callable():
assert callable(fudai_attend_fansclub.handle_fansclub_branch)
def test_module_only_exports_one_public_fn():
"""保持 API 最小化"""
public = [
x for x in dir(fudai_attend_fansclub)
if not x.startswith("_") and not x[0].isupper()
]
# 排除 import 进来的模块
own = [x for x in public if x not in {"os", "time", "path_config", "annotations"}]
assert "handle_fansclub_branch" in own
File diff suppressed because it is too large. Load diff
+276
View File
@@ -0,0 +1,276 @@
"""单元测试:douyin/core/fudai_modules/fudai_image_helpers.py
只覆盖纯逻辑分支与异常吞噬路径;完整图片读取链路依赖 ADB + 真实 PNG 文件,
不在单元测试范围内。
"""
from __future__ import annotations
import io
from unittest.mock import MagicMock, patch
import pytest
from douyin.core.fudai_modules import fudai_image_helpers
def _make_analyser():
a = MagicMock()
a.device_id = "test"
a._run_id = "test_run"
a._log_kv = MagicMock()
a.operation = MagicMock()
a.operation.get_screenshot = MagicMock()
return a
def test_capture_roi_no_screenshot_path_returns_empty(monkeypatch):
"""screenshot_path 不存在时直接返回空字符串"""
a = _make_analyser()
monkeypatch.setattr("os.path.exists", lambda _p: False)
result = fudai_image_helpers.capture_roi_screenshot(a, "label", 100, 100, 50)
assert result == ""
def test_capture_roi_with_invalid_path_returns_empty(monkeypatch):
a = _make_analyser()
monkeypatch.setattr("os.path.exists", lambda _p: False)
result = fudai_image_helpers.capture_roi_screenshot(
a, "label", 100, 100, 50, screenshot_path="/no/such/file.png"
)
assert result == ""
def test_capture_roi_outer_exception_swallowed(monkeypatch):
"""获取 path_config 抛错时也应吞噬异常并写日志"""
a = _make_analyser()
# 让 path_config 导入抛错
monkeypatch.setattr("os.path.exists", lambda _p: True)
with patch.object(
fudai_image_helpers, "_read_screenshot_with_validation",
side_effect=RuntimeError("boom"),
):
result = fudai_image_helpers.capture_roi_screenshot(a, "label", 100, 100, 50)
assert result == ""
# 应记录失败日志
a._log_kv.assert_called()
def test_read_screenshot_returns_none_when_path_missing(monkeypatch, tmp_path):
"""文件不存在时多次重试后返回 None"""
a = _make_analyser()
monkeypatch.setattr("time.sleep", lambda _s: None)
fake_path = str(tmp_path / "no.png")
result = fudai_image_helpers._read_screenshot_with_validation(
a, fake_path, max_attempts=2
)
assert result is None
def test_read_screenshot_validates_png_header(monkeypatch, tmp_path):
"""非 PNG 头时拒绝"""
a = _make_analyser()
monkeypatch.setattr("time.sleep", lambda _s: None)
bad_file = tmp_path / "bad.png"
bad_file.write_bytes(b"\x00" * 2048)
result = fudai_image_helpers._read_screenshot_with_validation(
a, str(bad_file), max_attempts=2
)
assert result is None
def test_read_screenshot_validates_iend_tail(monkeypatch, tmp_path):
"""PNG 头但缺失 IEND 尾时拒绝"""
a = _make_analyser()
monkeypatch.setattr("time.sleep", lambda _s: None)
bad_file = tmp_path / "bad.png"
# 有效 PNG header 但没 IEND
bad_file.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 2048)
result = fudai_image_helpers._read_screenshot_with_validation(
a, str(bad_file), max_attempts=2
)
assert result is None
def test_read_screenshot_skips_tiny_file(monkeypatch, tmp_path):
"""文件 < 1024 字节时跳过"""
a = _make_analyser()
monkeypatch.setattr("time.sleep", lambda _s: None)
tiny = tmp_path / "tiny.png"
tiny.write_bytes(b"\x89PNG\r\n\x1a\n") # 8 字节
result = fudai_image_helpers._read_screenshot_with_validation(
a, str(tiny), max_attempts=2
)
assert result is None
def test_read_screenshot_returns_data_for_valid_png(monkeypatch, tmp_path):
"""生成有效 PNG → _read_screenshot_with_validation 返回字节"""
from PIL import Image
import random
a = _make_analyser()
monkeypatch.setattr("time.sleep", lambda _s: None)
pic_path = tmp_path / "ok.png"
# 用随机像素生成大于 1024 字节的 PNG(白色图压缩后过小被 size guard 拒绝)
rng = random.Random(0)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(100 * 100)]
img = Image.new("RGB", (100, 100))
img.putdata(pixels)
img.save(str(pic_path))
assert pic_path.stat().st_size >= 1024
result = fudai_image_helpers._read_screenshot_with_validation(
a, str(pic_path), max_attempts=2
)
assert result is not None
assert result.startswith(b"\x89PNG")
assert b"IEND" in result[-512:]
def test_open_image_or_retry_with_valid_data():
a = _make_analyser()
from PIL import Image
img = Image.new("RGB", (50, 50), color="white")
buf = io.BytesIO()
img.save(buf, format="PNG")
data = buf.getvalue()
result = fudai_image_helpers._open_image_or_retry(a, data, "/tmp/x.png")
assert result is not None
def test_open_image_or_retry_unidentified_returns_none():
a = _make_analyser()
result = fudai_image_helpers._open_image_or_retry(a, b"not_a_png", "/no/path.png")
assert result is None
def test_capture_roi_end_to_end_with_real_png(monkeypatch, tmp_path):
"""端到端:写一个真实 PNG,capture_roi_screenshot 应返回有效 ROI 路径"""
from PIL import Image
import random
a = _make_analyser()
pic_path = tmp_path / "screenshot.png"
rng = random.Random(42)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(200 * 200)]
img = Image.new("RGB", (200, 200))
img.putdata(pixels)
img.save(str(pic_path))
out_dir = tmp_path / "out"
out_dir.mkdir()
fake_path_config = MagicMock()
fake_path_config.get_screenshot_path = lambda: str(pic_path)
fake_path_config.get_pic_dir = lambda: str(out_dir)
monkeypatch.setattr("douyin.core.path_config", fake_path_config)
monkeypatch.setattr("time.sleep", lambda _s: None)
result = fudai_image_helpers.capture_roi_screenshot(a, "test", 100, 100, 50)
assert result
assert "roi_test_test_run" in result
# ---- _correlation_score ---- #
def test_correlation_score_identical_arrays():
import numpy as np
a = np.array([1.0, 2.0, 3.0, 4.0])
score = fudai_image_helpers._correlation_score(a, a)
assert abs(score - 1.0) < 1e-6
def test_correlation_score_constant_arrays_returns_minus_one():
"""相同常数数组 → 范数为 0 → 返回 -1.0"""
import numpy as np
a = np.array([5.0, 5.0, 5.0])
b = np.array([5.0, 5.0, 5.0])
score = fudai_image_helpers._correlation_score(a, b)
assert score == -1.0
def test_correlation_score_anticorrelated():
import numpy as np
a = np.array([1.0, 2.0, 3.0])
b = np.array([3.0, 2.0, 1.0])
score = fudai_image_helpers._correlation_score(a, b)
assert abs(score - (-1.0)) < 1e-6
# ---- match_icon_template ---- #
def test_match_icon_missing_roi_returns_false():
a = _make_analyser()
detected, score = fudai_image_helpers.match_icon_template(
a, "/no/such/roi.png", "/no/such/tpl.png"
)
assert detected is False
assert score == 0.0
def test_match_icon_empty_paths_returns_false():
a = _make_analyser()
assert fudai_image_helpers.match_icon_template(a, "", "x") == (False, 0.0)
assert fudai_image_helpers.match_icon_template(a, "x", "") == (False, 0.0)
def test_match_icon_same_image_high_score(tmp_path):
"""同一张图作为 ROI 与模板 → 完美匹配,score=1.0"""
from PIL import Image
import random
a = _make_analyser()
rng = random.Random(0)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(60 * 60)]
img = Image.new("RGB", (60, 60))
img.putdata(pixels)
same = tmp_path / "same.png"
img.save(str(same))
detected, score = fudai_image_helpers.match_icon_template(
a, str(same), str(same), threshold=0.5
)
assert detected is True
assert abs(score - 1.0) < 1e-3
def test_match_icon_template_larger_than_roi_gets_resized(tmp_path):
"""模板比 ROI 大 → 自动缩放,仍能比对"""
from PIL import Image
a = _make_analyser()
roi = Image.new("RGB", (50, 50), color="white")
tpl = Image.new("RGB", (200, 200), color="white")
roi_path = tmp_path / "roi.png"
tpl_path = tmp_path / "tpl.png"
roi.save(str(roi_path))
tpl.save(str(tpl_path))
# 不抛错就算通过;都是白色范数为 0,会回到 -1
detected, score = fudai_image_helpers.match_icon_template(
a, str(roi_path), str(tpl_path)
)
# 白色图分母为 0 → score=-1,detected=False
assert detected is False
def test_match_icon_threshold_param_overrides_attr(tmp_path):
"""threshold=0 时即使分数较低也判定为 detected"""
from PIL import Image
import random
a = _make_analyser()
a.yanghao_icon_match_threshold = 0.99 # 默认很高
rng = random.Random(0)
pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(40 * 40)]
img = Image.new("RGB", (40, 40))
img.putdata(pixels)
same = tmp_path / "same.png"
img.save(str(same))
# threshold=0 → 任何 score >= 0 都算命中
detected, _ = fudai_image_helpers.match_icon_template(
a, str(same), str(same), threshold=0.0
)
assert detected is True
File diff suppressed because it is too large. Load diff
+65
View File
@@ -0,0 +1,65 @@
"""单元测试:gui/components/mapping_table_helpers.py
只测 compute_card_layout(纯函数,无 tk 依赖),其他 tk-依赖函数靠
mapping_table.py 整体 import 冒烟覆盖。
"""
from __future__ import annotations
import pytest
from gui.components import mapping_table_helpers as h
def test_compute_card_layout_narrow_canvas_one_column():
cols, w = h.compute_card_layout(canvas_width=400)
assert cols == 1
assert w >= 220
def test_compute_card_layout_wide_canvas_three_columns_capped():
cols, w = h.compute_card_layout(canvas_width=2000)
assert cols == 3
assert w >= 220
def test_compute_card_layout_medium_canvas():
cols, w = h.compute_card_layout(canvas_width=900)
assert 1 <= cols <= 3
assert w >= 220
def test_compute_card_layout_zero_width_falls_back_to_one_column():
cols, w = h.compute_card_layout(canvas_width=0)
assert cols == 1
def test_compute_card_layout_respects_max_columns_param():
cols, _ = h.compute_card_layout(canvas_width=10000, max_columns=5)
assert cols == 5
def test_compute_card_layout_min_card_width_param():
"""min_card_w 越大,能放下的列数越少"""
cols_a, _ = h.compute_card_layout(canvas_width=900, min_card_w=200)
cols_b, _ = h.compute_card_layout(canvas_width=900, min_card_w=600)
assert cols_a >= cols_b
def test_open_entry_detail_window_empty_content_no_crash():
"""空 content 应直接 return 不创建窗口(不需要 tk root)"""
h.open_entry_detail_window(root=None, content="", scrolled_text_cls=None)
def test_module_public_api():
"""API 表面:保护重命名/删除时主调用方能跟上"""
public = {x for x in dir(h) if not x.startswith("_") and not x[0].isupper()}
expected = {
"compute_card_layout",
"make_card_event_handlers",
"open_entry_detail_window",
"render_card_labels",
"set_card_bg",
}
# 至少暴露这些
assert expected.issubset(public)
+287
View File
@@ -0,0 +1,287 @@
"""单元测试:douyin/detection/detection_pkg/template_match_helpers.py
只覆盖纯逻辑路径与异常吞噬:
- 模板文件不存在 → 返回 (False, None)
- OpenCV 导入失败 / 模板读取失败 → 异常吞噬
- 命中/未命中分数对比
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch
import pytest
from douyin.detection.detection_pkg import template_match_helpers as h
def _make_analyser():
a = MagicMock()
a._log_kv = MagicMock()
a.fudai_template_match_threshold = 0.7
return a
def test_template_match_missing_template_file_returns_false(monkeypatch, tmp_path):
a = _make_analyser()
fake_assets = tmp_path / "no_assets"
monkeypatch.setattr(
"douyin.core.path_config.get_assets_dir",
lambda: str(fake_assets),
)
pic = MagicMock()
detected, x = h.template_match_fallback(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0, loop=0,
)
assert detected is False
assert x is None
def test_template_match_outer_exception_swallowed(monkeypatch):
a = _make_analyser()
# 让 cv2 import 抛错触发外层 except
monkeypatch.setitem(__import__("sys").modules, "cv2", None)
pic = MagicMock()
detected, x = h.template_match_fallback(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0, loop=0,
)
# cv2=None 时 .imread 调用抛 AttributeError → 被吞噬
assert detected is False
assert x is None
def test_template_match_threshold_attr_not_a_number(monkeypatch, tmp_path):
"""threshold 异常时回退到 0.7"""
a = _make_analyser()
a.fudai_template_match_threshold = "not_a_number"
fake_assets = tmp_path / "assets"
fake_assets.mkdir()
(fake_assets / "fudai.png").write_bytes(b"not_a_real_png")
monkeypatch.setattr(
"douyin.core.path_config.get_assets_dir",
lambda: str(fake_assets),
)
pic = MagicMock()
# cv2.imread 会返回 None(不是真 PNG),触发"模板读取失败"分支
detected, x = h.template_match_fallback(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0, loop=0,
)
assert detected is False
def test_template_match_full_pipeline_no_match(tmp_path, monkeypatch):
"""阈值设到 1.01(不可达)→ 必然不匹配,验证阈值分支。"""
cv2 = pytest.importorskip("cv2")
import numpy as np
from PIL import Image
a = _make_analyser()
a.fudai_template_match_threshold = 1.01 # 不可达,必然不匹配
fake_assets = tmp_path / "assets"
fake_assets.mkdir()
np.random.seed(7)
template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8)
cv2.imwrite(str(fake_assets / "fudai.png"), template)
monkeypatch.setattr(
"douyin.core.path_config.get_assets_dir",
lambda: str(fake_assets),
)
pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.template_match_fallback(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0, loop=0,
)
assert detected is False
assert x is None
def test_template_match_full_pipeline_perfect_match(tmp_path, monkeypatch):
"""构造一张包含模板的图像 → 模板匹配应命中"""
cv2 = pytest.importorskip("cv2")
import numpy as np
from PIL import Image
a = _make_analyser()
fake_assets = tmp_path / "assets"
fake_assets.mkdir()
# 创建一个 30x30 的明显图案作为模板
np.random.seed(0)
template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8)
cv2.imwrite(str(fake_assets / "fudai.png"), template)
monkeypatch.setattr(
"douyin.core.path_config.get_assets_dir",
lambda: str(fake_assets),
)
# 构造一张图:把模板嵌入到搜索区域内(X=156-269, Y=351-451)
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255 # alpha
embed_y, embed_x = 380, 200 # 都在搜索区域内
# cv2 imread 是 BGR,put 时转回 RGB;这里直接用 numpy 嵌入相同 BGR 数组
pic_arr[embed_y:embed_y + 30, embed_x:embed_x + 30, :3] = template[..., ::-1]
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.template_match_fallback(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0, loop=0,
)
assert detected is True
# 检测到的 x 应当在嵌入位置附近(embed_x + tw//2 = 200 + 15 = 215,1080 基准下相同)
assert x is not None
assert abs(x - (embed_x + 15)) <= 5
# ---- numpy_pixel_scan ---- #
def test_numpy_pixel_scan_no_match(tmp_path):
"""全黑图像 → numpy 扫描不会命中目标颜色范围"""
pytest.importorskip("numpy")
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.numpy_pixel_scan(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0,
optimal_x_scaled=169,
)
assert detected is False
assert x is None
def test_numpy_pixel_scan_with_match(tmp_path):
"""构造目标颜色 → numpy 扫描命中"""
pytest.importorskip("numpy")
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
# 目标颜色 R=200, G=185, B=240(在范围内:R[190-206], G[173-196], B[234-250])
# 在搜索区域 X=157-410, Y=354 附近放一列像素(每列至少 2 个像素,valid_cols >= 2)
target_x = 250
pic_arr[353:355, target_x, 0] = 200
pic_arr[353:355, target_x, 1] = 185
pic_arr[353:355, target_x, 2] = 240
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.numpy_pixel_scan(
a, pic, rx=1080, ry=2400,
width=1080, height=2400, y_pianyi_val=0,
optimal_x_scaled=target_x,
)
assert detected is True
assert x == target_x
def test_numpy_pixel_scan_invalid_roi():
"""搜索区域无效(width < 157)→ 直接返回 False"""
a = _make_analyser()
pic = MagicMock()
detected, x = h.numpy_pixel_scan(
a, pic, rx=1080, ry=2400,
width=100, height=2400, y_pianyi_val=0, # width < 157
optimal_x_scaled=169,
)
assert detected is False
# ---- per_pixel_scan_fallback ---- #
def test_per_pixel_scan_no_match():
"""全白图 → 像素逐行扫描找不到目标颜色"""
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.per_pixel_scan_fallback(
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is False
assert x is None
def test_per_pixel_scan_with_match():
"""构造目标像素 → 逐行扫描命中"""
import numpy as np
from PIL import Image
a = _make_analyser()
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
# 在 scan_y=403, scan_x=200 处放目标像素
pic_arr[403, 200] = (200, 185, 240, 255)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.per_pixel_scan_fallback(
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is True
assert x == 200
def test_per_pixel_scan_uses_last_fudai_x():
"""analyser.last_fudai_x 设置时,从该位置开始搜索"""
import numpy as np
from PIL import Image
a = _make_analyser()
a.last_fudai_x = 250
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
pic_arr[..., 3] = 255
pic_arr[403, 250] = (200, 185, 240, 255)
pic = Image.fromarray(pic_arr, mode="RGBA")
detected, x = h.per_pixel_scan_fallback(
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is True
assert x == 250
def test_per_pixel_scan_swallows_exception():
"""pic.load() 抛错时不应崩"""
a = _make_analyser()
bad_pic = MagicMock()
bad_pic.load.side_effect = RuntimeError("boom")
detected, x = h.per_pixel_scan_fallback(
a, bad_pic, rx=1080, ry=2400, y_pianyi_val=0,
)
assert detected is False
assert x is None
# ---- _is_target_pixel ---- #
def test_is_target_pixel_in_range():
assert h._is_target_pixel((200, 185, 240)) is True
assert h._is_target_pixel((190, 173, 234)) is True
assert h._is_target_pixel((206, 196, 250)) is True
def test_is_target_pixel_out_of_range():
assert h._is_target_pixel((189, 185, 240)) is False
assert h._is_target_pixel((200, 197, 240)) is False
assert h._is_target_pixel((200, 185, 233)) is False
def test_is_target_pixel_non_tuple():
assert h._is_target_pixel(None) is False
assert h._is_target_pixel((100,)) is False # 长度不够
assert h._is_target_pixel("not_tuple") is False