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
218 changed files with 27671 additions and 34856 deletions

No files matched your search

-3
View File
@@ -60,9 +60,6 @@ git_lsremote_trace.txt
log_filter_result.txt
time_analysis_result.txt
# Test/diagnostic outputs
output/
# Local runtime state and generated caches
state/
pic/
-32
View File
@@ -1,32 +0,0 @@
# WebUI 用户视角问题清单(2026-06-01)
## 已修复(本轮)
1. `/api/config` 布尔值字符串会被错误写入
- 现象:`"false"` 可能被当成 `true`。
- 修复:后端 `routes.py` 新增 `_coerce_bool`,前端 `config_form.js` 同步字面量解析。
2. 设备动作在无设备时存在未捕获 Promise 报错噪音
- 现象:点击“返回键”后可能触发全局 `pageerror`(虽有提示但会污染错误面板)。
- 修复:`runtime_device_actions.js` 的 `sendBackKey()` 增加局部 `try/catch`。
3. 预约/高价值列表中少量字段未统一做安全处理
- 现象:个别字符串字段直接插入模板字符串。
- 修复:`runtime_actions.js` 对 `future_str` 等补 `escapeHtml`,数值字段统一显式数值化。
4. WiFi 自动重连与扫描参数错误码语义不清
- 修复:
- 无 adb:`/api/wifi/auto-reconnect` 返回 `422`。
- `ports` 非法:`/api/wifi/scan` 返回 `400 invalid ports`。
- `probe_timeout` 非法继续返回 `400`。
## 仍可优化(下一批)
1. 移动端首屏头部信息密度偏高
- 证据:`mobile_home.png` 中操作按钮区占比较大,设备/状态卡阅读层级偏挤。
- 建议:在 `< 420px` 下把二级按钮折叠进更多菜单,保留“开始/停止/截图”主操作。
2. Tab 横向切换在自动化点击中偶发不可见状态
- 证据:Playwright 偶发 `runLogs` tab 点击超时(人工可复现概率低)。
- 建议:为 tab click 增加 `scrollIntoView` + `requestAnimationFrame` 后触发,提升自动化与低端机稳定性。
@@ -1,84 +0,0 @@
{
"url": "http://localhost:8001/",
"screenshots": [
"artifacts\\webui_checks\\20260601\\desktop_home.png",
"artifacts\\webui_checks\\20260601\\desktop_run_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_stats_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_monitor_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_reservations_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_runlogs_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_actionlogs_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_home.png",
"artifacts\\webui_checks\\20260601\\mobile_run_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_stats_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_monitor_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_reservations_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_runlogs_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_actionlogs_panel.png"
],
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
},
{
"type": "action",
"text": "click_failed .tabBtn[data-target=\"runLogs\"]: Locator.click: Timeout 3000ms exceeded.\nCall log:\n - waiting for locator(\".tabBtn[data-target=\\\"runLogs\\\"]\").first\n - locator resolved to <button role=\"tab\" type=\"button\" class=\"tabBtn\" data-target=\"runLogs\" aria-selected=\"false\">…</button>\n - attempting click action\n - waiting for element to be visible, enabled and stable\n - element is visible, enabled and stable\n - scrolling into view if needed\n - done scrolling\n - performing click action\n"
}
],
"page_errors": [
"未选择设备,且无法自动解析在线设备"
],
"checks": {
"desktop:has:btnStart": true,
"desktop:has:btnStop": true,
"desktop:has:btnForceStop": true,
"desktop:has:btnRefresh": true,
"desktop:has:btnScreenshot": true,
"desktop:has:btnBackKey": true,
"desktop:has:btnLoad": true,
"desktop:has:btnSave": true,
"desktop:has:device": true,
"desktop:has:btnWifiScan": true,
"desktop:has:wifiStatus": true,
"desktop:has:runLog": true,
"desktop:has:appConnText": true,
"desktop:has:appConnDot": true,
"desktop:has:reservationsContent": true,
"desktop:has:highValueRoomsContent": true,
"desktop:has:hv_expand_all": true,
"desktop:has:hv_collapse_all": true,
"desktop:conn_text": "已连接",
"desktop:body_box": {
"w": 1600,
"h": 1178.65625,
"scrollH": 1179
},
"desktop:overflow_controls": 0,
"mobile:has:btnStart": true,
"mobile:has:btnStop": true,
"mobile:has:btnForceStop": true,
"mobile:has:btnRefresh": true,
"mobile:has:btnScreenshot": true,
"mobile:has:btnBackKey": true,
"mobile:has:btnLoad": true,
"mobile:has:btnSave": true,
"mobile:has:device": true,
"mobile:has:btnWifiScan": true,
"mobile:has:wifiStatus": true,
"mobile:has:runLog": true,
"mobile:has:appConnText": true,
"mobile:has:appConnDot": true,
"mobile:has:reservationsContent": true,
"mobile:has:highValueRoomsContent": true,
"mobile:has:hv_expand_all": true,
"mobile:has:hv_collapse_all": true,
"mobile:conn_text": "已连接",
"mobile:body_box": {
"w": 390,
"h": 2102.875,
"scrollH": 2103
},
"mobile:overflow_controls": 1
}
}
@@ -1,15 +0,0 @@
{
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
}
],
"page_errors": [],
"screenshots": [
"artifacts\\webui_checks\\20260601_port8002\\mobile_main.png"
],
"checks": {
"has_unhandled_error": false
}
}
@@ -1,15 +0,0 @@
{
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
}
],
"page_errors": [],
"screenshots": [
"artifacts\\webui_checks\\20260601_postfix\\mobile_after_fix.png"
],
"checks": {
"has_unhandled_error": false
}
}
+5 -5
View File
@@ -5,11 +5,6 @@ import os
import shutil
import sys
# ==== 将项目根目录加入 sys.path,确保后续所有 douyin.* 导入正常 ================
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
if os.environ.get("PARAM_TRACK_ALL") == "1":
try:
@@ -52,6 +47,10 @@ except Exception as e:
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 确保项目根在 sys.path 中(脚本从 bin/ 目录启动时)
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
@@ -76,6 +75,7 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
+4 -17
View File
@@ -194,12 +194,12 @@
"monitor_critical_mb": 200.0
},
"debug_captures": {
"enabled": true,
"enabled": false,
"keep_days": 1,
"max_files": 1000,
"auto_cleanup": true,
"async_save": false,
"log_on_complete": true
"log_on_complete": false
},
"fudai_detail_template_threshold": 0.52,
"switch_room_wait_after_stage_diag_seconds": 7.5,
@@ -210,11 +210,7 @@
"reservation_test_mode": false,
"swipe_duration_ms": 250,
"gui": {
"theme": "litera",
"realtime_status": {
"refresh_interval_ms": 1000,
"tail_items": 50
}
"theme": "litera"
},
"fansclub_click_delay": 0.6,
"fansclub_auto_join_wait_seconds": 5.0,
@@ -228,14 +224,5 @@
"high_value_room_revisit_min_prize_value": 1000.0,
"high_value_room_revisit_max_age_days": 1,
"swipe_up_start_y": 1200,
"swipe_up_end_y": 600,
"swipe_down_back_enabled": false,
"swipe_down_back_count": 3,
"log_unified_enabled": true,
"log_unified_path": "logs/unified.log",
"last_wifi_target": {
"target": "192.168.5.2:5555",
"model": "PEPM00",
"saved_at": 1779501066
}
"swipe_up_end_y": 600
}
@@ -1,462 +0,0 @@
# 拆分 gui/gui_app.py 实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 把 `gui/gui_app.py`(5476 行)中内聚的 `main()` 闭包逐段抽到 `gui/components/*` 子模块,主文件持续瘦身,GUI 行为不变。
**Architecture:** 每个候选段抽到独立模块,改造为顶层函数,通过显式参数(回调 + 必要的 widgets/Vars/路径)接收依赖。每抽完一段独立 commit + push。
**Tech Stack:** Python 3.10+, tkinter / ttkbootstrap, pytest
**Spec:** `docs/superpowers/specs/2026-05-30-split-gui-app-design.md`
---
## 抽取顺序
按 spec 优先级:P1 → P2 → P3 → P4 → P5 → P6。每个任务独立可停。
P1 包括两个紧耦合段(`open_wifi_adb_dialog` 845 行 + `open_scan_dialog` 200 行)。
---
## Task 1: 抽 `open_scan_dialog` 到 `components/wifi_adb_scan_dialog.py`
**Files:**
- Create: `gui/components/wifi_adb_scan_dialog.py`
- Modify: `gui/gui_app.py:539-742` (删除原闭包) + 改 `gui/gui_app.py:1088-1093`(`open_scan_dialog` 调用点)
**理由先抽这个:** `open_scan_dialog` 已经是显式参数形式,不依赖 `main()` 任何捕获变量,迁移最简单。先做它能熟悉抽取流程,降 ~200 行。
- [ ] **Step 1: 读完整段确认依赖**
```bash
# 看 539-742 完整段
```
确认 `open_scan_dialog` 仅依赖参数 `parent, adb_exe_local, ip_var, on_line_local, refresh_cb` 和模块级 import(`tk`, `ttk`, `discover_adb_devices`, `get_local_subnet`, `pick_best_match`, `verify_adb_target` 等)。
- [ ] **Step 2: 创建新模块**
写 `gui/components/wifi_adb_scan_dialog.py`,把 539-742 的整段函数原样复制为 `open_scan_dialog`,加 `from __future__ import annotations` 与所有需要的 import。
- [ ] **Step 3: 修改 `gui_app.py`,替换调用点**
在 `gui_app.py` 顶部 import 新模块:
```python
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
```
删除 539-742 的原 `def open_scan_dialog(...)` 定义。
- [ ] **Step 4: 验证语法**
```bash
python -m py_compile gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
```
Expected: 无输出(成功)
- [ ] **Step 5: 跑测试**
```bash
pytest -x
```
Expected: 全部 PASS
- [ ] **Step 6: 行数核对 + commit**
```bash
wc -l gui/gui_app.py
git status --short
git add gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
git commit -m "refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → <new>)"
git push
```
---
## Task 2: 抽 `open_wifi_adb_dialog` 到 `components/wifi_adb_dialog.py`
**Files:**
- Create: `gui/components/wifi_adb_dialog.py`
- Modify: `gui/gui_app.py:743-1111` (删除原闭包,改 `wifi_adb_btn` 的 command)
**依赖分析(已完成):**
模块级(已 import,直接用):
- `list_adb_devices`, `enable_wifi_adb`, `connect_wifi_adb`, `disconnect_wifi_adb`, `auto_connect_wifi_adb`, `get_device_ip`, `get_connected_wifi_devices`(from `gui.gui_core`)
- `set_last_wifi_target`, `get_last_wifi_target`, `clear_last_wifi_target`(from `gui.gui_core_pkg`)
- `verify_adb_target`, `query_device_model`(from `gui.gui_core_pkg.wifi_adb_scan`)
`main()` 局部(必须传):
- `root: tk.Misc`(父窗口,用于 `tk.Toplevel(root)`)
- `adb_exe: str`
- `on_line: Callable[[str], None]`
- `refresh_devices: Callable[[], None]`
- `open_scan_dialog`(Task 1 完成后已为顶层函数,直接 import)
自递归(三处 `dialog.destroy(); open_wifi_adb_dialog()`):
改造为传入自己的引用 —— 用一个内部函数 `_reopen()` 闭包捕获参数,或参数化 `parent`/`adb_exe` 后直接再调用顶层函数。**采用方案 B:把 `open_wifi_adb_dialog` 改成顶层函数,签名带所有依赖,自递归直接调用自己。**
- [ ] **Step 1: 创建新模块骨架**
```python
# gui/components/wifi_adb_dialog.py
from __future__ import annotations
import re
import threading
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, W, X
from typing import Callable
from gui.gui_core import (
auto_connect_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
enable_wifi_adb,
get_connected_wifi_devices,
get_device_ip,
list_adb_devices,
)
from gui.gui_core_pkg import (
clear_last_wifi_target,
get_last_wifi_target,
set_last_wifi_target,
)
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
def open_wifi_adb_dialog(
root: tk.Misc,
*,
adb_exe: str,
on_line: Callable[[str], None],
refresh_devices: Callable[[], None],
) -> None:
"""打开 WiFi ADB 设置对话框。
从 gui_app.main 抽出,显式接收依赖。
"""
# ... (Step 2 复制原 743-1111 函数体,把对外部名字的引用替换为参数)
```
- [ ] **Step 2: 复制函数体并替换闭包变量引用**
把 `gui_app.py:743-1111`(从 `def open_wifi_adb_dialog():` 内 body 开始,到 `info_label.pack(...)` 结束)整段复制进新函数体,缩进调整 4 → 4(已经一致,只是去掉外层 `def main()` 这一层)。
把三处自递归改为带参数的:
```python
# 原: open_wifi_adb_dialog()
# 改: open_wifi_adb_dialog(root, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
```
把对 `open_scan_dialog` 的引用保留为 module-import 形式:
```python
# 原:
# command=lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists)
# 不变(因为已 import 顶层 open_scan_dialog)
```
注意 `toggle_maximize`、`refresh_device_lists` 是嵌套闭包,保持原样不抽 —— 它们捕获的是对话框内 widgets,只在对话框内用。
- [ ] **Step 3: 改 `gui_app.py`,删原闭包,改按钮 command**
在 `gui_app.py` 顶部加:
```python
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
```
删除 743-1111 的原嵌套 `def open_wifi_adb_dialog():` 整段。
把 1113 行的按钮 command 改为:
```python
wifi_adb_btn = ttk.Button(
top,
text="WiFi ADB",
command=lambda: _open_wifi_adb_dialog(
root,
adb_exe=adb_exe,
on_line=on_line,
refresh_devices=refresh_devices,
),
)
```
- [ ] **Step 4: 验证语法**
```bash
python -m py_compile gui/gui_app.py gui/components/wifi_adb_dialog.py
```
Expected: 无输出
- [ ] **Step 5: 跑测试**
```bash
pytest -x
```
Expected: 全部 PASS
- [ ] **Step 6: 行数核对 + commit**
```bash
wc -l gui/gui_app.py
git status --short
git add gui/gui_app.py gui/components/wifi_adb_dialog.py
git commit -m "refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (<old> → <new>)"
git push
```
---
## Task 3: 评估 P2(`load_config_to_ui` + `save_ui_to_config`)
P2 在 spec 里被标记为高风险(100+ Var)。只有 Task 1+2 完成且测试稳定时才做。
- [ ] **Step 1: 数 Var 数量**
```bash
grep -nE "^\s+[a-zA-Z_]+_var = " gui/gui_app.py | wc -l
```
如果数量 ≥ 50,跳过 Task 3,直接进 Task 4。
如果 < 50,继续。
- [ ] **Step 2: 如果继续,设计 dataclass 聚合 Var**
读 2748-3402 列出所有用到的 Var,定义:
```python
# gui/components/config_io.py
@dataclass
class ConfigVars:
y_var: tk.IntVar
needswitch_var: tk.BooleanVar
# ... 全部
```
抽出函数:
```python
def load_config_to_ui(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
def save_ui_to_config(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
```
实施步骤参考 Task 2 的 Step 1-6。
如果改动量过大或测试卡住,**回滚并跳过 P2**。
---
## Task 4: 抽 `refresh_reservations` 到 `components/reservations_view.py`
**Files:**
- Create: `gui/components/reservations_view.py`
- Modify: `gui/gui_app.py:4530-4805` (删原闭包),改调用点
- [ ] **Step 1: 列出依赖**
读 4530-4805,记录捕获的 widgets(主要是 `reservations_tree: ttk.Treeview`)、状态变量、回调。
- [ ] **Step 2: 创建模块,函数签名**
```python
# gui/components/reservations_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable
def refresh_reservations(
tree: ttk.Treeview,
*,
on_line: Callable[[str], None] = lambda _msg: None,
) -> None:
"""刷新预约 Tab 的 Treeview。"""
# body 来自原 4530-4805
```
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
- [ ] **Step 3: 修改 `gui_app.py`**
```python
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
# 原 def refresh_reservations(): ... 改为:
def refresh_reservations():
_refresh_reservations_impl(reservations_tree, on_line=on_line)
```
保留薄包装 `def refresh_reservations()`,因为 `auto_refresh_reservations` 等地方仍以闭包形式调用它。
- [ ] **Step 4: 验证 + 测试 + commit**
```bash
python -m py_compile gui/gui_app.py gui/components/reservations_view.py
pytest -x
wc -l gui/gui_app.py
git add gui/gui_app.py gui/components/reservations_view.py
git commit -m "refactor(gui): 抽 refresh_reservations 到 components/reservations_view (<old> → <new>)"
git push
```
---
## Task 5: 抽 `refresh_high_value_rooms` 到 `components/high_value_view.py`
**Files:**
- Create: `gui/components/high_value_view.py`
- Modify: `gui/gui_app.py:4805-5085`
- [ ] **Step 1: 列出依赖**
读 4805-5085,记录捕获的 widgets(主要是 `high_value_rooms_tree: ttk.Treeview`)、状态变量、回调。
- [ ] **Step 2: 创建模块,函数签名**
```python
# gui/components/high_value_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable
def refresh_high_value_rooms(
tree: ttk.Treeview,
*,
on_line: Callable[[str], None] = lambda _msg: None,
) -> None:
"""刷新高价值房间 Tab 的 Treeview。"""
# body 来自原 4805-5085
```
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
- [ ] **Step 3: 修改 `gui_app.py`**
```python
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
# 原 def refresh_high_value_rooms(): ... 改为薄包装:
def refresh_high_value_rooms():
_refresh_high_value_rooms_impl(high_value_rooms_tree, on_line=on_line)
```
- [ ] **Step 4: 验证 + 测试 + commit**
```bash
python -m py_compile gui/gui_app.py gui/components/high_value_view.py
pytest -x
wc -l gui/gui_app.py
git add gui/gui_app.py gui/components/high_value_view.py
git commit -m "refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (<old> → <new>)"
git push
```
---
## Task 6: 抽 `do_screenshot` + `_bind_screenshot_button` 到 `components/screenshot_action.py`
**Files:**
- Create: `gui/components/screenshot_action.py`
- Modify: `gui/gui_app.py:3402-3651`
- [ ] **Step 1: 列出依赖**
读 3402-3651。`do_screenshot` 依赖:`adb_exe`、状态 Label、图片预览刷新回调、ADB 截图工具函数。
- [ ] **Step 2-4: 抽出,签名:**
```python
def do_screenshot(
*,
adb_exe: str,
on_line: Callable[[str], None],
on_done: Callable[[str], None], # 截图保存路径
status_label: ttk.Label | None = None,
) -> None:
...
def bind_screenshot_button(
btn: ttk.Button,
*,
adb_exe: str,
on_line: Callable[[str], None],
on_done: Callable[[str], None],
status_label: ttk.Label | None = None,
) -> None:
btn.configure(command=lambda: do_screenshot(
adb_exe=adb_exe, on_line=on_line, on_done=on_done, status_label=status_label
))
```
调用点同 Task 4。
commit msg: `refactor(gui): 抽 do_screenshot 到 components/screenshot_action (<old> → <new>)`
---
## Task 7: 抽 `refresh_actions_log` + 搜索栏 到 `components/actions_log_view.py`
**Files:**
- Create: `gui/components/actions_log_view.py`
- Modify: `gui/gui_app.py:4845-5070`
- [ ] **Step 1: 列出依赖**
读 4845-5070。包含:`configure_actions_log_colors`、`refresh_actions_log`、几个搜索方法 `search_in_actions_log`/`search_next_in_actions`/`search_prev_in_actions`/`clear_search_in_actions`/`on_actions_search_entry_key`。
- [ ] **Step 2-4: 设计**
设计成 1 个 `setup_actions_log_view(text_widget, search_entry, ...)` 一次性绑定所有,或者保留几个独立函数都接收 `text_widget` 参数。优先后者(更小步)。
签名:
```python
def configure_actions_log_colors(text_widget: tk.Text) -> None: ...
def refresh_actions_log(text_widget: tk.Text, *, on_line: Callable[[str], None]) -> None: ...
def search_in_actions_log(text_widget: tk.Text, search_entry: ttk.Entry, *, direction: int = 1) -> None: ...
```
`gui_app.py` 里保留薄包装让原闭包调用模式不变。
commit msg: `refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (<old> → <new>)`
---
## Task 8: 评估停止条件 + 收尾
- [ ] **Step 1: 检查停止条件**
```bash
wc -l gui/gui_app.py
```
满足以下任一即停:
1. ≤ 3000 行
2. 行数下降 < 50
3. 下一段需传 ≥ 50 个独立依赖
- [ ] **Step 2: 如果停止,写收尾说明**
如果停止,在 `docs/superpowers/specs/2026-05-30-split-gui-app-design.md` 末尾追加 `## Outcome` 段:列出实际抽出的模块、行数变化、未做的项。
```bash
git add docs/superpowers/specs/2026-05-30-split-gui-app-design.md
git commit -m "docs(specs): 补充 gui_app 拆分实际成果"
git push
```
- [ ] **Step 3: 报告**
总结输出给用户:
- 起始行数:5476
- 当前行数:`<X>`
- 抽出的模块列表
- pytest 状态
- 是否还有未抽的候选(可作为下一轮)
---
## 关键约束(每个 Task 都要遵守)
1. **AGENTS.md**:每个 Task 都要 commit + push,只 stage 本任务实际改的文件,不混入用户已有改动。
2. **不改行为**:抽取是纯重构,不修 bug、不优化性能、不删功能。
3. **失败回滚**:若 pytest 失败且修复需改 ≥ 2 个非目标文件,`git reset --hard HEAD~1`(本任务的 commit 还没 push),回到上一 Task 报告问题。
4. **每个 Task 验证后再开下一个**:不批量做。
5. **手工 smoke 推迟到批次末尾**:本计划的 pytest 不覆盖 GUI 交互(项目测试有意写得轻),抽取属纯重构,逻辑保持一致。每个 Task 完成后,在 Task 8 的收尾报告里提示用户:「请启动 GUI 跑一遍受影响功能(WiFi 对话框 / 预约 Tab / 高价值房间 / 截图按钮 / 操作日志 Tab),确认无回归。」用户 smoke 后若发现问题,定位到具体 Task 的 commit 回滚。
@@ -1,982 +0,0 @@
# Split WebUI Large Files Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server.
**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task.
**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes.
---
## Current Evidence
From the current worktree on 2026-05-31:
| File | Lines | Role |
|---|---:|---|
| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules |
| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring |
| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving |
| `webui/index.html` | 1232 | WebUI DOM structure and config bindings |
`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle.
## Stop Conditions
Stop this plan and write an outcome note when any one is true:
1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines.
2. The next split would require changing more than 3 of the large files in one task.
3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary.
4. Tests fail and the fix would require behavior changes outside the current responsibility.
## Verification Commands
Run these after every JavaScript or HTML task:
```powershell
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected:
```text
py_compile: exit code 0
pytest: all selected tests PASS
```
Run these after every CSS or visual task:
```powershell
python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1
```
Expected:
```text
py_compile: exit code 0
pytest: all selected tests PASS
```
For frontend visual changes, also start the Web GUI and inspect it in a browser:
```powershell
python gui\web_gui.py
```
Expected browser checks:
- `/` loads without a blank page.
- Console has no module load errors, syntax errors, or missing function errors.
- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width.
- At mobile width, command buttons wrap and panels remain readable.
## Static Loading Decision
The current page loads:
```html
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
<script src="app.js?v=console-20260520-theme-v35"></script>
```
Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them.
For CSS, use multiple `<link rel="stylesheet">` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split.
---
## Task 1: Add WebUI Static Asset Structure
**Files:**
- Create: `webui/js/README.md`
- Create: `webui/css/README.md`
- Modify: `webui/index.html`
- [ ] **Step 1: Create asset directory docs**
Create `webui/js/README.md`:
```markdown
# WebUI JavaScript modules
Classic browser scripts loaded by `webui/index.html`.
Load order matters:
1. `constants.js`
2. `dom.js`
3. `api.js`
4. focused feature scripts
5. `app.js`
Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout.
```
Create `webui/css/README.md`:
```markdown
# WebUI CSS modules
Plain CSS files loaded by `webui/index.html`.
Recommended order:
1. `tokens.css`
2. `base.css`
3. `layout.css`
4. `components.css`
5. focused panel or feature CSS
6. `styles.css` compatibility remainder
Keep selectors stable so existing HTML and JavaScript continue to work.
```
- [ ] **Step 2: Add no-op load anchors to `index.html`**
Insert comments around the existing assets:
```html
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
```
```html
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="app.js?v=console-20260520-theme-v35"></script>
```
- [ ] **Step 3: Verify**
Run:
```powershell
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected: selected tests PASS.
- [ ] **Step 4: Commit and push**
```powershell
git add webui/index.html webui/js/README.md webui/css/README.md
git commit -m "refactor(webui): add static module split structure"
git push
```
---
## Task 2: Extract JavaScript Constants and Copy
**Files:**
- Create: `webui/js/constants.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `constants.js`**
Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged:
```javascript
const UI_LIMITS = Object.freeze({
runLogMaxLines: 50000,
runLogMaxChars: 200000,
actionsLogMaxLines: 5000,
scrollBottomThresholdPx: 5,
screenshotPollMs: 1500,
logPollMs: 800,
statsPollMs: 1200,
});
const UI_CLASS = Object.freeze({
busy: "isBusy",
clickable: "isClickable",
collapsed: "isCollapsed",
listCollapsed: "isListCollapsed",
reservationHeader: "reservationHeader",
reservationBody: "reservationBody",
reservationsList: "reservationsList",
shotEmpty: "isShotEmpty",
statusRunning: "statusRunning",
statusIdle: "statusIdle",
statusError: "statusError",
});
const RUN_TONE = Object.freeze({
running: "running",
idle: "idle",
error: "error",
});
```
Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged.
- [ ] **Step 2: Remove moved constants from `app.js`**
Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now.
- [ ] **Step 3: Load `constants.js` before `app.js`**
Change the bottom of `webui/index.html` to:
```html
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="js/constants.js?v=console-20260531-split-1"></script>
<script src="app.js?v=console-20260531-split-1"></script>
```
- [ ] **Step 4: Verify**
Run:
```powershell
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected: both PASS.
- [ ] **Step 5: Browser smoke**
Start:
```powershell
python gui\web_gui.py
```
Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors.
- [ ] **Step 6: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/constants.js
git commit -m "refactor(webui): extract frontend constants"
git push
```
---
## Task 3: Extract DOM and Formatting Helpers
**Files:**
- Create: `webui/js/dom_utils.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `dom_utils.js`**
Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged:
```javascript
function $(id)
function setTextIfExists(id, text)
function clearEl(el)
function escapeHtml(s)
function fmtTime(ts)
function fmtNum(v)
function fmtDuration(seconds)
```
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete the moved function declarations only. Do not move UI initialization functions yet.
- [ ] **Step 3: Load `dom_utils.js` after `constants.js`**
```html
<script src="js/constants.js?v=console-20260531-split-2"></script>
<script src="js/dom_utils.js?v=console-20260531-split-2"></script>
<script src="app.js?v=console-20260531-split-2"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/dom_utils.js
git commit -m "refactor(webui): extract DOM and format helpers"
git push
```
---
## Task 4: Extract API Client Helpers
**Files:**
- Create: `webui/js/api_client.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `api_client.js`**
Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged:
```javascript
let _apiFailStreak = 0;
const _apiFailThreshold = 2;
let _csrfToken = null;
function setConnState(state)
function notifyApiOk()
function notifyApiFail()
async function apiGet(path)
async function getCsrfToken()
async function apiPost(path, body)
```
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
- [ ] **Step 2: Remove moved declarations from `app.js`**
Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`.
- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`**
```html
<script src="js/constants.js?v=console-20260531-split-3"></script>
<script src="js/dom_utils.js?v=console-20260531-split-3"></script>
<script src="js/api_client.js?v=console-20260531-split-3"></script>
<script src="app.js?v=console-20260531-split-3"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/api_client.js
git commit -m "refactor(webui): extract API client helpers"
git push
```
---
## Task 5: Extract Log View Behavior
**Files:**
- Create: `webui/js/log_views.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `log_views.js`**
Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`:
```javascript
function classifyLogLine(line)
function renderLogLineNode(line)
function appendLog(lines)
function renderRunLog()
function appendRunLogLines(lines)
async function fetchActionsLog()
function renderActionsLog()
```
Keep these shared state variables in `app.js` for this task:
```javascript
let runLogBuffer = [];
let runLogFilter = "";
let runLogMode = "filter";
let runSearchResultsBuffer = [];
let runSearchActive = false;
let actionsLogBuffer = [];
let actionsLogFilter = "";
```
Because classic scripts share global scope, `log_views.js` can keep using these names.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved function declarations.
- [ ] **Step 3: Load `log_views.js` before `app.js`**
```html
<script src="js/constants.js?v=console-20260531-split-4"></script>
<script src="js/dom_utils.js?v=console-20260531-split-4"></script>
<script src="js/api_client.js?v=console-20260531-split-4"></script>
<script src="js/log_views.js?v=console-20260531-split-4"></script>
<script src="app.js?v=console-20260531-split-4"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/log_views.js
git commit -m "refactor(webui): extract log view behavior"
git push
```
---
## Task 6: Extract Dashboard Renderers
**Files:**
- Create: `webui/js/dashboard_renderers.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `dashboard_renderers.js`**
Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`:
```javascript
function renderBars(containerId, dataMap, labelMap)
function renderTopContent(containerId, items)
function renderWinsTable(containerId, wins)
function renderTimeline(containerId, timeline)
function renderOverviewSparkline(svgId, timeline)
```
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved renderer declarations.
- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`**
```html
<script src="js/dashboard_renderers.js?v=console-20260531-split-5"></script>
<script src="app.js?v=console-20260531-split-5"></script>
```
Keep all earlier module script tags before `dashboard_renderers.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/dashboard_renderers.js
git commit -m "refactor(webui): extract dashboard renderers"
git push
```
---
## Task 7: Extract Config Form Binding
**Files:**
- Create: `webui/js/config_form.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `config_form.js`**
Move these config-related functions from `app.js` into `webui/js/config_form.js`:
```javascript
function getConfigBoundElements()
function syncMirrorFields()
function getConfigValue(cfg, key)
function coerceValue(type, raw, isCheckbox)
function applyConfigToUI(cfg)
function collectConfigFromUI()
async function loadConfig()
async function saveConfig()
```
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved config declarations.
- [ ] **Step 3: Load `config_form.js` before `app.js`**
```html
<script src="js/config_form.js?v=console-20260531-split-6"></script>
<script src="app.js?v=console-20260531-split-6"></script>
```
Keep all earlier module script tags before `config_form.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/config_form.js
git commit -m "refactor(webui): extract config form bindings"
git push
```
---
## Task 8: Extract Polling and Device Actions
**Files:**
- Create: `webui/js/runtime_actions.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `runtime_actions.js`**
Move these functions from `app.js` into `webui/js/runtime_actions.js`:
```javascript
async function refreshDevices()
function decorateDeviceSelect()
function selectedDeviceId()
async function postDeviceAction(path, body, successPrefix)
async function forceStopRun()
async function sendBackKey()
async function wifiEnable()
async function wifiConnect()
async function wifiDisconnect()
async function tryAutoReconnectLastWifi()
async function wifiScan()
async function startRun()
async function testYanghao()
async function testComment()
async function stopRun()
async function pollLogs()
async function pollReservations()
async function pollHighValueRooms()
async function pollStats()
function startPolling()
function startStatsPolling()
```
Keep `DOMContentLoaded` event wiring in `app.js`.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved runtime declarations.
- [ ] **Step 3: Load `runtime_actions.js` before `app.js`**
```html
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
<script src="app.js?v=console-20260531-split-7"></script>
```
Keep all earlier module script tags before `runtime_actions.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/runtime_actions.js
git commit -m "refactor(webui): extract runtime actions and polling"
git push
```
---
## Task 9: Reduce `app.js` to Initialization Glue
**Files:**
- Create: `webui/js/ui_init.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Move UI initialization helpers**
Move these functions into `webui/js/ui_init.js`:
```javascript
function initTheme()
function ensureToastContainer()
function toast(message, kind = "info", { duration = 3500 } = {})
function initConfigSearch()
function initFooter()
function attachCopyButtons()
function initKeyboardShortcuts()
function initHeaderScroll()
function initShotFullscreen()
function applyKbdHints()
function initStickySectionShadow()
function initShortcutsHelp()
function updateTabBadge(target, count)
function startReservationsCountdownTick()
function initTabs()
function attachNumberSteppers()
function pollShot()
function startShotPolling()
function setButtonBusy(id, busy)
function setRunOverview(state, meta, tone)
function updateDeviceOverview()
```
- [ ] **Step 2: Keep `app.js` as bootstrapping only**
After this task, `app.js` should contain:
```javascript
window.addEventListener("DOMContentLoaded", async () => {
initTheme();
initTabs();
initConfigSearch();
initFooter();
attachCopyButtons();
initShotFullscreen();
initHeaderScroll();
initKeyboardShortcuts();
initShortcutsHelp();
initStickySectionShadow();
attachNumberSteppers();
applyKbdHints();
syncMirrorFields();
await refreshDevices();
await loadConfig();
startPolling();
startStatsPolling();
startShotPolling();
startReservationsCountdownTick();
pollLogs();
pollStats();
pollShot();
pollReservations();
pollHighValueRooms();
});
```
During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`.
- [ ] **Step 3: Verify and smoke**
Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save.
- [ ] **Step 4: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/ui_init.js
git commit -m "refactor(webui): reduce app script to initialization glue"
git push
```
---
## Task 10: Split CSS Tokens and Base Rules
**Files:**
- Create: `webui/css/tokens.css`
- Create: `webui/css/base.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract theme tokens**
Move these ranges from `styles.css` into `webui/css/tokens.css`:
- `:root { ... }` light theme token block
- `:root[data-theme="dark"] { ... }` dark theme token block
- reduced-motion token or global animation defaults that are pure variables
Do not rename variables.
- [ ] **Step 2: Extract base element rules**
Move base reset and generic element rules into `webui/css/base.css`:
- `*`, `html`, `body`
- `button`, `input`, `select`, `textarea`
- generic focus-visible rules
- global scrollbar rules
- generic utility classes that are not tied to one panel
- [ ] **Step 3: Load extracted CSS before `styles.css`**
```html
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-1" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-1" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-1" />
```
- [ ] **Step 4: Verify and smoke**
Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css
git commit -m "refactor(webui): extract CSS tokens and base rules"
git push
```
---
## Task 11: Split CSS Layout and Shared Components
**Files:**
- Create: `webui/css/layout.css`
- Create: `webui/css/components.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract layout rules**
Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors.
- [ ] **Step 2: Extract shared component rules**
Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors.
- [ ] **Step 3: Load CSS in stable order**
```html
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-2" />
```
- [ ] **Step 4: Verify and smoke**
Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css
git commit -m "refactor(webui): extract CSS layout and shared components"
git push
```
---
## Task 12: Split CSS Feature Panels
**Files:**
- Create: `webui/css/panels.css`
- Create: `webui/css/logs.css`
- Create: `webui/css/charts.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract panel-specific styles**
Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`.
- [ ] **Step 2: Extract log styles**
Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`.
- [ ] **Step 3: Extract chart/table styles**
Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`.
- [ ] **Step 4: Load CSS in stable order**
```html
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/panels.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/logs.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/charts.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-3" />
```
- [ ] **Step 5: Verify and smoke**
Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping.
- [ ] **Step 6: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css
git commit -m "refactor(webui): extract CSS feature panels"
git push
```
---
## Task 13: Decide Whether to Split `index.html`
**Files:**
- Modify: `webui/index.html`
- Optional create: `webui/partials/README.md`
- [ ] **Step 1: Recount file sizes**
Run:
```powershell
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
```
- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines**
If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet.
If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of:
- server-side partial injection in `gui/web_gui.py`
- client-side fetch of static partials
- build-time HTML generation
- [ ] **Step 3: Commit only if docs are added**
If `webui/partials/README.md` is created:
```powershell
git add webui/partials/README.md
git commit -m "docs(webui): record HTML partial split decision"
git push
```
---
## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable
**Files:**
- Create: `gui/web_gui_pkg/static_handler.py`
- Create: `gui/web_gui_pkg/request_parsing.py`
- Create: `gui/web_gui_pkg/routes.py`
- Modify: `gui/web_gui.py`
- Test: `tests/test_webgui.py`
- [ ] **Step 1: Extract request parsing helpers**
Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance:
```python
def send_json(handler: BaseHTTPRequestHandler, obj: object, status: int = 200) -> None:
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Cache-Control", "no-store")
handler.send_header("Content-Length", str(len(data)))
handler.end_headers()
handler.wfile.write(data)
```
```python
def read_json(handler: BaseHTTPRequestHandler) -> dict:
n = int(handler.headers.get("Content-Length") or 0)
raw = handler.rfile.read(n) if n > 0 else b"{}"
try:
value = json.loads(raw.decode("utf-8"))
except Exception:
return {}
return value if isinstance(value, dict) else {}
```
Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first.
- [ ] **Step 2: Extract static file serving**
Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`:
```python
def serve_static(
handler: BaseHTTPRequestHandler,
*,
webui_dir: str,
rel_path: str,
log_error: Callable[[str], None],
) -> None:
# paste current Handler._serve_static body and replace:
# self -> handler
# WEBUI_DIR -> webui_dir
# _wg_log(...) -> log_error(...)
```
Keep `Handler._serve_static` as:
```python
def _serve_static(self, rel_path: str) -> None:
serve_static(
self,
webui_dir=WEBUI_DIR,
rel_path=rel_path,
log_error=lambda msg: _wg_log(msg, level="ERROR"),
)
```
- [ ] **Step 3: Verify**
Run:
```powershell
python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1
pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1
```
Expected: PASS.
- [ ] **Step 4: Commit and push**
```powershell
git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py
git commit -m "refactor(webgui): extract request and static helpers"
git push
```
---
## Task 15: Final Outcome Note
**Files:**
- Modify: this plan file
- [ ] **Step 1: Record final sizes**
Run:
```powershell
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
```
- [ ] **Step 2: Append outcome**
Append:
```markdown
## Outcome
- `webui/app.js`: 2512 -> actual final line count
- `webui/styles.css`: 3745 -> actual final line count
- `webui/index.html`: 1232 -> actual final line count
- `gui/web_gui.py`: 1663 -> actual final line count
- Extracted JS modules: actual module filenames
- Extracted CSS modules: actual module filenames
- Verification: exact pytest log path and browser smoke result
- Remaining large files: actual top remaining files from the final size command
```
- [ ] **Step 3: Commit and push**
```powershell
git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md
git commit -m "docs(webui): record large-file split outcome"
git push
```
---
## Execution Notes
- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one.
- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task.
- Do not introduce a frontend build step in this plan.
- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean.
- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit.
- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade.
- Project rule: only stage files changed by the current task.
@@ -1,244 +0,0 @@
# 拆分 gui/gui_app.py 设计文档
## 背景
`gui/gui_app.py` 当前 5476 行,几乎全部代码都嵌在单个 `main()` 函数里,
内含 50+ 个闭包,捕获大量 widgets 和 tkinter Var。文件已经被多轮抽取过:
- `5649 → 5537`:`ThreadSafeLogWriter` → `components/log_writer`
- `5539 → 5370`:`_open_realtime_viewer_impl` → `components/realtime_viewer`
- `6339 → 5634`:`refresh_stats` 字符串格式化 → `components/stats_formatter`
继续按相同思路把内聚闭包抽到 `gui/components/*`,主文件继续瘦身。
## 目标
迭代式抽取 `gui/gui_app.py` 中的内聚闭包,主文件越变越小,
**不改变任何 GUI 运行行为**。
### 成功标准
1. `gui/gui_app.py` 行数显著下降(目标:≤ 3000 行;继续视边际收益决定是否再抽)
2. `pytest` 全绿
3. 每次抽取产生一个独立 commit,保持小步可回滚
4. GUI 启动 + 主要交互路径无回归(手工 smoke:启动 GUI、打开 WiFi 对话框、加载配置、截图、查看日志)
### 非目标
- 不重构 GUI 整体架构(不引入 MVC/MVVM)
- 不改变 `gui_app.py` 对外暴露的入口(`main()`、`format_gui_log_line()`)
- 不优化性能、不修 bug(除非抽取过程中发现)
- 不动 `gui/web_gui.py`(属于下一轮独立 spec)
## 抽取候选清单
按「行数 × 边界清晰度」排序(行数粗略统计):
| 优先级 | 闭包 | 行范围 | 行数 | 目标文件 | 主要依赖 |
|---|---|---|---|---|---|
| P1 | `open_wifi_adb_dialog` | 743-1588 | 845 | `components/wifi_adb_dialog.py` | ADB 工具 + 几个回调 |
| P2 | `load_config_to_ui` + `save_ui_to_config` | 2748-3402 | 654 | `components/config_io.py` | 100+ tkinter Var(需聚合)|
| P3 | `refresh_reservations` | 4530-4805 | 275 | `components/reservations_view.py` | 1-2 个 Treeview + 路径 |
| P4 | `refresh_high_value_rooms` | 4805-5085 | ~280 | `components/high_value_view.py` | 1 个 Treeview + 路径 |
| P5 | `do_screenshot` + `_bind_screenshot_button` | 3402-3651 | 249 | `components/screenshot_action.py` | ADB exe + 路径 + 状态 Label |
| P6 | `refresh_actions_log` + 搜索栏 | 4892-5070 | ~178 | `components/actions_log_view.py` | Text widget + 路径 |
**估算**:完整抽完 P1-P6 约减 2480 行 → 主文件 ~3000 行。
若 P2 风险评估后觉得不值得做,可跳过,仍能减约 1830 行 → ~3650 行。
## 抽取模式(每轮通用)
每个候选段按以下步骤处理:
### 1. 摸清依赖
读完整段代码,列出:
- 捕获的 `main()` 局部变量(widgets / Vars / 路径 / 状态)
- 调用的 `main()` 内其它闭包(回调)
- 调用的 module-level 函数 / 项目其它模块函数
### 2. 设计签名
把闭包改造为顶层函数:
```python
# components/<feature>.py
def <feature_action>(
parent: tk.Misc, # 父窗口或容器
*,
deps: <FeatureDeps>, # 依赖注入容器
on_line: Callable[[str], None], # 日志回调
...
) -> <return-type>:
"""..."""
```
依赖容器优先用 `dataclass`(命名参数太多时):
```python
@dataclass
class <FeatureDeps>:
adb_exe: str
ip_var: tk.StringVar
refresh_devices: Callable[[], None]
# ...
```
### 3. 抽取 + 注入
- 在 `gui/components/<feature>.py` 写新函数
- 在 `gui_app.py` 原位置:删旧闭包,import 新函数,传依赖调用
### 4. 验证
```bash
pytest # 全部通过
python -m py_compile gui/gui_app.py gui/components/<feature>.py
# 手工 smoke:启动 GUI 走一遍受影响功能
```
### 5. 提交
按 AGENTS.md 规则:
- `git status` 检查只改了预期文件
- `git add` 具体路径,不用 `-A`
- commit 消息格式参考历史:`refactor(gui): 抽 <feature> 到 components/<file> (<旧行数> → <新行数>)`
- `git push`
## 风险
| 风险 | 缓解 |
|---|---|
| 闭包捕获 Var 漏传 → 配置项静默丢失 | P2 用 `dataclass` 聚合 Var 引用;先写完整测试再改 |
| GUI 交互回归(按钮回调失效等) | 每轮手工 smoke;优先抽边界清晰的 P1/P5 验证流程 |
| `mainloop` / `after()` 调度跨闭包失效 | 显式把 `root` 或 `tk_widget.after` 当依赖传入 |
| import 循环(components → gui_app) | components/* 不允许 import gui_app;只接收依赖参数 |
## 停止条件
满足任一即停手,向用户报告本轮成果:
1. `gui_app.py` ≤ 3000 行
2. 下一个候选段需要传 ≥ 50 个独立依赖(信号:应该先把 widgets 聚成一个 `UiState`,那是另一个 spec)
3. 抽取后 `gui_app.py` 行数下降 < 50(边际收益太小)
4. 某轮抽取后 pytest 失败且修复需要改动多个非目标文件(信号:风险扩散,停下复盘)
## 实现顺序
按 P1 → P2 → P3 → P4 → P5 → P6,每段独立 commit。
P2 视 P1 完成后情况评估(如果 P1 已经把主文件压到很小,P2 可推迟)。
## 测试策略
- **现有 pytest**:每轮必须保持全绿(不需要为抽取新增单测,因为是纯重构)
- **手工 smoke**(每轮都要走一遍受影响路径):
- P1:启动 → 打开 "WiFi ADB" 对话框 → 扫描设备 → 连接
- P2:启动 → 修改若干配置项 → 关闭 → 重启 → 检查配置已保存
- P3/P4:启动 → 切到「预约」/「高价值房间」Tab → 验证刷新
- P5:启动 → 截图按钮 → 检查图片落盘
- P6:启动 → 切到「操作日志」Tab → 搜索
## Out of Scope
- `gui/web_gui.py`(1810 行)—— 下一轮独立 spec
- `douyin/core/*` 几个 1000+ 行业务文件 —— 下一轮独立 spec
- 引入新的 GUI 框架或异步模式
- 单元测试覆盖率提升
## Outcome(2026-05-30 实施完成)
**起始**:5476 行
**结束**:178 行
**降幅**:5298 行(-96.7%)
**新增模块**:54 个 component 文件
### 主文件最终结构(178 行)
```
imports 45 行 (gui_core / 14 个 components / stdlib)
warnings 抑制 / format_gui_log_line 18 行
def main(): ~115 行
setup_root_window
setup_log_pipeline ← (queue + ThreadSafeLogWriter + on_line + Runner)
setup_top_device_bar ← (设备选择 + WiFi 工具)
build_config_vars ← (127 个 tk Var)
setup_left_config_area ← (PanedWindow + 7 配置 Tab + load/save IO)
setup_right_main_area ← (Notebook + 9 Tab + actions + pump_logs)
setup_top_buttons ← (保存配置 + 截图+OCR)
setup_periodic_refreshers ← (启动延迟 + 周期刷新)
setup_close_handler ← (WM_DELETE_WINDOW)
refresh_devices() / mainloop()
```
### 抽取阶段总结
实施分 4 个阶段:
**阶段 1:闭包/视图抽取(5476 → 3590 行,-34%)**
把 `main()` 内的内聚闭包和视图刷新函数抽到独立模块。共 17 个模块:
wifi_adb_scan_dialog / wifi_adb_dialog / reservations_view / high_value_view /
screenshot_action / actions_log_view / wifi_adb_pick_dialog / wifi_adb_reconnect /
ocr_results_view / log_pump / win_record_view / preview_view /
wifi_adb_one_click_scan / run_log_view / text_search /
logging_config_io / run_params_builder。
**阶段 2:Var 聚合 + Tab UI(3590 → 1373 行,-44% → -75%)**
- `config_io.py`(load/save 640 行 → 1 个模块)用 dict-of-vars 模式
- `build_config_vars()` 工厂集中创建 127 个 tk Var
- 7 个 Tab UI(debug / logging / yanghao / reservation / run / filter / realtime)抽
到独立 `setup_*_tab(parent, vars_=_vars_)`,直接接受 vars 全集
**阶段 3:右侧 Tab + 工具栏 + 模板复用(1373 → 519 行,-75% → -90.5%)**
- log_search_toolbar / actions_log_toolbar 用 dataclass + handles 返回
- win_record_tab / preview_tab / log_tab 整段抽出
- simple_tabs.py 提供 setup_simple_text_tab / setup_text_tab_with_refresh /
setup_stats_tab / setup_actions_log_tab / setup_ocr_results_tab 复用模板
- main_notebook / action_buttons / top_buttons / top_device_bar /
log_pipeline / periodic_refreshers / log_text_colors / keywords_tab 全部抽出
**阶段 4:聚合层 + 死代码清理(519 → 178 行,-90.5% → -96.7%)**
最后阶段把 main() 里剩余的"装配脉络"打包成更高层组件,清理失效的导入和死注释:
- `setup_root_window`: ttkbootstrap fallback + root window
- `setup_left_config_area`: PanedWindow 布局 + 7 配置 Tab + load/save IO
- `setup_right_main_area`: Notebook + 9 Tab + actions + pump_logs
- 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var)
- 死注释清理 / 重复 import / 冗余 dict 字面量(_config_io_vars 复用 _vars_ 全集)
- 重复 lambda 去重(theme_getter / _open_realtime_viewer)
### 抽取模式(54 个 components 按用途分类)
| 类型 | 模块 |
|---|---|
| WiFi ADB(6 个) | wifi_adb_scan_dialog / wifi_adb_dialog / wifi_adb_pick_dialog / wifi_adb_reconnect / wifi_adb_one_click_scan / top_device_bar |
| Tab 视图(8 个) | reservations_view / high_value_view / actions_log_view / ocr_results_view / win_record_view / preview_view / run_log_view / log_pump |
| Tab UI 容器(13 个) | run_tab / filter_tab / reservation_tab / yanghao_tab / debug_tab / logging_tab / keywords_tab / log_tab / preview_tab / win_record_tab / realtime_tab / simple_tabs / main_notebook |
| 工具栏(2 个) | log_search_toolbar / actions_log_toolbar |
| 配色 / 状态(3 个) | log_text_colors / text_search / screenshot_action |
| 配置序列化(4 个) | logging_config_io / run_params_builder / config_io / config_vars |
| 顶部 / 底部按钮(2 个) | top_buttons / action_buttons |
| 系统调度(2 个) | log_pipeline / periodic_refreshers |
| 高层聚合(3 个) | root_window / left_config_area / right_main_area |
| 已有共用(11 个) | log_writer / log_viewer / log_color_config / mapping_table / mapping_utils / device_selector / actions_log_viewer / error_log_viewer / realtime_viewer / stats_formatter / __init__ |
### 验证
- 每轮抽取后 `pytest` 全绿(1374 passed),包括 `test_gui_app_smoke.py` 启动 smoke 和
`test_gui_webui_sync.py` GUI/WebUI 配置 key 同步检查。
- 共 7 次 pytest 失败均能定位修复(具体错误参见各次 commit message):
- `_preview_view` 在 `update_image_list` 之前被引用
- `enable_ocr_mode1_var` 因含数字未被正则替换(2 次)
- `BOTH` 常量 / `ScrolledText` import 缺失
- sync 工具锚点失效 → 让工具改读 `config_io.py` + `realtime_tab.py`
- `image_var` 在 `setup_top_buttons` 调用时还没创建 → 调整顺序
- 未做手工 GUI smoke(建议用户启动 GUI 走一遍 WiFi 对话框 / 各 Tab,确认无回归)。
### 停止原因
主文件已从 5476 → 178(-96.7%)。当前 main() 是清晰的"装配胶水":每个 setup_*
调用对应一个明确的功能区。继续抽要么打散这个装配脉络,要么把整个 main 改造成
`GuiApp` 类(MVC/MVVM),都属于另一个 spec。`pytest` 1374 全绿。
@@ -8,10 +8,11 @@ from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, Optional
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def find_and_open_fudai_detail(
@@ -291,12 +292,9 @@ def find_and_open_fudai_detail(
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
_raw = Image.open(screenshot_path)
try:
_raw.load()
pic_rgb_full = _raw.convert("RGB")
finally:
_raw.close()
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
try:
box_r = 30
coord_box = (
@@ -5,8 +5,13 @@ handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def handle_no_fudai_situation(
@@ -5,8 +5,14 @@ handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def handle_stage_after_diagnosis(
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
@@ -1,91 +0,0 @@
"""douyin/core/fudai_modules/fudai_device_control - 共享 ADB 设备操作
抽出 handle_detail_helpers 中重复 2 次的兜底 swipe 逻辑:
- _handle_error_status (L266-318)
- _fallback_swipe_up (L1187-1239)
两处都做"没有 swipe_up_to_next_live 时直接 ADB shell input swipe,失败再回退到
operation.swipe"。提到这里统一管理。
"""
from __future__ import annotations
import os
import subprocess
from typing import Any
def fallback_swipe_up_via_adb(self: Any) -> None:
"""没有 swipe_up_to_next_live 时用 ADB shell input swipe 兜底切换直播间。
流程:
1. 按 self.resolution_ratio_x/y(默认 1080x2400)计算起止坐标
2. 优先调用 self.operation._adb_path() 获取 adb 路径
3. 直接 subprocess.run ADB shell input swipe
4. 任何异常 → 回退到 self.operation.swipe(...)
主要用于 _handle_error_status 的"连续 task_count_zero≥3 强制切房"分支
和 _fallback_swipe_up 的"没有 swipe_up_to_next_live 时兜底"。
"""
try:
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
try:
if hasattr(self.operation, "_adb_path"):
adb_cmd = self.operation._adb_path()
else:
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if adb_cmd.startswith('"') and adb_cmd.endswith('"'):
adb_cmd = adb_cmd[1:-1]
cmd = [
adb_cmd,
"-s",
str(self.device_id),
"shell",
"input",
"swipe",
str(int(start_x)),
str(int(start_y)),
str(int(end_x)),
str(int(end_y)),
"300",
]
subprocess.run(
cmd,
timeout=5.0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
def swipe_up_or_fallback(self: Any) -> None:
"""优先调 self.swipe_up_to_next_live(),否则走 fallback_swipe_up_via_adb 兜底。
替代 handle_detail_helpers 中 L266-318 的内联兜底实现。
"""
try:
if hasattr(self, "swipe_up_to_next_live"):
self.swipe_up_to_next_live()
return
except Exception:
pass
fallback_swipe_up_via_adb(self)
@@ -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
-217
View File
@@ -1,217 +0,0 @@
"""douyin/core/fudai_modules/init_helpers - fudai_analyse 配置默认值与运行时状态初始化
把 fudai_analyse.__init__ 中"配置字段默认值 + 运行时状态字段初始化 + 状态文件
路径解析"的整段抽出来。原 __init__ 保留:设备/分辨率、operation 实例、日志系统
初始化、_run_id、_log_kv 等需要早期就绪的核心字段。
入口:apply_fudai_defaults(self) 一次性把所有"普通字段默认值"应用到实例。
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional, Tuple
def apply_fudai_defaults(self: Any) -> None:
"""把 fudai_analyse 实例的所有配置默认值 + 运行时状态字段一次性初始化。
依赖前提(必须由 caller 在调用前已设置):
- self.operation, self.device_id, self.y_pianyi
- self.resolution_ratio_x, self.resolution_ratio_y
- self._log_kv 等日志相关字段
本函数不调用 load_config(让 caller 决定时机)。
"""
self._forced_reservation_detail = None
self._forced_reservation_fudai_x = None
# 进入直播间后诊断与阶段流转所需的一些状态
self._last_diag_stage = "INIT"
self._last_diag_seen = "-"
self._last_diag_ts = 0.0
# 30 分钟超时相关:记录最后一次成功参与福袋的时间
self._last_successful_attend_ts = 0.0
self._no_attend_timeout_minutes = 30.0
self._run_start_ts = time.time()
# 预约状态上次写盘时间(初始化以避免 attribute-defined-outside-init 警告)
self._reservations_state_last_write_ts = 0.0
self.last_fudai_x = 0 # 上次检测到的福袋图标 X 坐标(用于优化搜索)
# 与配置相关的核心字段
self.contains_not_want = []
self.contains_want = []
self.min_prize_value_yuan = 0.0
self.min_participants = 0
self.max_participants = 0
self.skip_if_countdown_gt_seconds = 900
self.skip_if_countdown_lt_seconds = 0
self.no_fudai_watchdog_enabled = False
# 福袋图标检测节流相关默认值
self.fudai_icon_retry_delay_seconds = 0.6
self.fudai_icon_max_wait_seconds = 5.0
self.fudai_exit_after_misses = 999999
self.enable_back_on_misses = False
self.fudai_click_wait_seconds = 1.0
self.switch_room_wait_after_stage_diag_seconds = 7.0
self.swipe_duration_ms = 600
self.fudai_find_max_attempts = 10 # 已废弃,保留兼容性
# 优化查找器相关配置
self.fudai_finder_optimized_enabled = True
self.fudai_click_verify_enabled = True
self.fudai_find_max_retries = 3
self.screenshot_diagnose_min_interval_seconds = 8.0
self.lucky_draw_red_ratio_threshold = 0.9
self.coupon_template_match_threshold = 0.75
self.attend_button_red_ratio_threshold = 0.25
self.fansclub_join_red_ratio_threshold = 0.25
self.live_room_match_threshold = 0.8
self.fudai_template_match_enabled = False
self.fudai_template_match_threshold = 0.7
# 高价值福袋 / 预约相关配置
self.high_value_fudai_enabled = False
self.high_value_fudai_threshold_yuan = 500.0
self.high_value_fudai_join_ahead_seconds = 100
self.high_value_fudai_max_swipe_back = 35
self.high_value_fudai_max_reservations = 3
self.high_value_fudai_after_action = "continue"
self.high_value_fudai_after_stay_seconds = 120
self.high_value_fudai_poll_before_seconds = 10.0
# 高价值直播间"回访"相关
self.high_value_room_revisit_enabled = False
self.high_value_room_revisit_only_current_run = False
self.high_value_room_revisit_min_interval_seconds = 300
self.high_value_room_revisit_max_per_run = 5
self.high_value_room_revisit_min_prize_value = 0.0
self.high_value_room_revisit_max_age_days = 30
# 粉丝团相关配置
self.auto_join_fansclub = False
self.fansclub_fail_action = "stay"
# 预约回退相关
self.reservation_back_verify_enabled = True
self.reservation_back_swipe_delay = 0.6
# 滑动次数重置相关
self.reset_after_swipes_enabled = False
self.reset_after_swipes = 10
# 意外返回桌面自救相关(坐标兜底,主路径已改用 launch_package 包名启动)
self.desktop_icon_x = 153
self.desktop_icon_y = 260
self.yanghao_fallback_live_x = 540
self.yanghao_fallback_live_y = 2000
self.yanghao_fallback_enter_live_x = 540
self.yanghao_fallback_enter_live_y = 1200
# 推荐页养号默认配置
_apply_yanghao_defaults(self)
# 预约运行时状态(单次运行内有效)
self.reservations = []
self._first_run_once_basic = True
self.room_pos = 0
self.reservation_focus_until_ts = 0.0
self.reservation_after_action_pending = False
self.reset_to_list_after_reservations = False
self.queue_full_waiting_at_earliest = False
# 预约队列状态文件 + 清理映射表导出文件
_resolve_reservations_state_path(self)
_cleanup_old_room_pos_map_files(self)
# 已记录统计的福袋跟踪
self._recorded_fudai_stats = set()
# 运行时状态标志
self.needswitch = None
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._skip_stage_diagnosis_and_find_fudai = False
self._just_switched_room = False
# 高价值房间重访相关状态
self._last_high_value_revisit_ts = time.time()
self._current_run_revisit_count = 0
self._current_run_high_value_rooms = []
self._last_fudai_detail_tuple = None
self._current_fudai_future_ts = 0.0
self._current_fudai_content = ""
self._fudai_detail_first_read = False
self._fudai_detail_consecutive_failures = 0
self._detail_closed_by_attend = False
self._lottery_result_expected_ts = 0.0
self._lottery_wait_start_ts = 0.0
def _apply_yanghao_defaults(self: Any) -> None:
"""推荐页养号相关默认配置。"""
self.yanghao_enabled = True
self.yanghao_enable_actions = True
self.yanghao_step_screenshot = False
self.yanghao_recommend_duration_seconds = 60
self.yanghao_recommend_interval_seconds = 0
self.yanghao_like_prob = 0.15
self.yanghao_fav_prob = 0.05
self.yanghao_comment_prob = 0.0
self.yanghao_dwell_on_action_min_seconds = 5.0
self.yanghao_dwell_on_action_max_seconds = 30.0
self.yanghao_icon_roi_size = 180
self.yanghao_icon_match_threshold = 0.70
self.yanghao_like_roi_scale = 1.5
self.yanghao_fav_roi_scale = 1.5
self.yanghao_like_icon_match_threshold = None
self.yanghao_fav_icon_match_threshold = None
self.yanghao_like_icon_x = 0
self.yanghao_like_icon_y = 0
self.yanghao_fav_icon_x = 0
self.yanghao_fav_icon_y = 0
self.yanghao_like_roi_offset_x = 0
self.yanghao_like_roi_offset_y = 0
self.yanghao_fav_roi_offset_x = 0
self.yanghao_fav_roi_offset_y = 0
self._last_yanghao_ts = 0.0
self.yanghao_comment_btn_x = 0
self.yanghao_comment_btn_y = 0
self.yanghao_comment_input_x = 0
self.yanghao_comment_input_y = 0
self.yanghao_comment_send_x = 0
self.yanghao_comment_send_y = 0
self.yanghao_comment_close_x = 0
self.yanghao_comment_close_y = 0
self.yanghao_comment_texts = []
def _resolve_reservations_state_path(self: Any) -> None:
"""通过 path_config 解析预约状态文件路径,失败时退化到相对兜底。"""
try:
from douyin.core import path_config as _pc
self._reservations_state_path = _pc.get_reservations_path()
except Exception:
# 兜底:path_config 不可用时退到相对路径,与 douyin/core/state/ 一致
self._reservations_state_path = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "state", "reservations.json")
)
# 运行时直播间标题/位置映射表(清空后存)
self._room_pos_to_title_map = {}
def _cleanup_old_room_pos_map_files(self: Any) -> None:
"""每次启动时删除上次运行的导出文件,避免 GUI 显示过期内容。"""
try:
state_dir = os.path.dirname(self._reservations_state_path)
for filename in ("room_pos_map.json", "room_pos_map.csv", "room_pos_map.md"):
try:
p = os.path.join(state_dir, filename)
if os.path.exists(p):
os.remove(p)
except Exception:
pass
except Exception:
pass
File diff suppressed because it is too large. Load diff
+1 -104
View File
@@ -3,7 +3,6 @@
"""
import os
from typing import Optional
import json
# 项目根目录(所有路径的基准)
# __file__ 位于 <project_root>/douyin/core/path_config.py,
@@ -12,113 +11,12 @@ PROJECT_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
# 运行时路径与设备侧默认路径(支持环境变量覆盖,便于迁移)
DEFAULT_ANDROID_SCREENSHOT_PATH = "/sdcard/DCIM/screenshot.png"
DEFAULT_ANDROID_SCREENSHOT_ALT_PATH = "/sdcard/DCIM/screenshot1.png"
DEFAULT_ANDROID_WINDOW_DUMP_PATH = "/sdcard/window_dump.xml"
DEFAULT_DOUYIN_PACKAGES = (
"com.ss.android.ugc.aweme",
"com.ss.android.ugc.aweme.lite",
"com.zhiliaoapp.musically",
)
DEFAULT_ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
DEFAULT_WEB_GUI_HOST = "127.0.0.1"
DEFAULT_WEB_GUI_PORT = 8000
def get_project_root() -> str:
"""返回项目根目录(绝对路径)"""
return PROJECT_ROOT
def get_venv_python_path() -> str:
"""返回项目虚拟环境 Python 路径(Windows)。"""
return os.path.join(PROJECT_ROOT, ".venv", "Scripts", "python.exe")
def get_android_screenshot_path() -> str:
"""返回设备侧截图路径(可通过环境变量覆盖)。"""
return (
os.environ.get("ANDROID_SCREENSHOT_PATH", "").strip()
or DEFAULT_ANDROID_SCREENSHOT_PATH
)
def get_android_screenshot_alt_path() -> str:
"""返回设备侧备用截图路径(可通过环境变量覆盖)。"""
return (
os.environ.get("ANDROID_SCREENSHOT_ALT_PATH", "").strip()
or DEFAULT_ANDROID_SCREENSHOT_ALT_PATH
)
def get_android_window_dump_path() -> str:
"""返回设备侧 UI dump 路径(可通过环境变量覆盖)。"""
return (
os.environ.get("ANDROID_WINDOW_DUMP_PATH", "").strip()
or DEFAULT_ANDROID_WINDOW_DUMP_PATH
)
def get_douyin_packages() -> tuple[str, ...]:
"""返回抖音候选包名列表(支持环境变量覆盖,逗号分隔)。"""
raw = (os.environ.get("DOUYIN_PACKAGES", "") or "").strip()
if not raw:
return DEFAULT_DOUYIN_PACKAGES
items = tuple(x.strip() for x in raw.split(",") if x.strip())
return items or DEFAULT_DOUYIN_PACKAGES
def get_adb_keyboard_ime() -> str:
"""返回 ADBKeyboard IME(支持环境变量覆盖)。"""
return (os.environ.get("ADB_KEYBOARD_IME", "") or "").strip() or DEFAULT_ADB_KEYBOARD_IME
def _read_runtime_config() -> dict:
"""读取 config/config.json,失败时返回空字典。"""
try:
cfg_path = get_config_path()
if not os.path.exists(cfg_path):
return {}
with open(cfg_path, "r", encoding="utf-8") as f:
obj = json.load(f)
return obj if isinstance(obj, dict) else {}
except Exception:
return {}
def get_web_gui_host() -> str:
"""返回 Web GUI 监听 host(环境变量优先,其次 config.json,最后默认值)。"""
host = (os.environ.get("WEB_GUI_HOST") or os.environ.get("HOST") or "").strip()
if host:
return host
cfg = _read_runtime_config()
cfg_host = str(cfg.get("web_gui_host", "") or "").strip()
return cfg_host or DEFAULT_WEB_GUI_HOST
def get_web_gui_port() -> int:
"""返回 Web GUI 监听端口(环境变量优先,其次 config.json,最后默认值)。"""
env_raw = (os.environ.get("PORT") or os.environ.get("WEB_GUI_PORT") or "").strip()
if env_raw:
try:
port = int(env_raw)
if 1 <= port <= 65535:
return port
except Exception:
pass
cfg = _read_runtime_config()
cfg_raw = cfg.get("web_gui_port", DEFAULT_WEB_GUI_PORT)
try:
port = int(cfg_raw)
if 1 <= port <= 65535:
return port
except Exception:
pass
return DEFAULT_WEB_GUI_PORT
def get_config_path() -> str:
"""返回 config.json 的路径"""
return os.path.join(PROJECT_ROOT, "config", "config.json")
@@ -286,8 +184,7 @@ def find_executable(cmd: str) -> Optional[str]:
return first
else:
# 类 Unix:尝试 command -v 再 which
import shlex
proc = subprocess.run(["/bin/sh", "-c", f"command -v {shlex.quote(cmd)} || which {shlex.quote(cmd)}"], capture_output=True, text=True)
proc = subprocess.run(["/bin/sh", "-c", f"command -v {cmd} || which {cmd}"], capture_output=True, text=True)
if proc.returncode == 0 and proc.stdout:
first = proc.stdout.splitlines()[0].strip()
if first:
-113
View File
@@ -1,113 +0,0 @@
"""桌面自救共享逻辑
把 fudai_modules.run_once_basic_helpers 和 douyin.other.douyin_yanghao
中重复的"前台不在抖音 → 包名启动 → 失败兜底点击坐标"逻辑抽到这里。
"""
from __future__ import annotations
import time
from typing import Any, Callable, Optional
def is_douyin_foreground(top_pkg: str) -> bool:
"""判断给定的前台包名是否属于抖音相关包。"""
return bool(top_pkg) and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
def fallback_click_recovery(
analyser: Any,
log: Optional[Callable[[str], None]] = None,
) -> None:
"""旧的点击坐标自救:桌面图标 → 直播按钮 → 进入直播间×2。
保留作为 launch_package 失败时的兜底。所有坐标读 analyser 上的属性,
取不到时使用默认值(适配 1080x2400 的位置)。
"""
op = analyser.operation
device_id = analyser.device_id
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
try:
op.click(device_id, desktop_x, desktop_y)
except Exception:
# 退化为默认硬编码位置
try:
op.click(device_id, 153, 260)
except Exception:
pass
op.delay(2)
fallback_x = int(getattr(analyser, "yanghao_fallback_live_x", 540) or 540)
fallback_y = int(getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000)
try:
if log:
log(f"点击直播按钮 x={fallback_x} y={fallback_y}")
op.click(device_id, fallback_x, fallback_y)
op.delay(1.5)
except Exception:
pass
enter_x = int(getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540)
enter_y = int(getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200)
try:
if log:
log(f"点击进入直播间 x={enter_x} y={enter_y} 次数=2")
op.click(device_id, enter_x, enter_y)
op.delay(0.6)
op.click(device_id, enter_x, enter_y)
op.delay(2.0)
except Exception:
pass
def recover_to_douyin(
analyser: Any,
log: Optional[Callable[[str], None]] = None,
) -> bool:
"""统一的桌面自救入口。
流程:
1. 优先 op.launch_package(device_id, ""),按抖音常用包名顺序尝试
2. 包名启动失败或抛异常时,回退到点击坐标自救(fallback_click_recovery)
参数:
analyser: 提供 .operation / .device_id / 自救坐标属性的对象
log: 可选的日志回调(接受单字符串)
返回:
True 表示已尝试某种自救(不保证一定成功,但已执行动作);
False 仅在调用环境本身出现严重异常时返回。
"""
try:
op = analyser.operation
device_id = analyser.device_id
except Exception:
return False
launched_ok = False
used_pkg = ""
try:
launched_ok, used_pkg = op.launch_package(device_id, "")
except Exception as exc:
if log:
log(f"包名启动调用异常 {exc},回退点击坐标")
if launched_ok:
if log:
log(f"包名启动抖音成功 pkg={used_pkg}")
try:
op.delay(2.5)
except Exception:
time.sleep(2.5)
return True
# 兜底:保留旧的点击坐标自救
if log:
log("包名启动失败,回退点击桌面图标 + 备用坐标")
fallback_click_recovery(analyser, log=log)
return True
File diff suppressed because it is too large. Load diff
@@ -123,16 +123,16 @@ def check_countdown(last_time=""):
else:
total2 = None
if total1 is not None and total1 <= 3600:
if total1 is not None and total1 <= 900:
return total1
if total2 is not None and total2 <= 3600:
if total2 is not None and total2 <= 900:
return total2
# 若一个明显异常而另一个更合理(<=3600),交换
# 若一个明显异常而另一个更合理(<=900),交换
if total1 is not None and total2 is not None:
if total1 > 3600 and total2 <= 3600:
if total1 > 900 and total2 <= 900:
return total2
if total2 > 3600 and total1 <= 3600:
if total2 > 900 and total1 <= 900:
return total1
# 兜底:谁能解析就用谁;都不行则做进位
@@ -182,9 +182,9 @@ def check_countdown(last_time=""):
_uo_log("时间格式异常")
return False
_uo_log("剩余总秒数:", total_seconds)
# 超过 60 分钟视为 OCR 误识别,按 59 分 50 秒处理
if total_seconds > 3600:
total_seconds = 3590
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
if total_seconds > 900:
total_seconds = 890
now = datetime.now()
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
@@ -57,18 +57,10 @@ def select_device():
print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。")
return False
num = input()
try:
num = int(num)
except ValueError:
print("请输入有效数字:")
return False
num = int(num)
while not num in dictdevice.keys():
print("输入不正确,请重新输入:")
num = input()
try:
num = int(num)
except ValueError:
print("请输入有效数字:")
return False
num = int(num)
return dictdevice[num]
@@ -1,276 +0,0 @@
"""douyin/core/underlying_operations_pkg/image_ops - cut_pic 图片裁剪管道
把 underlying_operations.cut_pic 整段抽出来。流程:
- 默认分支(target=""):从项目根 pic/screenshot.png 读图,裁出 cut.png 或 ocr/<name>.png
- 命名分支(target="xxx"):从 pic/<target>/screenshot.png 读图,裁出 pic/<target>/<name>.png
- 重试 3 次(截图缺失/文件太小/PIL 损坏)
- 写入坐标缓存供 analyse_pic_word 调试图像用
- 可选保存 cut_pic 调试图(SAVE_CUT_PIC_DEBUG_IMAGES=1)
入口:cut_pic(self, left_up, right_down, target, name) -> bool
self 必须提供:_find_pic_path / _ocr_coords_lock / _ocr_coords_cache
"""
from __future__ import annotations
import logging
import os
import time as time_module
from typing import Any
from PIL import Image
def _ensure_parent_dir(path: str) -> None:
"""确保路径的父目录存在。"""
try:
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
except Exception:
pass
def _validate_coords(
left_up: tuple, right_down: tuple, image_size: tuple
) -> bool:
"""检查裁剪坐标在图片范围内且非空。"""
left, top = left_up
right, bottom = right_down
width, height = image_size
return not (
left < 0 or top < 0
or right > width or bottom > height
or left >= right or top >= bottom
)
def _save_cut_debug_images(self: Any, cropped_img, pic, name: str, source_label: str, left: int, top: int, right: int, bottom: int) -> None:
"""根据环境变量决定是否保存 cut_pic 调试图。"""
try:
save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
if not save_debug:
try:
save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
except Exception:
pass
if not save_debug:
return
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(完整截图+区域标注)
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": source_label,
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def cut_pic(
self: Any,
left_up=(0, 63),
right_down=(1080, 1620),
target: str = "",
name: str = "",
) -> bool:
"""裁剪图片,获取需要的区域小图片方便识别。"""
from douyin.core.underlying_operations import _uo_log
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
if target == "" or target is False:
from douyin.core import path_config
path = path_config.get_pic_dir()
pic1_path = path_config.get_screenshot_path()
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path + "/cut.png"
else:
cut_pic_path = self._find_pic_path(name, for_reading=False)
if not _validate_coords(left_up, right_down, pic.size):
raise ValueError(
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
)
left, top = left_up
right, bottom = right_down
cropped_img = pic.crop((left, top, right, bottom))
assert cut_pic_path is not None
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
# 存储坐标信息供 analyse_pic_word 使用
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
try:
_save_cut_debug_images(
self, cropped_img, pic, name,
"screenshot.png", left, top, right, bottom,
)
finally:
pic.close()
return True
else:
from douyin.core import path_config
path_target = os.path.join(path_config.get_pic_dir(), target)
pic1_path = os.path.join(path_target, "screenshot.png")
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path_target + "/cut.png"
else:
cut_pic_path = path_target + "/" + name + ".png"
try:
if not _validate_coords(left_up, right_down, pic.size):
error_msg = (
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, "
f"image_size={pic.size}"
)
if attempt == max_retries - 1:
_uo_log(f"[错误] {error_msg}")
return False
continue
left, top = left_up
right, bottom = right_down
assert cut_pic_path is not None
cropped_img = pic.crop((left, top, right, bottom))
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 命名分支总是保存 cut_pic 调试图(与原版行为一致 — 没有开关检查)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": target + "/screenshot.png",
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
return True
finally:
pic.close()
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
if attempt == max_retries - 1:
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
_uo_log(error_msg)
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
return False
continue
return False
@@ -1,380 +0,0 @@
"""douyin/core/underlying_operations_pkg/ocr_pipeline - analyse_pic_word OCR 管道
把 underlying_operations.analyse_pic_word 整段抽出来。流程:
1. 路径解析 + 缓存查询(基于图片字节哈希)
2. 加载 + 验证图片完整性
3. change_color 预处理(0=保留彩色,1/2=二值化)
4. 调试图像保存(preprocessed 步骤,仅当 SAVE_OCR_DEBUG_IMAGES=1)
5. 调用 OCR(EasyOCR / PaddleOCR predict/ocr)
6. 提取文本 + 置信度
7. 写缓存
8. 调试图像保存(after_ocr 步骤)
9. 成功识别保存到 ocr/<category>/<picname>_success.png
入口:analyse_pic_word(self, picname, change_color, pic_path, return_confidence)
self 必须提供:_find_pic_path / extract_ocr_content / ocr / ocr_type /
_ocr_coords_lock / _ocr_coords_cache / save_ocr_debug_images
"""
from __future__ import annotations
import logging
import os
from typing import Any, Optional
from PIL import Image, UnidentifiedImageError
import numpy as np
def analyse_pic_word(
self: Any,
picname: str,
change_color: int = 0,
pic_path: Optional[str] = None,
return_confidence: bool = False,
):
"""对指定图片运行 OCR 并返回拼接后的文本结果。
Args:
self: underlying_operations 实例
picname: 图片名(如"福袋内容")
change_color: 0=保留彩色,1/2=二值化
pic_path: 可选;未提供时通过 self._find_pic_path 查找
return_confidence: True 时返回 (text, confidence_info);否则只返回 text
Returns:
return_confidence=False: text(str)
return_confidence=True: (text, confidence_info)
"""
from douyin.core.underlying_operations import _uo_log
if not pic_path:
try:
pic_path = self._find_pic_path(picname)
except Exception:
pic_path = None
if not pic_path or not os.path.exists(pic_path):
return ("", None) if return_confidence else ""
# ===== 缓存查询:基于图片字节哈希 =====
cache_key = None
try:
from operations.ocr_operations import (
_img_fingerprint, cache_get, cache_put,
)
with open(pic_path, "rb") as _f:
_bytes = _f.read()
cache_key = _img_fingerprint(_bytes, mode=int(change_color or 0))
cached = cache_get(cache_key)
if cached is not None:
return cached if return_confidence else cached[0]
except Exception:
cache_key = None
# 加载图片
_pic_raw = None
img = None
try:
_pic_raw = Image.open(pic_path)
_pic_raw.load()
img = _pic_raw.convert("RGB")
_pic_raw.close()
_pic_raw = None
except (IOError, OSError, UnidentifiedImageError):
if _pic_raw is not None:
_pic_raw.close()
return ("", None) if return_confidence else ""
if img is None:
return ("", None) if return_confidence else ""
# 预处理:实测 PaddleOCR v4-mobile 内部已自带 resize/normalize,
# 外层"放大+锐化+对比度增强"反而会引入伪影,让识别变差。
# 因此默认走原图。仅在 change_color=1/2 业务显式要求二值化时才做。
if change_color in (1, 2):
old = img
img = img.convert("L")
old.close()
thresh = 128 if change_color == 1 else 180
img = img.point(lambda x, t=thresh: 0 if int(x) < t else 255)
else:
img = img.convert("RGB")
w, h = img.size
img1 = img # 不再做放大/锐化/对比度
# 调试图像保存(preprocessed 步骤)
_save_debug_preprocessed(self, img1, picname, pic_path, change_color, w, h)
img_np = np.array(img1)
ocr_confidence_info = None
try:
ocr_obj = getattr(self, "ocr", None)
ocr_type = getattr(self, "ocr_type", None)
except Exception:
ocr_obj = None
ocr_type = None
if ocr_obj is None:
try:
logging.warning("OCR 未初始化,跳过识别:picname=%s", picname)
except Exception:
pass
return ("", None) if return_confidence else ""
# 执行 OCR
try:
if ocr_type == "easyocr":
result = ocr_obj.readtext(img_np)
extract_result = self.extract_ocr_content(result, return_confidence=True)
if isinstance(extract_result, tuple):
text, ocr_confidence_info = extract_result
else:
text = extract_result
else:
# PaddleOCR 3.x:predict() 是新推荐 API;ocr() 仍兼容
_predict = getattr(ocr_obj, "predict", None) or ocr_obj.ocr
result = _predict(img_np)
if result == [None]:
if cache_key:
try:
cache_put(cache_key, ("", None))
except Exception:
pass
return ("", None) if return_confidence else ""
extract_result = self.extract_ocr_content(result, return_confidence=True)
if isinstance(extract_result, tuple):
text, ocr_confidence_info = extract_result
else:
text = extract_result
except Exception as e:
try:
logging.warning("OCR 调用失败,返回空结果:%s", e)
except Exception:
pass
return ("", None) if return_confidence else ""
# 写缓存
if cache_key:
try:
cache_put(cache_key, (text, ocr_confidence_info))
except Exception:
pass
# 调试日志:福袋内容 / 福袋倒计时 OCR 失败时打印 result 结构
if picname in ("福袋内容", "福袋倒计时") and not text:
try:
if isinstance(result, list) and result and isinstance(result[0], dict):
_uo_log(f"OCR调试({picname}): result[0] keys={list(result[0].keys())}")
else:
_uo_log(f"OCR调试({picname}): result type={type(result)}")
except Exception:
pass
# 调试图像保存(after_ocr 步骤)+ 置信度日志
_save_debug_after_ocr(
self, img1, picname, change_color, text,
ocr_confidence_info,
)
# 成功识别 → 保存到 ocr/<category>/<picname>_success.png
if text and text.strip() and picname:
_save_success_pic(img, img1, picname, text)
if return_confidence:
return text, ocr_confidence_info
else:
return text
def _save_debug_preprocessed(
self: Any, img1, picname: str, pic_path: str,
change_color: int, w: int, h: int,
) -> None:
"""保存预处理后的调试图像(OCR 输入),仅当 SAVE_OCR_DEBUG_IMAGES=1 时执行。"""
try:
save_debug = os.environ.get("SAVE_OCR_DEBUG_IMAGES", "0") == "1"
if not save_debug:
try:
save_debug = bool(getattr(self, "save_ocr_debug_images", False))
except Exception:
pass
if not save_debug:
return
from douyin.handlers import douyin_screenshot_manager
from douyin.core import path_config
ocr_coords = None
try:
with self._ocr_coords_lock:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
full_screenshot = None
try:
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
_raw = Image.open(screenshot_path)
try:
_raw.load()
full_screenshot = _raw.convert("RGB")
finally:
_raw.close()
except Exception:
pass
debug_image = full_screenshot if full_screenshot is not None else img1
debug_path = douyin_screenshot_manager.save_debug_image(
debug_image,
operation_type="ocr",
picname=picname,
step="preprocessed",
coords=ocr_coords,
extra_info={
"mode": change_color,
"size": f"{w}x{h}",
"source": pic_path if pic_path else picname,
"has_full_screenshot": full_screenshot is not None,
"has_coords": ocr_coords is not None,
},
)
if debug_path:
try:
logging.info("[调试图像] OCR预处理保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def _save_debug_after_ocr(
self: Any, img1, picname: str, change_color: int,
text: Optional[str], ocr_confidence_info: Optional[dict],
) -> None:
"""保存 OCR 完成后的调试图像(含识别文本预览 + 置信度)。"""
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(img1, operation_type="ocr")
ocr_result_preview = (text or "").strip()[:50] if text else ""
extra_info_dict = {
"mode": change_color,
"text_len": len(text or ""),
"text_preview": ocr_result_preview,
"used_img2": False, # 二次 OCR 已禁用
}
if ocr_confidence_info:
extra_info_dict["avg_confidence"] = round(
ocr_confidence_info.get("avg_confidence", 0.0), 4
)
extra_info_dict["min_confidence"] = round(
ocr_confidence_info.get("min_confidence", 0.0), 4
)
extra_info_dict["max_confidence"] = round(
ocr_confidence_info.get("max_confidence", 0.0), 4
)
extra_info_dict["confidence_items"] = ocr_confidence_info.get(
"item_count", 0
)
ocr_coords = None
try:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
full_screenshot = None
try:
from douyin.core import path_config
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
_raw = Image.open(screenshot_path)
try:
_raw.load()
full_screenshot = _raw.convert("RGB")
finally:
_raw.close()
except Exception:
pass
debug_image = full_screenshot if full_screenshot is not None else img1
extra_info_dict["has_full_screenshot"] = full_screenshot is not None
extra_info_dict["has_coords"] = ocr_coords is not None
debug_path = douyin_screenshot_manager.save_debug_image(
debug_image,
operation_type="ocr",
picname=picname,
step="after_ocr",
coords=ocr_coords,
extra_info=extra_info_dict,
)
# 记录 OCR 置信度到日志
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
try:
logging.info(
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
picname,
ocr_confidence_info.get("avg_confidence", 0.0),
ocr_confidence_info.get("min_confidence", 0.0),
ocr_confidence_info.get("max_confidence", 0.0),
int(ocr_confidence_info.get("item_count", 0) or 0),
)
except Exception:
pass
if debug_path:
try:
logging.info(
"[调试图像] OCR结果保存: %s, 文本: %s",
debug_path,
ocr_result_preview,
)
except Exception:
pass
except Exception:
pass
def _save_success_pic(img, img1, picname: str, text: str) -> None:
"""成功识别后保存到 ocr/<category>/<picname>_success.png。"""
try:
try:
from douyin.handlers import douyin_screenshot_manager
category = douyin_screenshot_manager.get_category_for_picname(picname)
except Exception:
category = "others"
from douyin.core import path_config
pic_base = path_config.get_pic_dir()
category_dir = os.path.join(pic_base, "ocr", category)
os.makedirs(category_dir, exist_ok=True)
success_path = os.path.join(category_dir, f"{picname}_success.png")
try:
img_to_save = img1
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_last_success(
img_to_save, operation_type="ocr"
)
except Exception:
pass
img_to_save.save(success_path)
except Exception:
try:
if img is not None:
img.save(success_path)
except Exception:
pass
except Exception:
pass
@@ -1,499 +0,0 @@
"""underlying_operations._get_screenshot_direct 的实现。
从 underlying_operations.py 抽出,原方法保留为 thin shim 调用 capture_screenshot_direct。
依赖:
- self._adb_path() —— 取 adb 可执行文件路径
- self.get_screenshot() —— 在最深兜底分支递归调用一次(注意保持兼容)
- io_utils._safe_replace_file
- io_utils._mirror_screenshot_to_external
"""
from __future__ import annotations
import logging
import os
import subprocess
import threading
import time as time_module
from datetime import datetime
from typing import TYPE_CHECKING
from douyin.core.io_utils import (
_mirror_screenshot_to_external,
_safe_replace_file,
)
if TYPE_CHECKING:
from douyin.core.underlying_operations import underlying_operations
def _uo_log(msg: str) -> None:
"""与 underlying_operations._uo_log 一致:默认 INFO 级别。"""
try:
logging.info(msg)
except Exception:
pass
def capture_screenshot_direct(
self: "underlying_operations", device_id, path: str = "pic"
) -> bool:
"""直接截图(不使用服务模式)。从 underlying_operations._get_screenshot_direct 抽出。
流程:
1. 准备输出目录 + 文件名
2. 优先 exec-out 路径(最多 2 次重试 + watchdog)
3. 失败 → 回退 shell screencap + adb pull
4. 再失败 → 兜底 mv + 递归调用 get_screenshot
"""
overall_start = time_module.time()
cleanup_dur = 0.0
adb_subprocess_dur = 0.0
validate_tmp_dur = 0.0
replace_dur = 0.0
mirror_dur = 0.0
validate_out_dur = 0.0
if path == "pic":
try:
from douyin.core import path_config
out_dir = path_config.get_pic_dir()
except Exception:
from douyin.core import path_config
out_dir = path_config.get_pic_dir()
else:
out_dir = os.path.join(os.path.dirname(__file__), "..", "target_pic")
if not os.path.exists(out_dir):
os.makedirs(out_dir)
out_file = os.path.join(out_dir, "screenshot.png")
tmp_file = out_file + ".tmp"
timetag = datetime.now().strftime("%H:%M:%S")
adb = self._adb_path()
skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1"
def _valid_png(path0: str) -> bool:
if skip_verify:
try:
if not os.path.exists(path0):
return False
sz = os.path.getsize(path0)
return sz >= 1024
except Exception:
return False
verify_start = time_module.time()
try:
if not os.path.exists(path0):
return False
sz = os.path.getsize(path0)
if sz < 1024:
return False
header_check_start = time_module.time()
try:
with open(path0, "rb") as _f:
header = _f.read(4)
if header != b"\x89PNG":
return False
try:
_f.seek(-256, 2)
except Exception:
_f.seek(0)
tail = _f.read(256)
if b"IEND" not in tail:
return False
except Exception:
return False
header_check_dur = (time_module.time() - header_check_start) * 1000.0
if header_check_dur > 10.0:
logging.debug(
"[截图] PNG头尾校验耗时(ms)=%.1f path=%s",
header_check_dur,
path0,
)
verify_total_dur = (time_module.time() - verify_start) * 1000.0
if verify_total_dur > 100.0:
logging.info(
"[截图] _valid_png总耗时(ms)=%.1f path=%s",
verify_total_dur,
path0,
)
return True
except Exception:
return False
# 优先走 exec-out
try:
execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10"))
except ValueError:
execout_timeout_sec = 10.0
try:
execout_warn_after_sec = float(
os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3")
)
except ValueError:
execout_warn_after_sec = 3.0
try:
execout_heartbeat_interval_sec = float(
os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5")
)
except ValueError:
execout_heartbeat_interval_sec = 5.0
try:
execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3"))
except ValueError:
execout_heartbeat_max = 3
for attempt in range(2):
try:
cleanup_start = time_module.time()
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
cleanup_dur = (time_module.time() - cleanup_start) * 1000.0
if cleanup_dur > 10.0:
logging.debug("[截图] 清理临时文件耗时(ms)=%.1f", cleanup_dur)
adb_start = time_module.time()
try:
process = subprocess.Popen(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
bufsize=0,
)
done_event = None
watchdog_thread = None
try:
done_event = threading.Event()
def _watchdog() -> None:
try:
if execout_warn_after_sec > 0:
if done_event.wait(timeout=execout_warn_after_sec):
return
start_wait = time_module.time()
for i in range(max(0, execout_heartbeat_max)):
if done_event.is_set():
return
waited = (time_module.time() - start_wait) * 1000.0
logging.warning(
"[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s",
waited,
device_id,
attempt + 1,
)
if done_event.wait(
timeout=max(0.5, execout_heartbeat_interval_sec)
):
return
except Exception:
return
watchdog_thread = threading.Thread(
target=_watchdog, name="adb-execout-watchdog", daemon=True
)
watchdog_thread.start()
except Exception:
done_event = None
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
if done_event is not None:
done_event.set()
if process.returncode != 0:
raise subprocess.CalledProcessError(
process.returncode,
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
)
with open(tmp_file, "wb", buffering=262144) as f:
f.write(stdout_data)
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
except subprocess.TimeoutExpired:
process.kill()
try:
process.communicate(timeout=1)
except Exception:
pass
try:
if done_event is not None:
done_event.set()
except Exception:
pass
raise
validate_tmp_start = time_module.time()
is_valid = _valid_png(tmp_file)
validate_tmp_dur = (time_module.time() - validate_tmp_start) * 1000.0
if validate_tmp_dur > 50.0:
logging.info(
"[截图] 临时文件验证耗时(ms)=%.1f result=%s",
validate_tmp_dur,
is_valid,
)
if is_valid:
replace_start = time_module.time()
replace_success = _safe_replace_file(tmp_file, out_file)
replace_dur = (time_module.time() - replace_start) * 1000.0
if replace_dur > 50.0:
logging.info(
"[截图] 文件替换耗时(ms)=%.1f result=%s",
replace_dur,
replace_success,
)
if replace_success:
mirror_start = time_module.time()
_mirror_screenshot_to_external(out_file)
mirror_dur = (time_module.time() - mirror_start) * 1000.0
if mirror_dur > 50.0:
logging.info(
"[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur
)
validate_out_start = time_module.time()
try:
if os.path.exists(out_file):
file_size = os.path.getsize(out_file)
if file_size >= 1024:
try:
with open(out_file, "rb") as f:
header = f.read(4)
if header == b"\x89PNG":
validate_out_dur = (
time_module.time()
- validate_out_start
) * 1000.0
if validate_out_dur > 50.0:
logging.info(
"[截图] 目标文件快速验证耗时(ms)=%.1f",
validate_out_dur,
)
overall_dur = (
time_module.time() - overall_start
) * 1000.0
logging.info(
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (exec-out成功) | 汇总: cleanup=%.1f adb_execout=%.1f validate_tmp=%.1f replace=%.1f mirror=%.1f validate_out=%.1f",
overall_dur,
cleanup_dur,
adb_subprocess_dur,
validate_tmp_dur,
replace_dur,
mirror_dur,
validate_out_dur,
)
return True
except Exception:
pass
try:
st = os.stat(out_file)
_uo_log(
f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}"
)
except Exception:
pass
except Exception:
pass
else:
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
_uo_log(
f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}"
)
except Exception:
pass
else:
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
_uo_log(
f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}"
)
except Exception:
pass
except subprocess.TimeoutExpired:
_uo_log("[截图] exec-out 超时,尝试重试或回退方案")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
except Exception as e:
_uo_log(f"[截图] exec-out 异常:{e}")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
# 回退方案:老式 shell screencap + pull
fallback_start = time_module.time()
try:
shell_screencap_start = time_module.time()
subprocess.run(
[
adb,
"-s",
device_id,
"shell",
"screencap",
"-p",
"/sdcard/DCIM/screenshot.png",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
timeout=10,
)
shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0
logging.info(
"[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s",
shell_screencap_dur,
device_id,
)
pull_start = time_module.time()
subprocess.run(
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
timeout=10,
)
pull_dur = (time_module.time() - pull_start) * 1000.0
logging.info(
"[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id
)
fallback_validate_start = time_module.time()
if _valid_png(tmp_file):
fallback_validate_dur = (
time_module.time() - fallback_validate_start
) * 1000.0
if fallback_validate_dur > 50.0:
logging.info(
"[截图] 回退方案-临时文件验证耗时(ms)=%.1f",
fallback_validate_dur,
)
fallback_replace_start = time_module.time()
if _safe_replace_file(tmp_file, out_file):
fallback_replace_dur = (
time_module.time() - fallback_replace_start
) * 1000.0
if fallback_replace_dur > 50.0:
logging.info(
"[截图] 回退方案-文件替换耗时(ms)=%.1f",
fallback_replace_dur,
)
fallback_mirror_start = time_module.time()
_mirror_screenshot_to_external(out_file)
fallback_mirror_dur = (
time_module.time() - fallback_mirror_start
) * 1000.0
if fallback_mirror_dur > 50.0:
logging.info(
"[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur
)
try:
if _valid_png(out_file):
overall_dur = (time_module.time() - overall_start) * 1000.0
fallback_total_dur = (
time_module.time() - fallback_start
) * 1000.0
logging.info(
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (回退方案成功, 回退部分耗时=%.1fms)",
overall_dur,
fallback_total_dur,
)
return True
except Exception:
pass
else:
# 替换失败 → 直接复制 / 兜底
try:
if os.path.exists(tmp_file):
try:
with open(tmp_file, "rb") as src, open(
out_file, "wb"
) as dst:
dst.write(src.read())
_mirror_screenshot_to_external(out_file)
try:
if _valid_png(out_file):
_uo_log(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)"
)
return True
except Exception:
pass
except (OSError, PermissionError) as e:
replace_success = _safe_replace_file(tmp_file, out_file)
if replace_success:
_mirror_screenshot_to_external(out_file)
try:
if _valid_png(out_file):
_uo_log(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)"
)
return True
except Exception:
pass
else:
_uo_log(
f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}"
)
return True
except Exception:
_uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
return True
except Exception:
# 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png
try:
subprocess.run(
[
adb,
"-s",
device_id,
"shell",
"screencap",
"-p",
"/sdcard/DCIM/screenshot1.png",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
subprocess.run(
[
adb,
"-s",
device_id,
"shell",
"mv",
"/sdcard/DCIM/screenshot1.png",
"/sdcard/DCIM/screenshot.png",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
return self.get_screenshot(device_id, path)
except Exception:
return False
+2 -5
View File
@@ -280,11 +280,8 @@ def check_in_fudai_detail(analyser: Any) -> bool:
return False
pic = Image.open(pic_path)
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
pic.load()
pic_rgb = pic.convert("RGB")
# 获取分辨率比例和Y偏移
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
+22 -18
View File
@@ -14,6 +14,11 @@ from typing import Any
from PIL import Image
from ._common import _ensure_detection_cache
from .template_match_helpers import (
numpy_pixel_scan,
per_pixel_scan_fallback,
template_match_fallback,
)
def check_have_fudai_with_ready_screenshot(
@@ -197,7 +202,6 @@ def check_have_fudai_with_ready_screenshot(
continue
pic_new = pic.convert("RGBA")
pic.close()
width, height = pic_new.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
@@ -269,30 +273,31 @@ def check_have_fudai_with_ready_screenshot(
except Exception:
pass
# numpy 加速扫描(性能优化,失败回退到逐像素扫描)
from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy
detected, _detected_x = scan_with_numpy(
analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
np_detected, np_x = numpy_pixel_scan(
analyser, pic_new, rx, ry, width, height, y_pianyi_val, optimal_x_scaled,
)
if detected and _detected_x is not None:
detected_x = _detected_x
if np_detected:
detected = True
detected_x = np_x
# numpy 未命中/不可用时回退到逐像素扫描
# numpy 未命中/不可用时回退到原始逐像素检查
if not detected:
from douyin.detection.detection_pkg.finder_pixel_scan import scan_pixel_by_pixel
detected, _detected_x = scan_pixel_by_pixel(
analyser, pic_new, rx, ry, y_pianyi_val
pp_detected, pp_x = per_pixel_scan_fallback(
analyser, pic_new, rx, ry, y_pianyi_val,
)
if detected and _detected_x is not None:
detected_x = _detected_x
if pp_detected:
detected = True
detected_x = pp_x
# 像素检测未命中时,使用模板匹配作为兜底
if not detected or detected_x is None:
from douyin.detection.detection_pkg.finder_template_match import match_template
_det, _x = match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop)
if _det and _x is not None:
tm_detected, tm_x = template_match_fallback(
analyser, pic_new, rx, ry, width, height, y_pianyi_val, loop,
)
if tm_detected:
detected = True
detected_x = _x
detected_x = tm_x
if detected and detected_x is not None:
# 重置连续失败计数
@@ -421,4 +426,3 @@ def check_have_fudai_with_ready_screenshot(
except Exception:
pass
return False
@@ -1,169 +0,0 @@
"""douyin/detection/detection_pkg/finder_numpy_scan - numpy 加速福袋图标像素扫描
把 check_have_fudai_with_ready_screenshot 中"numpy 加速扫描水平带"段抽出来。
逻辑:在 ROI 内根据预设颜色范围生成像素掩码,按列聚合,从最优起始列向两侧
交替搜索第一个匹配列,命中即返回检测到的 x 坐标(1080 基准)。
入口:scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
返回:(detected: bool, detected_x: Optional[int])
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
def scan_with_numpy(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
optimal_x_scaled: int,
) -> Tuple[bool, Optional[int]]:
"""numpy 加速扫描福袋图标的水平像素带。
Args:
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
optimal_x_scaled: 最优起始列(设备分辨率坐标)
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标;
失败/异常返回 (False, None),由 caller 切换到逐像素扫描。
"""
try:
import numpy as _np
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
width, height = pic_new.size
try:
# 计算检测区域,考虑分辨率缩放和偏移
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
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] # type: ignore[index]
g = arr[:, :, 1] # type: ignore[index]
b = arr[:, :, 2] # type: ignore[index]
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
# 原来的范围:R[193-203], G[176-193], B[237-247]
# 优化后:适度放宽范围,但保持中心值权重
mask_center = (
(r >= 190) & (r <= 206)
& (g >= 173) & (g <= 196)
& (b >= 234) & (b <= 250)
) # type: ignore[operator]
mask = mask_center
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
cols = _np.sum(mask, axis=0)
# 至少需要 2 个像素匹配(避免单个噪点误判)
valid_cols = cols >= 2
if not valid_cols.any():
return False, None
# 从最优位置开始向左右两侧交替搜索
roi_width = x2 - x1
optimal_col = optimal_x_scaled - x1
optimal_col = max(0, min(optimal_col, roi_width - 1))
found_col: Optional[int] = 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
# 1080 基准坐标
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
@@ -1,205 +0,0 @@
"""douyin/detection/detection_pkg/finder_pixel_scan - 逐像素福袋图标扫描兜底
当 numpy 加速扫描没找到时,回退到逐像素遍历。逻辑与 numpy 版相似但
使用 PIL.Image.load() 提供的像素访问,性能较慢但兼容性最好。
入口:scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val)
返回:(detected: bool, detected_x: Optional[int])
颜色范围与 finder_numpy_scan 一致:r ∈ [190, 206], g ∈ [173, 196], b ∈ [234, 250]。
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
# 福袋图标主色范围(与 finder_numpy_scan 共享)
_R_MIN, _R_MAX = 190, 206
_G_MIN, _G_MAX = 173, 196
_B_MIN, _B_MAX = 234, 250
def _is_target_pixel(px) -> bool:
"""检查像素是否落在目标颜色范围内。"""
if not (isinstance(px, tuple) and len(px) >= 3):
return False
r, g, b = px[0], px[1], px[2]
return _R_MIN <= r <= _R_MAX and _G_MIN <= g <= _G_MAX and _B_MIN <= b <= _B_MAX
def _safe_check_pixel(pix, x: int, y: int) -> bool:
"""读 pix[x, y] 后检查是否目标颜色,越界/类型错误时返回 False。"""
try:
return _is_target_pixel(pix[x, y])
except (IndexError, TypeError):
return False
def _pick_optimal_x(analyser, scan_x_start: int, scan_x_end: int, rx: int) -> int:
"""选择本次扫描的最优起始列:优先用历史 last_fudai_x,否则默认热区中心。"""
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
):
return last_fudai_x * rx // 1080
except Exception:
pass
# 默认最优位置:最热门区域中心(98-240 的中心,约 169)
return 169 * rx // 1080
def _search_along_y(
pix,
scan_x_start: int,
scan_x_end: int,
optimal_x_scaled: int,
check_y: int,
) -> Optional[int]:
"""在指定 y 行上找第一个目标色像素的 x 坐标。
搜索顺序:optimal_x → 向两侧交替搜索 → 最后从左到右兜底。
"""
# 1. 先检查最优位置本身
if _safe_check_pixel(pix, optimal_x_scaled, check_y):
return optimal_x_scaled
# 2. 向左右两侧交替搜索
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 and _safe_check_pixel(pix, right_x, check_y):
return right_x
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start and _safe_check_pixel(pix, left_x, check_y):
return left_x
# 3. 最后从左到右扫一遍兜底
for x_scaled in range(scan_x_start, scan_x_end):
if _safe_check_pixel(pix, x_scaled, check_y):
return x_scaled
return None
def scan_pixel_by_pixel(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
) -> Tuple[bool, Optional[int]]:
"""逐像素遍历兜底(numpy 不可用 / 未命中时使用)。
Args:
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
"""
detected = False
detected_x: Optional[int] = None
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
optimal_x_scaled = _pick_optimal_x(analyser, scan_x_start, scan_x_end, rx)
# 确保最优位置在搜索范围内
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 = _search_along_y(
pix, scan_x_start, scan_x_end, optimal_x_scaled, check_y
)
if found_x is None:
continue
# 命中:转换回 1080 基准
detected_x = int(found_x * 1080.0 / max(1, rx))
detected = True
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
# 双截图记录:成功识别存档
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
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
break # 找到后退出 offset_y 循环
except Exception:
# 像素检测失败,记录但不影响主流程
pass
return detected, detected_x
@@ -1,279 +0,0 @@
"""douyin/detection/detection_pkg/finder_template_match - OpenCV 模板匹配兜底
像素检测(numpy + 逐像素)都失败时的最后兜底:用 OpenCV 模板匹配
(TM_CCOEFF_NORMED)在搜索区域里找 fudai.png 模板。
入口:match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) -> (detected, x)
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional, Tuple
def _resolve_template_path() -> str:
"""获取 fudai.png 模板的绝对路径。优先 path_config,回退到本文件相邻 assets/。"""
try:
from douyin.core import path_config
return path_config.get_assets_dir() + "/fudai.png"
except Exception:
# 兜底:导入失败时显式拼到项目根的 assets/,
# 不要用 dirname(__file__) 拼 "assets"(那样会推到 detection_pkg/assets)
return os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..", "..", "..",
"assets", "fudai.png",
)
)
def _save_search_roi(analyser, search_roi, last_match_path: str, loop: int, x1: int, x2: int, y_top: int, y_bottom: int, rw: int, rh: int) -> None:
"""保存搜索区域到 last_match.png(仅作日志/调试用)。"""
try:
import cv2
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 match_template(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
loop: int,
) -> Tuple[bool, Optional[int]]:
"""像素检测全部失败后的模板匹配兜底。
Args:
analyser: 提供 fudai_template_match_threshold / _log_kv / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
loop: 当前循环次数(仅用于日志)
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
"""
detected = False
detected_x: Optional[int] = None
try:
import cv2
import numpy as np
template_path = _resolve_template_path()
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
# 将 PIL 图片转换为 OpenCV 格式
pic_rgb = pic_new.convert("RGB")
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
height, width = screenshot_bgr.shape[:2]
# 定义搜索区域: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] # type: ignore[index]
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
try:
from douyin.core import path_config as _pc
match_dir = os.path.join(_pc.get_pic_dir(), "template_match")
except Exception:
match_dir = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..", "..", "..",
"pic", "template_match",
)
)
try:
os.makedirs(match_dir, exist_ok=True)
last_match_path = os.path.join(match_dir, "last_match.png")
_save_search_roi(
analyser, search_roi, last_match_path, loop,
x1, x2, y_top, y_bottom, rw, rh,
)
except Exception:
pass
# 模板太大就缩小
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template = cv2.resize(
template,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
th, tw = template.shape[:2]
# 执行模板匹配
if 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)
# 双截图记录:保存实时操作截图(搜索区域)
try:
from douyin.handlers import douyin_screenshot_manager
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
)
douyin_screenshot_manager.save_latest_attempt(
search_roi_pil, operation_type="template_match"
)
except Exception:
pass
try:
analyser._log_kv(
"[找福袋图标] 模板匹配兜底",
loop=loop,
匹配分数=round(max_val, 4),
阈值=template_threshold,
是否通过=bool(max_val >= template_threshold),
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
搜索区域尺寸=f"{rw}x{rh}",
模板尺寸=f"{tw}x{th}",
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
)
except Exception:
pass
if max_val < template_threshold:
return False, None
# 命中:保存成功识别存档
try:
from douyin.handlers import douyin_screenshot_manager
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
)
douyin_screenshot_manager.save_last_success(
search_roi_pil, operation_type="template_match"
)
except Exception:
pass
# 1080 基准坐标
detected_x_in_roi = max_loc[0]
detected_x = int(
(x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)
)
detected = True
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return detected, detected_x
except (ImportError, Exception) as e:
# OpenCV 不可用或模板匹配失败,让 caller 继续走未命中分支
try:
analyser._log_kv(
"[找福袋图标] 模板匹配异常",
loop=loop,
错误类型=type(e).__name__,
错误信息=str(e),
)
except Exception:
pass
return False, None
@@ -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
+2 -5
View File
@@ -21,11 +21,8 @@ def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
if not pic_path or (not os.path.exists(pic_path)):
return None
pic = Image.open(pic_path)
try:
pic.load()
return pic.convert("RGB")
finally:
pic.close()
pic.load() # Force load to catch truncated files early
return pic.convert("RGB")
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return None
+1 -1
View File
@@ -203,7 +203,7 @@ def detect_fudai_detail_page(
return False
try:
from douyin.detection.douyin_detection import check_detail_height
from .douyin_detection import check_detail_height
# 执行任务数量检测
task_count = int(check_detail_height(analyser) or 0)
-11
View File
@@ -63,18 +63,7 @@ ROBOT_VERIFY = (100, 1200, 980, 1780)
# 诊断购物红包(弹窗快速检测区域 - 文字区域)
DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写)
# COUNTDOWN_BOX = (390, 1140, 570, 1290)
# BUTTON_BOX = (306, 2030, 780, 2180)
# CONTENT_BOX = (200, 600, 880, 900)
# 点击坐标常量(基准分辨率 1080x2400)
# 关闭详情页:点击详情页旁边空白区域
DETAIL_OUTSIDE_CLICK = (500, 470)
# 参与抽奖按钮
PARTICIPATE_BTN_CLICK = (543, 2070)
# 粉丝团加入按钮
FANSCLUB_JOIN_CLICK = (540, 2006)
# 粉丝团加入按钮(回退坐标)
FANSCLUB_JOIN_FALLBACK_CLICK = (500, 2060)
+12 -16
View File
@@ -11,8 +11,6 @@ from typing import Any
from douyin.core import path_config
from .coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK
def attend_choujiang(analyser) -> bool:
"""点击参与抽奖。"""
@@ -151,7 +149,7 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
@@ -170,7 +168,7 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif (
@@ -283,7 +281,7 @@ def attend_choujiang(analyser) -> bool:
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击刚才打开福袋的旁边位置
analyser.click(500, 470) # 点击刚才打开福袋的旁边位置
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif attend_button_text and (
@@ -319,7 +317,7 @@ def attend_choujiang(analyser) -> bool:
analyser.operation.delay(0.5)
except Exception:
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
except Exception:
pass
return False
@@ -339,7 +337,7 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "无法参与" in attend_button_text:
@@ -355,7 +353,7 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "时长不足" in attend_button_text:
@@ -371,13 +369,13 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "评论" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
@@ -402,7 +400,7 @@ def attend_choujiang(analyser) -> bool:
elif attend_button_text and "参与抽奖" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
@@ -522,14 +520,12 @@ def attend_choujiang(analyser) -> bool:
elif attend_button_text and (
"加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text
):
from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import (
handle_fansclub_branch,
)
from douyin.fudai.core.fudai_attend_fansclub import handle_fansclub_branch
return handle_fansclub_branch(analyser, attend_button_text)
elif attend_button_text and "开始观看" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击开始观看(基于截图优化坐标)",
@@ -542,7 +538,7 @@ def attend_choujiang(analyser) -> bool:
elif attend_button_text and "参与" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与(基于截图优化坐标)",
@@ -1,23 +1,27 @@
"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler - 粉丝团门槛分支
"""福袋粉丝团分支处理模块
attend_choujiang 中"加入粉丝团/粉丝团"按钮分支的处理逻辑。原本是 1057 行 elif 块,
内嵌一个 _recover_to_fudai_detail_after_fansclub 闭包做"加入页"恢复。
入口:handle_fansclub_branch(analyser, attend_button_text) -> bool
返回 True(与原 elif 的 return True 一致)。
从 attend_choujiang 中拆出粉丝团门槛的处理逻辑(原 1057 行):
1. 第一次点击参与按钮
2. OCR 识别加入粉丝团按钮位置并点击
3. 关闭详情页
4. 如果非自动加入,等待 15 秒
5. 进入加入粉丝团独立页面后递归恢复回详情页
"""
from __future__ import annotations
import os
import time
from typing import Any
from douyin.core import path_config
from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK, FANSCLUB_JOIN_CLICK, FANSCLUB_JOIN_FALLBACK_CLICK
def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
"""处理"需要粉丝团门槛"分支:先点参与按钮 → OCR 找加入粉丝团按钮 → 点击 → 关闭详情 → 等待 → 恢复 → 返回 True。"""
"""处理粉丝团门槛分支,返回 True 表示完成(无论参与是否成功)。
上层 attend_choujiang 在该分支无条件返回 True。
"""
analyser.last_attend_fail_reason = "fansclub_required"
# 保存debug截图:标注OCR识别区域(参与按钮区域)
@@ -29,40 +33,34 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
from PIL import Image
pic = Image.open(pic_path)
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
try:
width, height = pic_rgb.size
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
# 缩放OCR区域坐标到实际分辨率
ocr_x1 = int(306 * width / rx)
ocr_y1 = int(2030 * height / ry)
ocr_x2 = int(780 * width / rx)
ocr_y2 = int(2110 * height / ry)
# 保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="参与按钮",
step="识别参与按钮",
coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2),
extra_info={
"ocr_text": attend_button_text[:50],
"region": "(306,2030)-(780,2110)",
"result": "需要粉丝团",
},
)
finally:
pic_rgb.close()
pic.load()
pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
# 缩放OCR区域坐标到实际分辨率
ocr_x1 = int(306 * width / rx)
ocr_y1 = int(2030 * height / ry)
ocr_x2 = int(780 * width / rx)
ocr_y2 = int(2110 * height / ry)
# 保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="参与按钮",
step="识别参与按钮",
coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2),
extra_info={
"ocr_text": attend_button_text[:50],
"region": "(306,2030)-(780,2110)",
"result": "需要粉丝团",
},
)
except Exception:
pass
# 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"粉丝团门槛:先点击参与按钮",
@@ -106,14 +104,10 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
from PIL import Image
img = Image.open(pic_path)
try:
img.load()
img_rgb = img.convert("RGB")
finally:
img.close()
img = img.convert("RGB")
import numpy as np
img_np = np.array(img_rgb)
img_np = np.array(img)
# 调用OCR获取原始结果
if getattr(analyser.operation, "ocr_type", None) == "easyocr":
@@ -194,42 +188,36 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
from PIL import Image
pic = Image.open(pic_path)
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
try:
width, height = pic_rgb.size
# 缩放OCR区域坐标到实际分辨率
ocr_x1 = int(ocr_region_x1 * width / rx)
ocr_y1 = int(ocr_region_y1 * height / ry)
ocr_x2 = int(ocr_region_x2 * width / rx)
ocr_y2 = int(ocr_region_y2 * height / ry)
# 保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="加入粉丝团按钮",
step="识别加入粉丝团按钮",
coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2),
extra_info={
"ocr_text": fansclub_text[:50] if fansclub_text else "",
"region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
"result": (
"识别成功"
if fansclub_text
and (
"加入粉丝团" in fansclub_text
or "粉丝团" in fansclub_text
)
else "识别失败"
),
"has_bbox": fansclub_bbox is not None,
},
)
finally:
pic_rgb.close()
pic.load()
pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size
# 缩放OCR区域坐标到实际分辨率
ocr_x1 = int(ocr_region_x1 * width / rx)
ocr_y1 = int(ocr_region_y1 * height / ry)
ocr_x2 = int(ocr_region_x2 * width / rx)
ocr_y2 = int(ocr_region_y2 * height / ry)
# 保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="加入粉丝团按钮",
step="识别加入粉丝团按钮",
coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2),
extra_info={
"ocr_text": fansclub_text[:50] if fansclub_text else "",
"region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})",
"result": (
"识别成功"
if fansclub_text
and (
"加入粉丝团" in fansclub_text
or "粉丝团" in fansclub_text
)
else "识别失败"
),
"has_bbox": fansclub_bbox is not None,
},
)
except Exception:
pass
@@ -324,7 +312,7 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e))
# 第三步:关闭详情页
analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击详情页旁边位置关闭详情页
analyser.click(500, 470) # 点击详情页旁边位置关闭详情页
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
if not analyser.auto_join_fansclub:
@@ -428,14 +416,10 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
from PIL import Image
img = Image.open(pic_path)
try:
img.load()
img_rgb = img.convert("RGB")
finally:
img.close()
img = img.convert("RGB")
import numpy as np
img_np = np.array(img_rgb)
img_np = np.array(img)
if (
getattr(
@@ -649,11 +633,11 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
except Exception:
# 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮)
try:
analyser.click(*FANSCLUB_JOIN_CLICK) # 粉丝团加入按钮优化坐标
analyser.click(540, 2006) # 粉丝团加入按钮优化坐标
except Exception:
# 最后回退到旧坐标
try:
analyser.click(*FANSCLUB_JOIN_FALLBACK_CLICK)
analyser.click(500, 2060)
except Exception:
pass
@@ -708,7 +692,7 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
analyser.operation.delay(1.0) # 等待点击完成
# 关闭详情页
analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击详情页旁边位置关闭详情页
analyser.click(500, 470) # 点击详情页旁边位置关闭详情页
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
analyser.operation.delay(1.0) # 等待关闭完成
except Exception as e:
@@ -805,14 +789,10 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
from PIL import Image
img = Image.open(pic_path)
try:
img.load()
img_rgb = img.convert("RGB")
finally:
img.close()
img = img.convert("RGB")
import numpy as np
img_np = np.array(img_rgb)
img_np = np.array(img)
if (
getattr(
@@ -1093,4 +1073,3 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
except Exception:
pass
return _recover_to_fudai_detail_after_fansclub()
return True
Whitespace-only changes.
+137 -145
View File
@@ -114,11 +114,8 @@ def safe_image_load(image_path: str) -> Optional[Image.Image]:
try:
pic = Image.open(image_path)
try:
pic.load()
return pic.convert("RGB")
finally:
pic.close()
pic.load() # 确保图像数据已加载
return pic.convert("RGB")
except UnidentifiedImageError as e:
# 图像格式不支持
raise ValueError(f"无法识别图像格式: {image_path}") from e
@@ -183,159 +180,154 @@ def save_full_screenshot_with_ocr_region(
return
# 安全加载图像
pic_rgb: Optional[Image.Image] = None
try:
try:
pic_rgb = safe_image_load(pic_path)
if pic_rgb is None:
return
except ValueError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "加载图像"},
level="ERROR",
)
return
except OSError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "读取图像文件"},
level="ERROR",
)
return
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "加载图像(未知错误)"},
level="ERROR",
)
pic_rgb = safe_image_load(pic_path)
if pic_rgb is None:
return
except ValueError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "加载图像"},
level="ERROR",
)
return
except OSError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "读取图像文件"},
level="ERROR",
)
return
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "加载图像(未知错误)"},
level="ERROR",
)
return
# 获取分辨率信息
width, height = pic_rgb.size
# 获取分辨率信息
width, height = pic_rgb.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "获取分辨率", "image_size": f"{width}x{height}"},
level="WARNING",
)
rx, ry = 1080, 2400 # 使用默认值
context.update({
"image_size": f"{width}x{height}",
"base_resolution": f"{rx}x{ry}",
})
# 缩放坐标到实际分辨率
try:
x1_base, y1_base, x2_base, y2_base = coords
x1 = int(x1_base * width / rx)
y1 = int((y1_base + y_pianyi) * height / ry)
x2 = int(x2_base * width / rx)
y2 = int((y2_base + y_pianyi) * height / ry)
scaled_coords = (x1, y1, x2, y2)
except (ValueError, ZeroDivisionError) as e:
log_debug_error(
analyser,
e,
{**context, "stage": "坐标缩放"},
level="ERROR",
)
return
# 验证和修正坐标
is_valid, error_msg, corrected_coords = validate_coords(
scaled_coords, width, height
)
if not is_valid:
log_debug_error(
analyser,
ValueError(f"坐标无效: {error_msg}"),
{**context, "stage": "坐标验证", "scaled_coords": scaled_coords},
level="WARNING",
)
return
x1, y1, x2, y2 = corrected_coords
# 如果坐标被修正,记录警告
if error_msg:
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "获取分辨率", "image_size": f"{width}x{height}"},
analyser._log_kv(
"验证",
"OCR区域坐标超出屏幕范围,已修正",
original_coords=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
corrected_coords=f"({x1},{y1})-({x2},{y2})",
screen_size=f"{width}x{height}",
base_coords=coords,
level="WARNING",
)
rx, ry = 1080, 2400 # 使用默认值
except Exception:
pass
context.update({
"image_size": f"{width}x{height}",
"base_resolution": f"{rx}x{ry}",
})
# 缩放坐标到实际分辨率
try:
x1_base, y1_base, x2_base, y2_base = coords
x1 = int(x1_base * width / rx)
y1 = int((y1_base + y_pianyi) * height / ry)
x2 = int(x2_base * width / rx)
y2 = int((y2_base + y_pianyi) * height / ry)
scaled_coords = (x1, y1, x2, y2)
except (ValueError, ZeroDivisionError) as e:
log_debug_error(
analyser,
e,
{**context, "stage": "坐标缩放"},
level="ERROR",
)
return
# 验证和修正坐标
is_valid, error_msg, corrected_coords = validate_coords(
scaled_coords, width, height
# 保存调试图片
try:
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname=picname,
step="before_ocr",
coords=(x1, y1, x2, y2),
extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi,
},
)
if not is_valid:
log_debug_error(
analyser,
ValueError(f"坐标无效: {error_msg}"),
{**context, "stage": "坐标验证", "scaled_coords": scaled_coords},
level="WARNING",
)
return
x1, y1, x2, y2 = corrected_coords
# 如果坐标被修正,记录警告
if error_msg:
if debug_path:
try:
analyser._log_kv(
"验证",
"OCR区域坐标超出屏幕范围,已修正",
original_coords=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
corrected_coords=f"({x1},{y1})-({x2},{y2})",
screen_size=f"{width}x{height}",
base_coords=coords,
"[调试图像]",
f"OCR识别前保存完整截图({picname})",
path=debug_path,
region=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
)
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "记录成功日志", "debug_path": debug_path},
level="WARNING",
)
except Exception:
pass
# 保存调试图片
try:
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname=picname,
step="before_ocr",
coords=(x1, y1, x2, y2),
extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
f"OCR识别前保存完整截图({picname})",
path=debug_path,
region=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
)
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "记录成功日志", "debug_path": debug_path},
level="WARNING",
)
except PermissionError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "保存调试图像(权限错误)"},
level="ERROR",
)
except OSError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "保存调试图像(系统错误)"},
level="ERROR",
)
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "保存调试图像(未知错误)"},
level="ERROR",
)
finally:
if pic_rgb is not None:
pic_rgb.close()
except PermissionError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "保存调试图像(权限错误)"},
level="ERROR",
)
except OSError as e:
log_debug_error(
analyser,
e,
{**context, "stage": "保存调试图像(系统错误)"},
level="ERROR",
)
except Exception as e:
log_debug_error(
analyser,
e,
{**context, "stage": "保存调试图像(未知错误)"},
level="ERROR",
)
# 向后兼容:保留原函数名
@@ -46,17 +46,15 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
path = path_config.get_screenshot_path()
try:
_raw = Image.open(path)
try:
_raw.load() # Force load to catch truncated files early
pic = _raw.convert("RGBA")
finally:
_raw.close()
pic = Image.open(path)
pic.load() # Force load to catch truncated files early
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return False
except Exception:
return False
pic = pic.convert("RGBA")
pix = pic.load()
w, h = pic.size
@@ -239,12 +237,9 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
_raw = Image.open(pic_path)
try:
_raw.load()
pic_rgb_check = _raw.convert("RGB")
finally:
_raw.close()
pic_check = Image.open(pic_path)
pic_check.load()
pic_rgb_check = pic_check.convert("RGB")
width, height = pic_rgb_check.size
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
@@ -6,7 +6,7 @@ from __future__ import annotations
import os
import time
from typing import Any, Dict, Optional, Tuple
from typing import Any, Dict, Tuple
from PIL import Image
@@ -168,18 +168,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pic_path = path_config.get_screenshot_path()
except Exception:
# 兜底:导入失败时显式拼到项目根的 pic/,
# 不要用 dirname(__file__) 拼"pic"(那样会推到 douyin/fudai/core/fudai_detail_orchestrator_pkg/pic)
pic_path = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
"..",
"pic",
"screenshot.png",
)
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
@@ -223,18 +213,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pic_path = path_config.get_screenshot_path()
except Exception:
# 兜底:导入失败时显式拼到项目根的 pic/,
# 不要用 dirname(__file__) 拼"pic"(那样会推到 douyin/fudai/core/fudai_detail_orchestrator_pkg/pic)
pic_path = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
"..",
"pic",
"screenshot.png",
)
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
wait_start = time.time()
@@ -255,18 +235,22 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pass
# 使用统一的截图路径配置
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
try:
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
pic_rgb = None
try:
if os.path.exists(pic_path):
_img0 = time.time()
pic = Image.open(pic_path)
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
pic.load()
pic_rgb = pic.convert("RGB")
image_load_ms = round((time.time() - _img0) * 1000, 1)
_log_perf("after_image_load") # 移除:避免过多性能日志
except Exception:
+2 -11
View File
@@ -211,17 +211,8 @@ def read_live_room_title_core(
pic_path = path_config.get_screenshot_path()
except Exception:
# 兜底:导入失败时显式拼到项目根的 pic/,
# 不要用 dirname(__file__) 拼"pic"(那样会推到 douyin/fudai/core/pic)
pic_path = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
"pic",
"screenshot.png",
)
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
+21 -26
View File
@@ -54,27 +54,28 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
# 检查1:内容不能为空(至少要有一些文字)
# 如果运行时显式禁用了内容识别,则跳过此检查(允许内容为空)
disable_content = False
if analyser:
try:
try:
disable_content = False
if analyser:
disable_content = bool(
getattr(analyser, "fudai_disable_content_recognition", False)
)
except Exception:
pass
if not disable_content:
try:
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_content = bool(
cfg.get("fudai_disable_content_recognition", False)
)
except Exception:
pass
if not disable_content:
# 如果 analyser 未设置该属性,再尝试从 config.json 读取全局配置
if not disable_content:
try:
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_content = bool(
cfg.get("fudai_disable_content_recognition", False)
)
except Exception:
pass
if not disable_content:
if not content or len(content.strip()) < 2:
return False, "content_empty_or_too_short"
except Exception:
if not content or len(content.strip()) < 2:
return False, "content_empty_or_too_short"
@@ -201,14 +202,8 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
).strip()
if countdown_mm_raw and countdown_ss_raw:
try:
from douyin.utils.time_utils import extract_2digits
mm_str = extract_2digits(countdown_mm_raw)
ss_str = extract_2digits(countdown_ss_raw)
if not mm_str or not ss_str:
return False, "countdown_mm_ss_not_numeric"
mm = int(mm_str)
ss = int(ss_str)
mm = int(countdown_mm_raw)
ss = int(countdown_ss_raw)
if mm < 0 or mm > 59 or ss < 0 or ss > 59:
return False, "countdown_mm_ss_invalid_range"
# 如果有倒计时元组,验证是否一致
@@ -10,9 +10,8 @@ import re
import time
from typing import Any, Tuple
from .helpers import _is_short_countdown_text, is_watch_task_fudai
from .helpers import _is_short_countdown_text
from .should_skip import should_skip_fudai_by_config
from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
@@ -55,36 +54,20 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
)
return False
elif last_status == "validation_failed":
# 按钮状态为可操作时,即使验证失败也继续走参与流程
_ACTIONABLE = {
"可以参与", "需要加入粉丝团", "需要评论",
"需要观看", "已参与",
}
_btn_st = getattr(analyser, "_fudai_button_status", None)
if _btn_st in _ACTIONABLE:
try:
analyser._log_kv(
"参与",
"basic_join_decision:验证失败但按钮可操作,继续参与",
button_status=_btn_st,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"参与",
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
)
except Exception:
pass
elapsed = time.time() - start_time
try:
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
)
return False
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
@@ -98,66 +81,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser)
if not is_valid:
# 按钮状态为可操作时,即使验证失败也继续走参与流程
_ACTIONABLE = {
"可以参与", "需要加入粉丝团", "需要评论",
"需要观看", "已参与",
}
_btn_st = getattr(analyser, "_fudai_button_status", None)
if _btn_st in _ACTIONABLE:
try:
analyser._log_kv(
"参与",
"basic_join_decision:验证失败但按钮可操作,继续参与",
validation_reason=reason,
button_status=_btn_st,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"参与",
"basic_join_decision:福袋详情数据验证失败,识别出错",
validation_reason=reason,
content=content[:50] if content else "",
prize_value_yuan=prize_value_yuan,
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
if not content and prize_value_yuan == 0.0:
# 按钮状态为可操作时,即使详情为空也继续走参与流程
_ACTIONABLE = {
"可以参与", "需要加入粉丝团", "需要评论",
"需要观看", "已参与",
}
_btn_st = getattr(analyser, "_fudai_button_status", None)
if _btn_st in _ACTIONABLE:
try:
analyser._log_kv(
"参与",
"basic_join_decision:详情为空但按钮可操作,继续参与",
button_status=_btn_st,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"参与",
"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
content=content,
"basic_join_decision:福袋详情数据验证失败,识别出错",
validation_reason=reason,
content=content[:50] if content else "",
prize_value_yuan=prize_value_yuan,
)
except Exception:
@@ -165,10 +94,31 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(无效详情)",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
if not content and prize_value_yuan == 0.0:
try:
analyser._log_kv(
"参与",
"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
content=content,
prize_value_yuan=prize_value_yuan,
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(无效详情)",
elapsed_seconds=round(elapsed, 2),
)
return False
# 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋
try:
@@ -184,7 +134,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
except Exception:
pass
# 这里需要导入 attend_choujiang 函数
from ..fudai_attend import attend_choujiang
from .fudai_attend import attend_choujiang
result = attend_choujiang(analyser)
elapsed = time.time() - start_time
@@ -276,7 +226,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
pass
# 关闭详情页
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
@@ -415,7 +365,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
pass
# 关闭详情页
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
@@ -519,7 +469,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
pass
# 丢弃时,尽量关闭详情,避免停留在详情页
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
@@ -561,7 +511,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
analyser._log_kv("参与", "basic_join_decision:开始参与抽奖")
except Exception:
pass
from ..fudai_attend import attend_choujiang
from .fudai_attend import attend_choujiang
result = attend_choujiang(analyser)
elapsed = time.time() - start_time
File diff suppressed because it is too large. Load diff
@@ -1,200 +0,0 @@
"""douyin_fudai_core_pkg.countdown_split - 福袋倒计时区域分割识别
从 get_fudai_contain 抽出的 _read_countdown_split 闭包:
把倒计时区域分割成"分钟段"和"秒段",分别 OCR 后组合为 mm:ss。
签名:
read_countdown_split(analyser, box, *, save_debug_images=False) -> str
返回 mm:ss(如 "03:25");识别失败返回空字符串。
保留原行为和日志:日志 tag、warning level、错误兜底全部不变。
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from typing import Tuple
def _extract_digits(text: str, max_digits: int = 2) -> str:
"""提取数字,最多 max_digits 位,取前 max_digits 位优先。"""
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
if len(digits) > max_digits:
candidate = digits[:max_digits]
if set(candidate) == {"0"} and digits.lstrip("0"):
actual = digits.lstrip("0")[:max_digits]
return actual.zfill(max_digits)
return candidate
if len(digits) == 1:
return "0" + digits
return digits
def read_countdown_split(
analyser,
box: Tuple[int, int, int, int],
*,
save_debug_images: bool = False,
) -> str:
"""将倒计时区域分割成"分钟段"和"秒段",分别 OCR 识别,然后组合为 mm:ss。
倒计时格式通常是:XX:XX后开奖,其中前两位是分钟,中间两位是秒。
分割:前 30% 为分钟数字框,中间 30% 为秒数字框(剩余 40% 是冒号 + "后开奖")。
Args:
analyser: fudai_analyse 实例(提供 cut_pic / operation / _log_kv / y_pianyi)
box: 倒计时区域 (x1, y1, x2, y2)
save_debug_images: 是否保存调试截图(仅当全局开关启用时)
Returns:
mm:ss 字符串(识别成功),空字符串(识别失败)
"""
try:
from douyin.fudai.core.fudai_debug_utils import (
_save_full_screenshot_with_ocr_region,
)
except Exception:
_save_full_screenshot_with_ocr_region = None # type: ignore[assignment]
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
except Exception:
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
return str(picname)
try:
x1, y1, x2, y2 = box
w = max(1, int(x2 - x1))
# 优化:根据实际布局,倒计时通常是:分钟(2位数字框) + 冒号 + 秒(2位数字框) + 后开奖
# 更精确的分割:前30%为分钟数字框,中间30%为秒数字框(剩余40%包含冒号和"后开奖")
seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框
seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框
# 保存调试截图(仅在配置启用时)
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
try:
_save_full_screenshot_with_ocr_region(
analyser,
"福袋倒计时_分钟",
(x1, y1, x1 + seg1, y2),
analyser.y_pianyi,
)
_save_full_screenshot_with_ocr_region(
analyser,
"福袋倒计时_秒",
(x1 + seg1, y1, x1 + seg1 + seg2, y2),
analyser.y_pianyi,
)
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"保存倒计时调试截图失败",
error=str(e_inner),
error_type=type(e_inner).__name__,
box=box,
level="WARNING",
)
except Exception:
pass
# 切割分钟区域(左侧)
analyser.cut_pic(
x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
)
# 切割秒区域(中间,跳过冒号)
analyser.cut_pic(
x1 + seg1,
y1,
x1 + seg1 + seg2,
y2,
"",
"福袋倒计时_秒",
analyser.y_pianyi,
)
# 并行执行两个 OCR 识别(使用轻量数字 OCR),优先预处理以提高识别率
try:
mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟")
ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒")
except Exception:
mm_name = "福袋倒计时_分钟"
ss_name = "福袋倒计时_秒"
with ThreadPoolExecutor(max_workers=2) as executor:
future_mm = executor.submit(
analyser.operation.analyse_pic_digits, mm_name, 1
)
future_ss = executor.submit(
analyser.operation.analyse_pic_digits, ss_name, 1
)
mm_raw = future_mm.result()
ss_raw = future_ss.result()
mm = _extract_digits(mm_raw, max_digits=2)
ss = _extract_digits(ss_raw, max_digits=2)
# 分割识别已经分别识别了分钟和秒,顺序是正确的,不需要交换纠正
# 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果)
try:
mm_int = int(mm) if mm else 0
ss_int = int(ss) if ss else 0
if ss_int >= 60:
try:
analyser._log_kv(
"验证",
"分割识别:检测到秒数>=60(可能是识别错误)",
mm=mm_int,
ss=ss_int,
mm_raw=mm_raw,
ss_raw=ss_raw,
level="WARNING",
)
except Exception:
pass
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"验证倒计时数值失败",
error=str(e_inner),
error_type=type(e_inner).__name__,
mm=mm,
ss=ss,
level="WARNING",
)
except Exception:
pass
if mm and ss:
result = f"{mm}:{ss}"
try:
analyser._log_kv(
"福袋倒计时",
"分割识别成功",
mm_raw=mm_raw,
ss_raw=ss_raw,
result=result,
)
except Exception as e_inner:
try:
analyser._log_kv(
"错误",
"记录倒计时识别成功日志失败",
error=str(e_inner),
error_type=type(e_inner).__name__,
level="WARNING",
)
except Exception:
pass
return result
except Exception as e_inner:
try:
analyser._log_kv(
"福袋倒计时",
"分割识别失败",
error=str(e_inner),
error_type=type(e_inner).__name__,
)
except Exception:
pass
return ""
@@ -1,111 +0,0 @@
"""douyin_fudai_core_pkg.cut_regions - 福袋详情区域截图准备
把 get_fudai_contain 中按 renwu 分 4 个分支的"内容/倒计时/价值"截图准备逻辑
合并成一个 helper。4 个分支唯一的差异是 countdown_box,其它操作都一样。
"""
from __future__ import annotations
from typing import Tuple, Optional
def _select_countdown_box(renwu: int) -> Tuple[int, int, int, int]:
"""根据任务数选 countdown_box 坐标常量。"""
from douyin.fudai.core.coords import (
COUNTDOWN_1010_1130,
COUNTDOWN_1110_1230,
COUNTDOWN_1140_1290,
COUNTDOWN_1460_1580,
)
if renwu == 2:
return COUNTDOWN_1110_1230
if renwu == 1:
return COUNTDOWN_1140_1290
if renwu == 3:
return COUNTDOWN_1010_1130
return COUNTDOWN_1460_1580
def cut_detail_regions(
analyser,
renwu: int,
*,
save_debug_images: bool = False,
) -> Tuple[int, int, int, int]:
"""根据 renwu 切割福袋详情的"内容/倒计时分钟/倒计时秒/价值"4 个区域。
倒计时区域内部还会按 30%/30% 比例分割成"分钟"和"秒"两段单独切。
Args:
analyser: fudai_analyse 实例(提供 cut_pic / y_pianyi)
renwu: 任务数量(1/2/3,其它视为默认)
save_debug_images: 是否保存全屏带 OCR 区域标注的调试截图
Returns:
countdown_box: 选中的倒计时区域 (x1, y1, x2, y2),供后续 _read_countdown_split 使用
"""
from douyin.fudai.core.coords import (
VALUE_BOX_TARGET,
CONTENT_BOX,
)
try:
from douyin.fudai.core.fudai_debug_utils import (
_save_full_screenshot_with_ocr_region,
)
except Exception:
_save_full_screenshot_with_ocr_region = None # type: ignore[assignment]
countdown_box = _select_countdown_box(renwu)
value_box = VALUE_BOX_TARGET
# 1. 福袋内容
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
try:
_save_full_screenshot_with_ocr_region(
analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi
)
except Exception:
pass
analyser.cut_pic(*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi)
# 2. 倒计时区域分割(前 30% 分钟 + 中间 30% 秒)
x1, y1, x2, y2 = countdown_box
w = max(1, int(x2 - x1))
seg1 = max(1, int(w * 0.3)) # 前 30%:分钟数字框
seg2 = max(1, int(w * 0.3)) # 中间 30%:秒数字框
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
try:
_save_full_screenshot_with_ocr_region(
analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi
)
except Exception:
pass
analyser.cut_pic(
x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
)
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
try:
_save_full_screenshot_with_ocr_region(
analyser,
"福袋倒计时_秒",
(x1 + seg1, y1, x1 + seg1 + seg2, y2),
analyser.y_pianyi,
)
except Exception:
pass
analyser.cut_pic(
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
)
# 3. 福袋价值
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
try:
_save_full_screenshot_with_ocr_region(
analyser, "福袋价值", value_box, analyser.y_pianyi
)
except Exception:
pass
analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi)
return countdown_box
@@ -1,165 +0,0 @@
"""douyin_fudai_core_pkg.heavy_ocr - 福袋详情按需补 OCR
从 get_fudai_contain 抽出的 _run_heavy_ocr 闭包:当轻量 OCR 漏字段时,
按需调用更重的文本/数字模型补齐 task_list / content / countdown_mm /
countdown_ss / value / button 共 6 个字段。
签名:
run_heavy_ocr(analyser, fields) -> Dict[str, Any]
返回字典含成功补到的字段值 + "_duration_ms"。失败字段不进字典。
所有日志、配置开关读取行为与原闭包一致。
"""
from __future__ import annotations
import json
import os
import time
from typing import Any, Dict, Set
def _read_disable_flag(analyser, attr_name: str, cfg_key: str) -> bool:
"""读取 analyser 属性,无值再回退到 config.json。"""
try:
flag = bool(getattr(analyser, attr_name, False))
except Exception:
flag = False
if flag:
return True
try:
from douyin.core import path_config
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
return bool(cfg.get(cfg_key, False))
except Exception:
pass
return False
def run_heavy_ocr(analyser, fields: Set[str]) -> Dict[str, Any]:
"""按需补充较重的 OCR,避免默认就跑全量重模型。
Args:
analyser: fudai_analyse 实例(提供 operation / _log_kv / 配置开关)
fields: 需要补的字段集合,可包含 task_list / content / countdown_mm /
countdown_ss / value / button
Returns:
Dict 含成功识别到的字段;总耗时记在 "_duration_ms"。
"""
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
except Exception:
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
return str(picname)
results: Dict[str, Any] = {}
heavy_start = time.time()
def _safe_preprocess(name: str) -> str:
try:
return preprocess_for_ocr(analyser, name)
except Exception:
return name
# 任务列表:用于兜底检测观看任务(尊重配置开关)
if "task_list" in fields:
if _read_disable_flag(
analyser,
"fudai_disable_task_recognition",
"fudai_disable_task_recognition",
):
try:
analyser._log_kv(
"福袋", "跳过福袋任务列表OCR识别(配置启用)"
)
except Exception:
pass
else:
try:
name_tl = _safe_preprocess("福袋任务列表")
results["task_list"] = analyser.operation.analyse_pic_word(
name_tl, 1
)
except Exception:
pass
# 内容:使用更重的文本模型兜底(尊重配置开关)
if "content" in fields:
if _read_disable_flag(
analyser,
"fudai_disable_content_recognition",
"fudai_disable_content_recognition",
):
try:
analyser._log_kv(
"福袋", "跳过福袋内容OCR识别(配置启用)"
)
except Exception:
pass
else:
try:
name_fc = _safe_preprocess("福袋内容")
results["content"] = analyser.operation.analyse_pic_word(
name_fc, 1
)
except Exception:
pass
# 倒计时:先数字模型,失败再文本提取数字
if "countdown_mm" in fields:
mm_digits = _ocr_digits_with_fallback(analyser, "福袋倒计时_分钟")
if mm_digits:
results["countdown_mm"] = mm_digits
if "countdown_ss" in fields:
ss_digits = _ocr_digits_with_fallback(analyser, "福袋倒计时_秒")
if ss_digits:
results["countdown_ss"] = ss_digits
# 价值:重模型兜底一次,兼容带符号文本
if "value" in fields:
try:
name_val = _safe_preprocess("福袋价值")
raw_val = analyser.operation.analyse_pic_word(name_val, 0)
results["value"] = str(raw_val or "")
except Exception:
pass
# 按钮状态:重模型兜底,避免轻量误判
if "button" in fields:
try:
name_btn = _safe_preprocess("参与按钮")
results["button"] = analyser.operation.analyse_pic_word(name_btn, 1)
except Exception:
pass
try:
results["_duration_ms"] = round((time.time() - heavy_start) * 1000, 1)
except Exception:
pass
return results
def _ocr_digits_with_fallback(analyser, picname: str) -> str:
"""先 analyse_pic_digits,失败再 analyse_pic_word,提取数字。
返回提取到的数字字符串;都失败返回 ""。
"""
digits = ""
try:
raw = analyser.operation.analyse_pic_digits(picname, 1)
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
if not digits:
try:
raw = analyser.operation.analyse_pic_word(picname, 1)
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
except Exception:
pass
return digits
@@ -20,6 +20,11 @@ class _FudaiOcrExecutorState:
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
def _get_fudai_ocr_executor(optimal_workers: int) -> ThreadPoolExecutor:
"""获取复用的 OCR 线程池;如线程数变化则重建。"""
state = _fudai_ocr_executor_state
@@ -1,340 +0,0 @@
"""douyin_fudai_core_pkg.ocr_tasks - 福袋详情 7 个并行 OCR 子任务
把 get_fudai_contain 中 7 个 ocr_* 闭包封装成一个类。每个方法对应
ThreadPoolExecutor 的一个并行任务:
OcrTaskRunner.ocr_task_list 福袋任务列表
OcrTaskRunner.ocr_content 福袋内容
OcrTaskRunner.ocr_countdown_mm 倒计时分钟(数字模型)
OcrTaskRunner.ocr_countdown_ss 倒计时秒(数字模型)
OcrTaskRunner.ocr_value 福袋价值
OcrTaskRunner.ocr_button 参与按钮状态
OcrTaskRunner.ocr_live_room_title 直播间标题
每个方法的 finally 把单项耗时(ms)写入共享 dict(用 lock 保护),便于
主流程后续聚合输出性能日志。所有日志、配置开关读取行为与原闭包一致。
"""
from __future__ import annotations
import threading
import time
from typing import Any, Dict, Optional, Tuple
# OCR 按钮关键词列表(识别到任一即可短路返回,省 50% 时间)
_BUTTON_KEYWORDS = (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
"加入粉丝团",
"粉丝团",
"等待开奖",
"未达成",
)
def _safe_preprocess(analyser, name: str) -> str:
"""preprocess_for_ocr 的安全包装:失败时返回原 name。"""
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
return preprocess_for_ocr(analyser, name)
except Exception:
return name
class OcrTaskRunner:
"""7 个并行 OCR 子任务的运行器。
Args:
analyser: fudai_analyse 实例
perf_durations: 共享 dict,存放各任务的耗时(ms)
perf_lock: 保护 perf_durations 的 Lock
disable_content_recognition: 主流程已经读到的内容 OCR 开关(避免每次任务再读一次)
"""
def __init__(
self,
analyser,
perf_durations: Dict[str, float],
perf_lock: threading.Lock,
*,
disable_content_recognition: bool = False,
):
self.analyser = analyser
self.durations = perf_durations
self.lock = perf_lock
self.disable_content_recognition = bool(disable_content_recognition)
# ============================================================
# 内部工具
# ============================================================
def _record_duration(self, key: str, start: float) -> None:
try:
dur = round((time.time() - start) * 1000, 1)
with self.lock:
self.durations[key] = dur
except Exception:
pass
def _log_warn(self, msg: str, exc: BaseException) -> None:
try:
self.analyser._log_kv(
"错误",
msg,
error=str(exc),
error_type=type(exc).__name__,
level="WARNING",
)
except Exception:
pass
# ============================================================
# 7 个并行 OCR 子任务
# ============================================================
def ocr_task_list(self) -> Optional[str]:
"""OCR 识别福袋任务列表(用于检测观看任务,尊重配置开关)。"""
start = time.time()
try:
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import (
_read_disable_flag,
)
disable = _read_disable_flag(
self.analyser,
"fudai_disable_task_recognition",
"fudai_disable_task_recognition",
)
if disable:
try:
self.analyser._log_kv(
"福袋", "跳过福袋任务列表OCR识别(配置启用)"
)
except Exception:
pass
return None
name_tl = _safe_preprocess(self.analyser, "福袋任务列表")
return self.analyser.operation.analyse_pic_word(name_tl, 0)
except Exception as e:
self._log_warn("OCR识别任务列表失败", e)
return None
finally:
self._record_duration("ocr_task_list", start)
def ocr_content(self) -> Optional[str]:
"""OCR 识别福袋内容。"""
start = time.time()
try:
if self.disable_content_recognition:
try:
self.analyser._log_kv(
"福袋", "跳过福袋内容OCR识别(配置启用)"
)
except Exception:
pass
return None
name_fc = _safe_preprocess(self.analyser, "福袋内容")
return self.analyser.operation.analyse_pic_word(name_fc, 0)
except Exception as e:
self._log_warn("OCR识别福袋内容失败", e)
return None
finally:
self._record_duration("ocr_content", start)
def ocr_countdown_mm(self) -> Optional[str]:
"""OCR 识别福袋倒计时分钟(纯数字模型,无回退)。"""
start = time.time()
try:
raw = str(
self.analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) or ""
)
return "".join(ch for ch in raw if ch.isdigit())
except Exception as e:
self._log_warn("OCR识别倒计时分钟失败", e)
return None
finally:
self._record_duration("ocr_countdown_mm", start)
def ocr_countdown_ss(self) -> Optional[str]:
"""OCR 识别福袋倒计时秒(纯数字模型,无回退)。"""
start = time.time()
try:
raw = str(
self.analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) or ""
)
return "".join(ch for ch in raw if ch.isdigit())
except Exception as e:
self._log_warn("OCR识别倒计时秒失败", e)
return None
finally:
self._record_duration("ocr_countdown_ss", start)
def ocr_value(self) -> Optional[str]:
"""OCR 识别福袋价值(普通文本模型,支持小数点)。"""
start = time.time()
try:
name_val = _safe_preprocess(self.analyser, "福袋价值")
word_raw = str(
self.analyser.operation.analyse_pic_word(name_val, 0) or ""
)
return word_raw
except Exception as e:
self._log_warn("OCR识别福袋价值失败", e)
return None
finally:
self._record_duration("ocr_value", start)
def ocr_button(self) -> Optional[str]:
"""OCR 识别参与按钮状态(关键词短路,节省 50% OCR 时间)。
注意:原闭包没有 finally 计时(按钮属于同步路径),保留这个差异。
"""
try:
name_btn = _safe_preprocess(self.analyser, "参与按钮")
# 模式 0 试一次:若识别到关键词直接返回
button_text = str(
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
if button_text and any(k in button_text for k in _BUTTON_KEYWORDS):
return button_text
# 模式 0 完全失败时再试一次(保留旧逻辑:仍是模式 0)
if not button_text:
button_text = str(
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
return button_text
except Exception as e:
self._log_warn("OCR识别参与按钮失败", e)
return None
def ocr_live_room_title(self) -> Tuple[str, str]:
"""OCR 识别直播间标题,返回 (title, raw_text)。"""
start = time.time()
try:
from douyin.fudai.core.fudai_detail_room_title import (
_ocr_try_room_title,
)
return _ocr_try_room_title(self.analyser, "live_room_title_mid", 0)
except Exception as e:
self._log_warn("OCR识别直播间标题失败", e)
return "", ""
finally:
self._record_duration("ocr_live_room_title", start)
class OcrTaskRunnerFallback:
"""主并行 OCR 失败时的备用任务集。
与 OcrTaskRunner 区别:
- 不记录 perf_durations(备用路径调用频率低,无性能追踪需求)
- countdown_mm / countdown_ss 直接返回原始 OCR 结果(不做数字提取)
- 日志里把 tag 改为"备用OCR..."
Args:
analyser: fudai_analyse 实例
disable_content_recognition: 主流程已读到的内容 OCR 开关
"""
def __init__(
self,
analyser,
*,
disable_content_recognition: bool = False,
):
self.analyser = analyser
self.disable_content_recognition = bool(disable_content_recognition)
def _log_warn(self, msg: str, exc: BaseException) -> None:
try:
self.analyser._log_kv(
"错误",
msg,
error=str(exc),
error_type=type(exc).__name__,
level="WARNING",
)
except Exception:
pass
def ocr_task_list(self) -> Optional[str]:
try:
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import (
_read_disable_flag,
)
disable = _read_disable_flag(
self.analyser,
"fudai_disable_task_recognition",
"fudai_disable_task_recognition",
)
if disable:
try:
self.analyser._log_kv(
"福袋", "跳过备用福袋任务列表OCR识别(配置启用)"
)
except Exception:
pass
return None
name_tl = _safe_preprocess(self.analyser, "福袋任务列表")
return self.analyser.operation.analyse_pic_word(name_tl, 0)
except Exception as e:
self._log_warn("备用OCR识别任务列表失败", e)
return None
def ocr_content(self) -> Optional[str]:
if self.disable_content_recognition:
try:
self.analyser._log_kv(
"福袋", "跳过备用福袋内容OCR识别(配置启用)"
)
except Exception:
pass
return None
try:
return self.analyser.operation.analyse_pic_word("福袋内容", 0)
except Exception as e:
self._log_warn("备用OCR识别福袋内容失败", e)
return None
def ocr_countdown_mm(self):
try:
return self.analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0)
except Exception as e:
self._log_warn("备用OCR识别倒计时分钟失败", e)
return None
def ocr_countdown_ss(self):
try:
return self.analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0)
except Exception as e:
self._log_warn("备用OCR识别倒计时秒失败", e)
return None
def ocr_value(self):
try:
return self.analyser.operation.analyse_pic_word("福袋价值", 0)
except Exception as e:
self._log_warn("备用OCR识别福袋价值失败", e)
return None
def ocr_button(self) -> Optional[str]:
try:
name_btn = _safe_preprocess(self.analyser, "参与按钮")
button_text = str(
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
if not button_text or not any(
k in button_text for k in _BUTTON_KEYWORDS
):
button_text = str(
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
)
return button_text
except Exception as e:
self._log_warn("备用OCR识别参与按钮失败", e)
return None
@@ -79,11 +79,8 @@ class FudaiDetailVerifier:
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
pic = Image.open(pic_path)
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
pic.load()
pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size
rx = int(
@@ -7,14 +7,11 @@ from __future__ import annotations
# pylint: disable=E1101
import os
import time
from typing import Any, Dict, Optional
from PIL import Image
from douyin.core import path_config
def detect_by_template(analyser, rx: int, pic: Image.Image, region: Dict) -> Optional[int]:
"""使用模板匹配在指定区域查找福袋图标(优化版:多方法+预处理)
@@ -452,6 +452,8 @@ class FudaiDetector:
pass
return detected_x
if found_x is not None:
break # 找到后退出offset_y循环
except Exception:
pass
@@ -62,21 +62,18 @@ class FudaiImageAcquirer:
# 读取截图
try:
pic = Image.open(self.screenshot_path)
pic.load()
elapsed = (time.time() - start_time) * 1000
try:
pic.load()
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 图像获取",
"成功",
elapsed_ms=round(elapsed, 2),
size=f"{pic.size[0]}x{pic.size[1]}",
)
except Exception:
pass
return pic.convert("RGBA")
finally:
pic.close()
self.analyser._log_kv(
"[福袋查找] 图像获取",
"成功",
elapsed_ms=round(elapsed, 2),
size=f"{pic.size[0]}x{pic.size[1]}",
)
except Exception:
pass
return pic.convert("RGBA")
except Exception:
return None
except Exception as e:
@@ -39,7 +39,7 @@ def check_have_fudai_with_ready_screenshot_optimized(
screenshot_ready: 是否已有可用截图
返回:
福袋X坐标(1080基准),未找到返回 0
福袋X坐标(1080基准),未找到返回False
"""
# 只检测,不点击(避免与 find_and_open_fudai_detail 重复点击)
try:
@@ -47,13 +47,13 @@ def check_have_fudai_with_ready_screenshot_optimized(
pic = acquirer.acquire_screenshot(force_refresh=not screenshot_ready)
if pic is None:
return 0
return False
detector = FudaiDetector(analyser)
detected_x, _detect_method = detector.detect(pic)
if detected_x is not None:
return int(detected_x)
return 0
return False
except Exception:
return False
@@ -26,6 +26,8 @@ from ._common import (
_debug_save_queue,
_debug_save_shutdown_event,
_debug_save_worker_lock,
_LOGGER,
_mgr_log,
)
from . import _common as _state
from .paths import ensure_debug_captures_dir
@@ -351,3 +353,8 @@ def _ensure_debug_save_worker_started() -> None:
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
t.start()
_state._debug_save_worker_started = True
# 注册 atexit 清理函数(仅注册一次)
import atexit
atexit.register(shutdown_debug_save_worker)
@@ -4,6 +4,7 @@ from __future__ import annotations
import os
import shutil
import time
from datetime import datetime
from douyin.core import path_config
@@ -11,8 +11,6 @@ from datetime import datetime
from douyin.core import path_config
from ._common import _mgr_log
def get_ocr_dir() -> str:
"""获取OCR目录路径"""
@@ -138,11 +138,8 @@ def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool:
try:
if not os.path.exists(source_path):
return False
_raw = Image.open(source_path)
try:
return save_latest_attempt(_raw, operation_type)
finally:
_raw.close()
image = Image.open(source_path)
return save_latest_attempt(image, operation_type)
except Exception as e:
try:
_mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}")
@@ -166,11 +163,8 @@ def save_success_from_file(source_path: str, operation_type: str = "") -> bool:
try:
if not os.path.exists(source_path):
return False
_raw = Image.open(source_path)
try:
return save_last_success(_raw, operation_type)
finally:
_raw.close()
image = Image.open(source_path)
return save_last_success(image, operation_type)
except Exception as e:
try:
_mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}")
@@ -8,9 +8,12 @@ from __future__ import annotations
import json
import os
import re
import threading
import time
import traceback
from datetime import datetime
from typing import Optional, Tuple
from typing import Any, Optional, Tuple
import logging
from PIL import Image, ImageDraw, ImageFont
@@ -18,22 +21,17 @@ from PIL import Image, ImageDraw, ImageFont
from douyin.core import path_config
from ._common import (
_async_save_counters_lock,
_debug_save_queue,
_LOGGER,
_mgr_log,
_SKIP_DEBUG_SAVE_IN_HOTLOOPS,
)
from .cleanup import (
_OPERATION_TYPE_CN,
_PICNAME_CN,
_STEP_CN,
_EXTRA_INFO_KEY_CN,
cleanup_debug_captures,
count_debug_captures_files,
)
from . import _common as _state
from .paths import (
ensure_debug_captures_dir,
get_category_for_picname,
get_debug_captures_dir,
get_debug_captures_base_dir,
)
from .async_save import _ensure_debug_save_worker_started
@@ -728,3 +726,6 @@ def save_debug_image( # type: ignore
except Exception:
pass
return None
# 结束 save_debug_image 的主逻辑,返回 None 表示保存失败
return None
+12 -7
View File
@@ -14,17 +14,19 @@
from .log_formatter import (
format_debug_log,
format_action_log,
format_error_log,
format_call_stack,
format_parameters,
format_variables,
format_exception,
add_separators,
add_colors,
beautify_log_output,
colorize_log_line,
)
# 性能追踪模块
from .performance_tracker import PerformanceTracker
# 错误与调试日志(合并到 internal_loggers)
from .internal_loggers import ErrorLogger, DebugLogger
from .internal_loggers import ErrorLogger, DebugLogger, _get_debug_logger
# 行为日志模块(含 track_action 装饰器)
from .action_logger import ActionLogger, track_action
@@ -36,10 +38,12 @@ __all__ = [
# 格式化函数
"format_debug_log",
"format_action_log",
"format_error_log",
"format_call_stack",
"format_parameters",
"format_variables",
"format_exception",
"add_separators",
"add_colors",
"beautify_log_output",
"colorize_log_line",
# 类
"PerformanceTracker",
"ErrorLogger",
@@ -48,4 +52,5 @@ __all__ = [
"LoggingWrapper",
# 装饰器和工具函数
"track_action",
"_get_debug_logger",
]
+9
View File
@@ -95,6 +95,15 @@ class ActionLogger:
msg = format_action_log(operation, details or "", **extra)
_logger.info(msg)
def log_ocr(self, region: str, result: str, elapsed: Optional[float] = None) -> None:
self.log_operation("OCR", f"region={region} result={result}", elapsed=elapsed)
def log_decision(self, decision: str, elapsed: Optional[float] = None) -> None:
self.log_operation("Decision", decision, elapsed=elapsed)
def log_state_change(self, before: str, after: str, elapsed: Optional[float] = None) -> None:
self.log_operation("StateChange", f"{before}->{after}", elapsed=elapsed)
def log_step(self, name: str, elapsed: Optional[float] = None) -> None:
self.log_operation("Step", name, elapsed=elapsed)
+40 -1
View File
@@ -146,6 +146,32 @@ class DebugLogger:
def __init__(self, enabled: bool = True) -> None:
self.enabled = enabled
def log_function_entry(
self, func_name: str, *args: Any, **kwargs: Any
) -> None:
if not self.enabled:
return
line = format_debug_log(
f"FunctionEntry: {func_name}",
level="DEBUG",
args=args,
kwargs=kwargs,
)
_debug_module_logger.debug(line)
def log_function_exit(
self, func_name: str, retval: Any, elapsed: float
) -> None:
if not self.enabled:
return
line = format_debug_log(
f"FunctionExit: {func_name}",
level="DEBUG",
elapsed_seconds=elapsed,
return_value=retval,
)
_debug_module_logger.debug(line)
def log_variable(self, name: str, value: Any) -> None:
if not self.enabled:
return
@@ -154,6 +180,15 @@ class DebugLogger:
)
_debug_module_logger.debug(line)
def log_call_stack(self) -> None:
if not self.enabled:
return
stack = traceback.format_stack()
line = format_debug_log(
"CallStack", level="DEBUG", stack="".join(stack)
)
_debug_module_logger.debug(line)
def log_exception(
self, exc: BaseException, context: Optional[Dict[str, Any]] = None
) -> None:
@@ -186,4 +221,8 @@ class DebugLogger:
_perf.get_elapsed(name)
__all__ = ["ErrorLogger", "DebugLogger"]
def _get_debug_logger() -> DebugLogger:
return DebugLogger(True)
__all__ = ["ErrorLogger", "DebugLogger", "_get_debug_logger"]
+74
View File
@@ -127,6 +127,7 @@ def format_action_log(action: str, details: Optional[str] = None, **fields: Any)
def format_error_log(
message: str, level: str = "ERROR", tag: Optional[str] = None, **fields: Any
) -> str:
"""格式化错误日志"""
parts = []
if tag:
parts.append(f"[{tag}]")
@@ -138,7 +139,39 @@ def format_error_log(
return " ".join(parts)
def format_call_stack(stack: Optional[List[str]] = None) -> str:
if not stack:
return ""
return "\n".join(stack)
def format_parameters(params: Dict[str, Any]) -> str:
if not params:
return ""
return " ".join(f"{k}={v}" for k, v in params.items())
def format_variables(vars: Dict[str, Any]) -> str:
if not vars:
return ""
return " ".join(f"{k}={v}" for k, v in vars.items())
def format_exception(exc: BaseException) -> str:
import traceback
return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
def add_separators(text: str, label: Optional[str] = None) -> str:
if not label:
label = ""
sep = "=" * 80
return f"{sep}\n {label} \n{sep}\n{text}\n{sep}"
def add_colors(text: str, color: str = "green") -> str:
# 简易颜色支持,只有在控制台启用时有效
colors = {
"red": "\033[31m",
"green": "\033[32m",
@@ -152,19 +185,48 @@ def add_colors(text: str, color: str = "green") -> str:
def beautify_log_output(line: str) -> str:
"""
美化日志输出,为GUI显示优化格式。
对日志行进行美化处理,包括:
- 提取关键信息
- 简化冗余部分
- 突出重要信息
"""
if not line or not line.strip():
return line
# 对于GUI显示,我们保持相对简洁但有用的格式
# 移除过长的堆栈跟踪,但保留关键错误信息
if len(line) > 500:
# 如果行太长,进行截断
parts = line.split()
if len(parts) > 10:
# 保留前10个部分和最后的部分
shortened = " ".join(parts[:8]) + " ... " + " ".join(parts[-2:])
return shortened
# 突出显示重要关键字
important_keywords = ["ERROR", "CRITICAL", "FAILED", "EXCEPTION"]
for keyword in important_keywords:
if keyword in line.upper():
# 在GUI中我们不添加颜色代码,因为GUI使用标签系统
# 这里只是为了标识重要行
break
return line
def colorize_log_line(line: str) -> str:
"""
为日志行添加颜色代码(用于控制台输出)。
基于日志级别和内容为日志行添加ANSI颜色代码。
"""
if not line:
return line
# 检查日志级别并应用相应颜色
if "[DEBUG]" in line:
return add_colors(line, "blue")
elif "[INFO]" in line:
@@ -174,7 +236,14 @@ def colorize_log_line(line: str) -> str:
elif "[ERROR]" in line:
return add_colors(line, "red")
elif "[CRITICAL]" in line:
return add_colors(line, "red") # 红色加粗可以通过多次应用实现
# 检查特殊内容
if "elapsed_seconds=" in line or "耗时" in line:
return add_colors(line, "green")
if "EXCEPTION" in line.upper():
return add_colors(line, "red")
return line
@@ -182,6 +251,11 @@ __all__ = [
"format_debug_log",
"format_action_log",
"format_error_log",
"format_call_stack",
"format_parameters",
"format_variables",
"format_exception",
"add_separators",
"add_colors",
"beautify_log_output",
"colorize_log_line",
+11
View File
@@ -33,6 +33,17 @@ class PerformanceTracker:
return 0.0
return time.perf_counter() - start
def track_function(self, func: Callable) -> Callable:
def wrapper(*args, **kwargs):
name = func.__qualname__
timer = self.start_timer(name)
try:
result = func(*args, **kwargs)
return result
finally:
self.end_timer(timer)
return wrapper
def track_step(self, name: str) -> Callable:
def decorator(func: Callable) -> Callable:
def inner(*args, **kwargs):
+174 -1
View File
@@ -22,7 +22,7 @@ import logging
import threading
import inspect
import traceback
from typing import Optional, Dict, Any
from typing import Optional, Dict, Any, Callable
from functools import wraps
from contextlib import contextmanager
@@ -356,6 +356,174 @@ def get_unified_logger(name: Optional[str] = None) -> logging.Logger:
return logger
@contextmanager
def trace_context(trace_id: Optional[str] = None, **mdc_context):
"""上下文管理器:为代码块设置traceId和MDC上下文"""
old_trace_id = MDC.get_trace_id()
old_mdc = MDC.get_all()
# 设置新的traceId
if trace_id is None:
trace_id = MDC.set_trace_id()
else:
MDC.set_trace_id(trace_id)
# 设置其他MDC上下文
for key, value in mdc_context.items():
MDC.put(key, value)
try:
yield trace_id
finally:
# 恢复旧的MDC
MDC.clear()
if old_trace_id:
MDC.set_trace_id(old_trace_id)
for key, value in old_mdc.items():
MDC.put(key, value)
def log_method_entry_exit(
logger: Optional[logging.Logger] = None,
log_args: bool = True,
log_result: bool = False,
log_duration: bool = True,
min_duration: float = 0.0,
):
"""装饰器:自动记录方法入口、出口、参数、返回值、耗时"""
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
if logger is None:
_logger = get_unified_logger()
else:
_logger = logger
func_name = f"{func.__module__}.{func.__name__}"
start_time = time.time()
# 记录方法入口
if log_args:
args_str = ", ".join([str(arg)[:100] for arg in args[:3]])
kwargs_str = ", ".join(
[f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]]
)
call_info = (
f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
)
if len(args) > 3 or len(kwargs) > 3:
call_info += "..."
_logger.info(f"[方法入口] {call_info}")
# 执行方法
try:
result = func(*args, **kwargs)
elapsed = time.time() - start_time
# 记录方法出口
exit_msg = f"[方法出口] {func_name}"
if log_duration and elapsed >= min_duration:
exit_msg += f" 耗时: {elapsed:.3f}秒"
if log_result:
result_str = str(result)[:200]
exit_msg += f" 返回值: {result_str}"
_logger.info(exit_msg)
return result
except Exception as e:
elapsed = time.time() - start_time
_logger.error(
f"[方法异常] {func_name} 发生异常: {type(e).__name__}: {str(e)} "
f"耗时: {elapsed:.3f}秒",
exc_info=True,
)
raise
return wrapper
return decorator
def log_external_call(
target: str,
request_params: Optional[Dict[str, Any]] = None,
response_result: Optional[Any] = None,
success: bool = True,
duration: Optional[float] = None,
logger: Optional[logging.Logger] = None,
):
"""记录外部调用(API调用、数据库查询等)"""
if logger is None:
logger = get_unified_logger()
# 脱敏请求参数
if request_params:
request_params = SensitiveDataMasker.mask_dict(request_params)
msg_parts = [f"[外部调用] {target}"]
if request_params:
params_str = ", ".join(
[f"{k}={v}" for k, v in list(request_params.items())[:5]]
)
if len(request_params) > 5:
params_str += "..."
msg_parts.append(f"请求参数: {params_str}")
if response_result is not None:
result_str = str(response_result)[:200]
msg_parts.append(f"响应结果: {result_str}")
if duration is not None:
msg_parts.append(f"耗时: {duration:.3f}秒")
msg_parts.append(f"状态: {'成功' if success else '失败'}")
level = logging.INFO if success else logging.ERROR
logger.log(level, " | ".join(msg_parts))
def log_decision_point(
decision: str,
condition: Optional[str] = None,
result: Any = None,
logger: Optional[logging.Logger] = None,
):
"""记录关键决策点(分支判断、条件判断等)"""
if logger is None:
logger = get_unified_logger()
msg_parts = [f"[决策点] {decision}"]
if condition:
msg_parts.append(f"条件: {condition}")
if result is not None:
result_str = str(result)[:100]
msg_parts.append(f"结果: {result_str}")
logger.info(" | ".join(msg_parts))
def log_state_change(
old_state: Any,
new_state: Any,
reason: Optional[str] = None,
logger: Optional[logging.Logger] = None,
):
"""记录状态变化"""
if logger is None:
logger = get_unified_logger()
msg_parts = [f"[状态变化] {old_state} -> {new_state}"]
if reason:
msg_parts.append(f"原因: {reason}")
logger.info(" | ".join(msg_parts))
# 导出主要接口
__all__ = [
@@ -363,4 +531,9 @@ __all__ = [
"SensitiveDataMasker",
"UnifiedFormatter",
"get_unified_logger",
"trace_context",
"log_method_entry_exit",
"log_external_call",
"log_decision_point",
"log_state_change",
]
+6 -12
View File
@@ -36,12 +36,9 @@ def check_coupon_popup(analyser) -> bool:
pic_path = path_config.get_screenshot_path()
pic = Image.open(pic_path)
try:
pic.load() # Force load to catch truncated files early
pic_rgb = pic.convert("RGB")
finally:
pic.close()
template_matched = bool(douyin_pixel.detect_coupon_popup_background(pic_rgb))
pic.load() # Force load to catch truncated files early
pic = pic.convert("RGB")
template_matched = bool(douyin_pixel.detect_coupon_popup_background(pic))
except (OSError, IOError, SyntaxError) as e:
# Handle truncated image files
try:
@@ -210,11 +207,8 @@ def check_shopping_redpacket_popup(analyser) -> bool:
pic_path = path_config.get_screenshot_path()
pic = Image.open(pic_path)
try:
pic.load() # Force load to catch truncated files early
pic_rgb = pic.convert("RGB")
finally:
pic.close()
pic.load() # Force load to catch truncated files early
pic = pic.convert("RGB")
try:
redpacket_threshold = float(
getattr(analyser, "shopping_redpacket_red_ratio_threshold", None)
@@ -224,7 +218,7 @@ def check_shopping_redpacket_popup(analyser) -> bool:
redpacket_threshold = 0.15
has_popup_pixel = bool(
douyin_pixel.detect_redpacket_popup_background(
pic_rgb,
pic,
red_ratio_threshold=redpacket_threshold,
analyser=analyser,
)
+2 -10
View File
@@ -133,11 +133,7 @@ def deal_robot_pic_change_color(analyser) -> None:
path = path_config.get_robot_verify_pic_path(save_subdir=True)
pic = path
_raw = Image.open(pic)
try:
img = _raw.convert("RGB")
finally:
_raw.close()
img = Image.open(pic).convert("RGB")
width, height = img.size
for x in range(5, width - 40):
for y in range(20, height - 30):
@@ -160,11 +156,7 @@ def check_robot_pic_distance(analyser) -> int:
if not pic_path or not os.path.exists(pic_path):
raise FileNotFoundError(f"机器人验证图片不存在: {pic_path}")
_raw = Image.open(pic_path)
try:
img = _raw.convert("RGB")
finally:
_raw.close()
img = Image.open(pic_path).convert("RGB")
width, height = img.size
first_x = 0
+152 -25
View File
@@ -299,24 +299,73 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
if now - last_desktop_check_ts >= desktop_check_interval:
last_desktop_check_ts = now
try:
from douyin.core import recovery as _recovery
top_pkg = (
analyser.operation.get_top_package(analyser.device_id)
or ""
)
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
_yanghao_log(
analyser,
f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}",
is_douyin_pkg = top_pkg and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
if top_pkg and not is_douyin_pkg:
_yanghao_log(analyser,
f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}"
)
try:
_recovery.recover_to_douyin(
analyser,
log=lambda msg: _yanghao_log(
analyser, f"[养号] 自救: {msg}"
),
desktop_x = int(
getattr(analyser, "desktop_icon_x", 153) or 153
)
desktop_y = int(
getattr(analyser, "desktop_icon_y", 260) or 260
)
analyser.operation.click(
analyser.device_id, desktop_x, desktop_y
)
analyser.operation.delay(2)
fallback_x = int(
getattr(
analyser, "yanghao_fallback_live_x", 540
)
or 540
)
fallback_y = int(
getattr(
analyser, "yanghao_fallback_live_y", 2000
)
or 2000
)
analyser.operation.click(
analyser.device_id, fallback_x, fallback_y
)
analyser.operation.delay(1.5)
enter_x = int(
getattr(
analyser,
"yanghao_fallback_enter_live_x",
540,
)
or 540
)
enter_y = int(
getattr(
analyser,
"yanghao_fallback_enter_live_y",
1200,
)
or 1200
)
analyser.operation.click(
analyser.device_id, enter_x, enter_y
)
analyser.operation.delay(0.6)
analyser.operation.click(
analyser.device_id, enter_x, enter_y
)
analyser.operation.delay(2.0)
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
@@ -436,22 +485,58 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
def _yanghao_check_and_recover_from_desktop(analyser) -> bool:
"""养号模式下的桌面检测和自救恢复(提前定义以供循环使用)。"""
try:
from douyin.core import recovery as _recovery
# 获取前台包名
top_pkg = analyser.operation.get_top_package(analyser.device_id) or ""
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
# 检查是否在抖音前台
is_douyin_pkg = top_pkg and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
if top_pkg and not is_douyin_pkg:
_yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}")
# 执行自救操作
try:
_recovery.recover_to_douyin(
analyser,
log=lambda msg: _yanghao_log(analyser, f"[养号] 自救: {msg}"),
# 点击桌面图标
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
analyser.operation.click(analyser.device_id, desktop_x, desktop_y)
analyser.operation.delay(2)
# 点击直播按钮(备用坐标)
fallback_x = int(
getattr(analyser, "yanghao_fallback_live_x", 540) or 540
)
fallback_y = int(
getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000
)
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
analyser.operation.delay(1.5)
# 点击进入直播间(备用坐标)
enter_x = int(
getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540
)
enter_y = int(
getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200
)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(0.6)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(2.0)
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
return True
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
return False
return False
else:
return False
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
return False
@@ -529,22 +614,64 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
def _yanghao_check_and_recover_from_desktop(analyser) -> bool:
"""养号模式下的桌面检测和自救恢复"""
try:
from douyin.core import recovery as _recovery
# 获取前台包名
top_pkg = analyser.operation.get_top_package(analyser.device_id) or ""
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
# 检查是否在抖音前台
is_douyin_pkg = top_pkg and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
if top_pkg and not is_douyin_pkg:
_yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}")
# 执行自救操作
try:
_recovery.recover_to_douyin(
analyser,
log=lambda msg: _yanghao_log(analyser, f"[养号] 自救: {msg}"),
# 点击桌面图标
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
analyser.operation.click(
analyser.device_id, desktop_x, desktop_y
)
analyser.operation.delay(2)
# 点击直播按钮(备用坐标)
fallback_x = int(
getattr(analyser, "yanghao_fallback_live_x", 540) or 540
)
fallback_y = int(
getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000
)
analyser.operation.click(
analyser.device_id, fallback_x, fallback_y
)
analyser.operation.delay(1.5)
# 点击进入直播间(备用坐标)
enter_x = int(
getattr(analyser, "yanghao_fallback_enter_live_x", 540)
or 540
)
enter_y = int(
getattr(analyser, "yanghao_fallback_enter_live_y", 1200)
or 1200
)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(0.6)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(2.0)
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
return True
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
return False
return False
else:
return False
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
return False
@@ -209,12 +209,9 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
from douyin.detection import douyin_pixel
try:
button_result = douyin_pixel.detect_attend_button_red_area(
pic_rgb, return_info=True, analyser=analyser
)
finally:
pic_rgb.close()
button_result = douyin_pixel.detect_attend_button_red_area(
pic_rgb, return_info=True, analyser=analyser
)
if isinstance(button_result, tuple):
has_button, button_info = button_result
else:
@@ -307,12 +304,9 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
)
screenshot_path2 = path_config.get_screenshot_path()
pic_rgb2 = Image.open(screenshot_path2) # type: ignore[attr-defined]
try:
button_result2 = douyin_pixel.detect_attend_button_red_area(
pic_rgb2, return_info=True, analyser=analyser
)
finally:
pic_rgb2.close()
button_result2 = douyin_pixel.detect_attend_button_red_area(
pic_rgb2, return_info=True, analyser=analyser
)
if isinstance(button_result2, tuple):
has_button2, button_info2 = button_result2
else:
@@ -380,8 +380,6 @@ def validate_back_to_reservation(
except Exception:
pass
current_title = ""
current_title_raw = ""
if expected_title:
try:
# 回退校验时强制重新识别直播间标题,避免复用切换前的旧截图
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,552 +0,0 @@
"""reservation_logic.attend_window_verify - 回退后的校验与二次回退
从 process_reservation_attend_window 抽出的"if ok:"分支(540 行):
- 回退操作成功后等待直播间加载
- 调用 douyin_reservation_verify.validate_back_to_reservation 校验
- 校验失败 → 用映射表重定位 + 二次回退
- 校验通过 / 二次回退结果 / 校验异常 三种返回路径
入口:handle_back_verify(...)
返回值:
- True : 校验失败但二次回退成功,主函数应 `return True`
- False : 校验失败且二次回退也失败,主函数应 `return False`
- None : 校验通过 / 校验禁用 / 校验异常,主函数继续设锁定期
"""
from __future__ import annotations
import time
from typing import Any, Callable, Dict, List, Optional
from ._common import (
ReservationItem,
_RESERVATION_ERROR_UTILS_AVAILABLE,
format_reservation_context,
log_reservation_error,
)
def handle_back_verify(
analyser: Any,
target: ReservationItem,
reservations: List[ReservationItem],
room_pos: int,
ft: float,
poll_before: float,
reservation_focus_until_ts_ref: List[float],
reservation_after_action_pending_ref: List[bool],
seek_reservation_room_callback: Callable[[ReservationItem], bool],
write_state_callback: Callable[[], None],
) -> Optional[bool]:
"""处理回退后的校验与可能的二次回退。
Returns:
True/False → 主函数立即返回该值
None → 校验通过 / 禁用 / 异常,继续设置锁定期
"""
target_room_title = str(target.get("room_title") or "").strip()
target_room_title_raw = str(target.get("room_title_raw") or "").strip()
target_content = str(target.get("content") or "").strip()
target_value = float(target.get("prize_value_yuan") or 0.0)
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:回退操作成功,准备进行回退校验",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=target_room_title[:50] if target_room_title else "",
target_room_title_raw=(
target_room_title_raw[:50] if target_room_title_raw else ""
),
target_content=target_content[:50] if target_content else "",
target_value_yuan=target_value,
current_room_pos=int(room_pos),
reservation_back_verify_enabled=bool(
getattr(analyser, "reservation_back_verify_enabled", True)
),
level="DEBUG",
)
except Exception:
pass
try:
verify_enabled = bool(
getattr(analyser, "reservation_back_verify_enabled", True)
)
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:检查回退校验开关",
reservation_back_verify_enabled=verify_enabled,
level="DEBUG",
)
except Exception:
pass
if not verify_enabled:
try:
analyser._log_kv("预约", "[预约] 回退校验已禁用,跳过校验")
except Exception:
pass
return None
# 等待直播间加载完成
try:
verify_wait_seconds = float(
getattr(analyser, "reservation_back_verify_wait_seconds", 5.0) or 5.0
)
if verify_wait_seconds < 0.1:
verify_wait_seconds = 0.1
if verify_wait_seconds > 10.0:
verify_wait_seconds = 10.0
except Exception:
verify_wait_seconds = 3.0
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:回退后等待直播间加载完成(开始等待)",
verify_wait_seconds=verify_wait_seconds,
level="INFO",
)
except Exception:
pass
wait_start_ts = time.time()
try:
try:
analyser.operation.delay(verify_wait_seconds)
except Exception:
time.sleep(verify_wait_seconds)
finally:
waited = time.time() - wait_start_ts
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:回退等待完成",
expected_wait_seconds=verify_wait_seconds,
waited_seconds=round(waited, 3),
level="INFO",
)
except Exception:
pass
try:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:开始调用回退校验函数",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
level="DEBUG",
)
except Exception:
pass
import douyin.reservation.douyin_reservation_verify as douyin_reservation_verify
verify_ok, verify_detail = (
douyin_reservation_verify.validate_back_to_reservation(
analyser=analyser,
item=target,
quick=False,
max_checks=3,
)
)
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:回退校验函数返回",
verify_ok=verify_ok,
verify_detail_exists=verify_detail is not None,
level="DEBUG",
)
except Exception:
pass
if verify_ok:
try:
analyser._log_kv(
"预约",
f"[预约] 回退校验通过:已成功回退到目标直播间并验证福袋详情 - 目标位置:{int(target.get('pos_seen', 0))}, 直播间:'{target_room_title[:30] if target_room_title else ''}'",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
)
except Exception:
pass
return None # 校验通过,主函数继续设锁定期
# 校验失败 → 走二次回退逻辑
return _handle_verify_failure(
analyser, target, reservations,
target_room_title, target_room_title_raw,
ft, poll_before,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
seek_reservation_room_callback,
write_state_callback,
verify_detail,
)
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] 回退校验执行时发生异常,继续执行",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 校验异常不影响主流程,继续执行
return None
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] 检查回退校验开关时发生异常,继续执行",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return None
def _handle_verify_failure(
analyser: Any,
target: ReservationItem,
reservations: List[ReservationItem],
target_room_title: str,
target_room_title_raw: str,
ft: float,
poll_before: float,
reservation_focus_until_ts_ref: List[float],
reservation_after_action_pending_ref: List[bool],
seek_reservation_room_callback: Callable[[ReservationItem], bool],
write_state_callback: Callable[[], None],
verify_detail: Any,
) -> bool:
"""校验失败 → 用映射表重定位 + 二次回退。返回 True/False 给 caller。"""
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
Exception("回退校验失败:回退操作成功但校验未通过"),
format_reservation_context(
item=target,
reservations=reservations,
verify_detail=verify_detail,
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
),
level="WARNING",
stage="回退校验",
)
else:
try:
analyser._log_kv(
"预约",
"[预约] 回退校验失败:回退操作成功但校验未通过(不再自动回退重试,避免循环卡死)",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
)
except Exception:
pass
try:
try:
analyser._log_kv(
"预约",
"[预约] 回退校验失败:尝试根据映射表回退到对应直播间并跳过设置锁定期",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
)
except Exception:
pass
updated_target, mapped_target_pos, mapped_current_pos, room_pos_before_map = (
_remap_target_via_room_titles(
analyser, target, target_room_title, target_room_title_raw
)
)
ok2 = _retry_seek_with_mapped_diff(
analyser, updated_target,
mapped_target_pos, mapped_current_pos, room_pos_before_map,
seek_reservation_room_callback,
)
if ok2:
# 第二次回退成功,设置锁定期并标记待处理
focus_until_new = ft + max(0.0, poll_before)
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = focus_until_new
else:
reservation_focus_until_ts_ref.append(focus_until_new)
if reservation_after_action_pending_ref:
reservation_after_action_pending_ref[0] = True
else:
reservation_after_action_pending_ref.append(True)
try:
analyser._log_kv(
"预约",
"[预约] 第二次回退成功:已根据映射表回退到目标直播间",
target_pos=int(updated_target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
focus_until=int(focus_until_new),
)
except Exception:
pass
try:
write_state_callback()
except Exception:
pass
return True
else:
# 第二次回退也失败,清理锁定相关标志
try:
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = 0.0
except Exception:
pass
try:
if reservation_after_action_pending_ref:
reservation_after_action_pending_ref[0] = False
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] 第二次回退失败:无法根据映射表定位到目标直播间",
target_pos=int(updated_target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
)
except Exception:
pass
try:
write_state_callback()
except Exception:
pass
except Exception:
pass
# 不设置锁定期,回退校验失败视作本次未成功回退,返回 False 以便上层继续处理
return False
def _remap_target_via_room_titles(
analyser: Any,
target: ReservationItem,
target_room_title: str,
target_room_title_raw: str,
):
"""通过映射表重新查找 target 与当前直播间位置。
Returns: (updated_target, mapped_target_pos, mapped_current_pos, room_pos_before_map)
"""
updated_target: Dict[str, Any] = dict(target)
try:
room_pos_before_map = int(getattr(analyser, "room_pos", 0) or 0)
except Exception:
room_pos_before_map = 0
mapped_target_pos: Optional[int] = None
mapped_current_pos: Optional[int] = None
try:
from douyin.reservation.douyin_reservation_handler import ReservationHandler
mapped_target_pos = ReservationHandler.find_room_pos_by_title(
analyser, target_room_title, target_room_title_raw,
)
if mapped_target_pos is not None and mapped_target_pos > 0:
updated_target["pos_seen"] = int(mapped_target_pos)
try:
analyser._log_kv(
"预约",
"[预约] 重新查找目标直播间位置成功",
old_pos=int(target.get("pos_seen", 0)),
new_pos=int(mapped_target_pos),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
)
except Exception:
pass
else:
try:
analyser._log_kv(
"预约",
"[预约] 重新查找目标直播间位置失败,使用原有位置",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50] if target_room_title else ""
),
)
except Exception:
pass
# 识别当前直播间标题(优先缓存,必要时重新识别)
current_room_title = str(
getattr(analyser, "current_room_title", "") or ""
).strip()
current_room_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
).strip()
if not current_room_title and not current_room_title_raw:
try:
from douyin.fudai import douyin_fudai_detail
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
(
current_room_title,
current_room_title_raw,
) = douyin_fudai_detail.read_live_room_title_core(
analyser, y_pianyi_val
)
try:
analyser.current_room_title = current_room_title
analyser.current_room_title_raw = current_room_title_raw
except Exception:
pass
except Exception:
current_room_title = ""
current_room_title_raw = ""
if current_room_title or current_room_title_raw:
mapped_current_pos = ReservationHandler.find_room_pos_by_title(
analyser, current_room_title, current_room_title_raw,
)
if mapped_current_pos is not None and mapped_current_pos > 0:
try:
old_room_pos = int(getattr(analyser, "room_pos", 0) or 0)
except Exception:
old_room_pos = 0
try:
analyser.room_pos = int(mapped_current_pos)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] 通过映射表识别当前直播间位置",
old_pos=int(old_room_pos),
new_pos=int(mapped_current_pos),
current_room_title=(
current_room_title[:50] if current_room_title else ""
),
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] 重新查找目标/当前直播间位置时出错",
error=str(e),
target_pos=int(target.get("pos_seen", 0)),
)
except Exception:
pass
return updated_target, mapped_target_pos, mapped_current_pos, room_pos_before_map
def _retry_seek_with_mapped_diff(
analyser: Any,
updated_target: Dict[str, Any],
mapped_target_pos: Optional[int],
mapped_current_pos: Optional[int],
room_pos_before_map: int,
seek_reservation_room_callback: Callable[[ReservationItem], bool],
) -> bool:
"""根据映射表差值(mapped_target - mapped_current)执行二次回退。
特殊路径:mapped_pos_diff==0 时若 room_pos_before_map 与 mapped_target_pos 不一致,
设置 _seek_direction_hint 后仍重试;否则跳过二次回退。
"""
ok2 = False
should_retry_seek = True
mapped_pos_diff: Optional[int] = None
if mapped_current_pos is not None and mapped_target_pos is not None:
try:
mapped_pos_diff = int(mapped_target_pos) - int(mapped_current_pos)
except Exception:
mapped_pos_diff = None
try:
analyser._log_kv(
"预约",
"[预约] 映射表差值回退准备",
mapped_current_pos=int(mapped_current_pos),
mapped_target_pos=int(mapped_target_pos),
mapped_pos_diff=(
int(mapped_pos_diff) if mapped_pos_diff is not None else None
),
)
except Exception:
pass
if mapped_pos_diff == 0:
# 若映射表显示已在目标位置但校验失败,尝试根据回退前位置进行一次纠偏回退
if (
mapped_target_pos is not None
and room_pos_before_map != mapped_target_pos
):
try:
if room_pos_before_map > int(mapped_target_pos):
updated_target["_seek_direction_hint"] = "down"
elif room_pos_before_map < int(mapped_target_pos):
updated_target["_seek_direction_hint"] = "up"
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] 映射表显示已在目标位置但校验失败,启用纠偏回退",
mapped_current_pos=int(mapped_current_pos),
mapped_target_pos=int(mapped_target_pos),
room_pos_before_map=int(room_pos_before_map),
direction_hint=updated_target.get("_seek_direction_hint", ""),
)
except Exception:
pass
else:
should_retry_seek = False
try:
analyser._log_kv(
"预约",
"[预约] 映射表显示已在目标位置,但校验失败,跳过二次回退",
mapped_current_pos=int(mapped_current_pos),
mapped_target_pos=int(mapped_target_pos),
)
except Exception:
pass
if should_retry_seek:
try:
if seek_reservation_room_callback:
ok2 = bool(seek_reservation_room_callback(updated_target))
except Exception:
ok2 = False
return ok2
+95 -248
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
@@ -333,25 +237,53 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
step0_elapsed = (time.time() - step_start) * 1000
_log("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed)
# 不在直播间时:跑 OCR 找推荐页/关注列表/直播列表/购物红包
from douyin.stage.douyin_stage_handler_pkg.ocr_detection import (
detect_pages_via_ocr,
)
_ocr_result = detect_pages_via_ocr(
analyser=analyser,
in_live_room=in_live_room,
pixel_state=pixel_state,
pixel_details=pixel_details,
diag_start=diag_start,
max_diag_time=max_diag_time,
max_step_time=max_step_time,
enable_ocr_mode1=enable_ocr_mode1,
log=_log,
log_summary=_log_summary,
log_separator=_log_separator,
)
if _ocr_result is not None:
return _ocr_result
# ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)==========
if not in_live_room:
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
# 购物红包像素命中:不在直播间也必须进行OCR复查
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标签栏,整合在一起检测)
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,
)
if matched:
return stage, reason
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
_log_summary(
"阶段诊断完成",
阶段="IN_LIVE_ROOM",
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
# ========== 在直播间:继续执行像素检测结果处理 ==========
_log_separator("在直播间,继续执行像素检测结果处理")
@@ -362,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()
@@ -633,12 +483,9 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
_raw = Image.open(pic_path)
try:
_raw.load()
pic_rgb = _raw.convert("RGB")
finally:
_raw.close()
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
width, height = pic_rgb.size
rx = int(
@@ -707,7 +554,7 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
# 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(
getattr(analyser, "enable_ocr_mode1", True)
getattr(analyser, "enable_ocr_mode1", False)
)
if enable_ocr_mode1 and (
not ocr_text
@@ -783,22 +630,23 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed)
# 所有像素检测完成,未命中任何特定阶段:检查是否有可疑弹窗背景需要 OCR 确认
from douyin.stage.douyin_stage_handler_pkg.popup_verification import (
verify_popup_via_ocr,
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
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,
)
_popup_result = verify_popup_via_ocr(
analyser=analyser,
pixel_state=pixel_state,
diag_start=diag_start,
max_diag_time=max_diag_time,
max_step_time=max_step_time,
enable_ocr_mode1=enable_ocr_mode1,
log=_log,
log_summary=_log_summary,
)
if _popup_result is not None:
return _popup_result
if matched:
return stage, reason
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
if in_live_room:
@@ -826,4 +674,3 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"
@@ -1,581 +0,0 @@
"""douyin_stage_handler_pkg.ocr_detection - 不在直播间时的 OCR 检测
从 diagnose_stage_from_current_screen 抽出 L336-774 的整段 "if not in_live_room"
分支(438 行):
- 步骤 2.5:购物红包 OCR 复查(像素命中红包背景时再用 OCR 二次确认)
- 步骤 3:OCR 推荐页/关注列表/直播列表标签栏
入口:detect_pages_via_ocr(...) -> Optional[Tuple[str, str]]
返回值:
- ("SHOPPING_REDPACKET_POPUP", reason) | ("RECOMMEND_PAGE", reason)
| ("FOLLOW_LIST", reason) | ("LIVE_LIST", reason) | ("IN_LIVE_ROOM", reason)
→ caller 立即 return("IN_LIVE_ROOM" 是兜底默认值,与原代码保持一致)
- None
→ in_live_room=True,caller 应继续走"在直播间"分支
"""
from __future__ import annotations
import time
from typing import Any, Callable, Optional, Tuple
from douyin.fudai.core.coords import (
FOLLOW_TAB,
LIVE_LIST_TAB,
RECOMMEND_TAB,
SHOPPING_REDPACKET_AREA,
)
def detect_pages_via_ocr(
analyser: Any,
in_live_room: bool,
pixel_state: dict,
pixel_details: dict,
diag_start: float,
max_diag_time: float,
max_step_time: float,
enable_ocr_mode1: bool,
log: Callable[..., None],
log_summary: Callable[..., None],
log_separator: Callable[..., None],
) -> Optional[Tuple[str, str]]:
"""如果不在直播间,跑 OCR 找推荐页 / 关注列表 / 直播列表 / 购物红包。
返回 ("阶段", 原因) 让 caller 立即 return;返回 None 表示 in_live_room=True,继续后续逻辑。
"""
if in_live_room:
return None
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
except Exception:
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
return str(picname)
log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
# 购物红包 OCR 复查(不在直播间也必须执行)
redpacket_result = _check_redpacket_ocr_when_not_in_live_room(
analyser,
pixel_state,
pixel_details,
diag_start,
max_step_time,
enable_ocr_mode1,
preprocess_for_ocr,
log,
log_summary,
)
if redpacket_result is not None:
return redpacket_result
# 步骤 3:OCR 推荐页/关注列表/直播列表标签栏
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
log(
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
)
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:
follow_result = _confirm_follow_list(
analyser,
t_recommend,
step_start,
diag_start,
max_step_time,
enable_ocr_mode1,
preprocess_for_ocr,
log,
log_summary,
log_separator,
)
if follow_result is not None:
return follow_result
# follow_result 为 None:关注列表确认失败,但继续走直播列表分支
t_follow = getattr(analyser, "_last_follow_list_title_text", "") or ""
# 命中"正在直播"或"直播"标签 → 直播列表精确确认
if "正在直播" in t_recommend or (
"直播" in t_recommend
and "推荐" not in t_recommend
and "关注" not in t_recommend
):
list_result = _confirm_live_list(
analyser,
step_start,
diag_start,
max_step_time,
enable_ocr_mode1,
preprocess_for_ocr,
log,
log_summary,
log_separator,
)
if list_result is not None:
return list_result
# 记录诊断时看到的"关注页标题"
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(),
)
step3_elapsed = (time.time() - step_start) * 1000
log("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
# 如果不在直播间且 OCR 也未识别到特定页面,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
log_summary(
"阶段诊断完成",
阶段="IN_LIVE_ROOM",
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
总耗时毫秒=total_elapsed,
)
log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
def _check_redpacket_ocr_when_not_in_live_room(
analyser: Any,
pixel_state: dict,
pixel_details: dict,
diag_start: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable,
log: Callable[..., None],
log_summary: Callable[..., None],
) -> Optional[Tuple[str, str]]:
"""步骤 2.5:购物红包像素命中时的 OCR 二次确认(不在直播间分支专用)。"""
if not pixel_state.get("has_redpacket_bg", False):
return None
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
redpacket_text = ""
ocr_confidence_info = None
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)
>= getattr(analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35)
)
if has_keyword_match or has_high_confidence:
redpacket_verified = True
log(
"步骤2.5[购物红包OCR复查]-命中",
关键词匹配=has_keyword_match,
高置信度匹配=has_high_confidence,
阈值=getattr(analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35),
)
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)
return None
def _confirm_follow_list(
analyser: Any,
t_recommend: str,
step_start: float,
diag_start: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable,
log: Callable[..., None],
log_summary: Callable[..., None],
log_separator: Callable[..., None],
) -> Optional[Tuple[str, str]]:
"""精确截图 + OCR 确认是否真的是关注列表。"""
log(
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
精确区域="(658,147)-(765,194)",
)
step_start_follow = time.time()
t_follow = ""
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)
# 关注列表确认失败:把 t_follow 存到 analyser,后续可读
try:
analyser._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
analyser._last_follow_list_title_text = ""
return None
def _confirm_live_list(
analyser: Any,
step_start: float,
diag_start: float,
max_step_time: float,
enable_ocr_mode1: bool,
preprocess_for_ocr: Callable,
log: Callable[..., None],
log_summary: Callable[..., None],
log_separator: Callable[..., None],
) -> Optional[Tuple[str, str]]:
"""精确截图 + OCR 确认是否真的是直播列表。"""
log(
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
精确区域="(650,145)-(800,195)",
)
step_start_list = time.time()
t_list = ""
try:
ocr_start = time.time()
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()
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)
return None
@@ -1,211 +0,0 @@
"""douyin_stage_handler_pkg.popup_verification - 弹窗 OCR 二次确认
从 diagnose_stage_from_current_screen 抽出 L1203-1358 的"未命中任何阶段
但像素检测到弹窗背景"段(156 行):当 has_coupon_bg / has_redpacket_bg
为 True 时,再用 OCR 二次确认是否真的是优惠券/购物红包弹窗(避免直播间
背景色误判)。
入口:verify_popup_via_ocr(...) -> Optional[Tuple[str, str]]
返回值:
- ("COUPON_POPUP", reason) 或 ("SHOPPING_REDPACKET_POPUP", reason)
→ caller 应立即 return 该元组
- None
→ 没有可疑弹窗 / 像素未检测到 / OCR 确认失败,caller 继续后续逻辑
"""
from __future__ import annotations
import time
from typing import Any, Callable, Optional, Tuple
from douyin.fudai.core.coords import (
COUPON_PARTICIPATE_BUTTON_ALT,
SHOPPING_REDPACKET_AREA,
)
def verify_popup_via_ocr(
analyser: Any,
pixel_state: dict,
diag_start: float,
max_diag_time: float,
max_step_time: float,
enable_ocr_mode1: bool,
log: Callable[..., None],
log_summary: Callable[..., None],
) -> Optional[Tuple[str, str]]:
"""像素层有可疑弹窗背景时用 OCR 再确认一次。
Args:
analyser: 调用 cut_pic / operation.analyse_pic_word
pixel_state: 像素检测结果 dict(含 has_coupon_bg / has_redpacket_bg)
diag_start: 整个阶段诊断起始时间(用于汇总耗时日志)
max_diag_time: 诊断总超时(秒)
max_step_time: 单步超时(秒)
enable_ocr_mode1: 是否额外并行跑模式 1 OCR
log / log_summary: 原 diagnose 内部的两个嵌套日志闭包,按原行为保留
Returns:
("COUPON_POPUP", reason) / ("SHOPPING_REDPACKET_POPUP", reason)
/ None(不需要拦截)
"""
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 None
try:
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
except Exception:
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
return str(picname)
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_text = ""
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()
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确认后未匹配,判定为直播间背景颜色",
)
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
log("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
return None
+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
+95
View File
@@ -0,0 +1,95 @@
"""福袋相关文本解析辅助函数。
本模块提供若干轻量级的解析函数,主要用于:
- 从 OCR 文本中抽取福袋内容/倒计时/价值/参与人数
- 方便在单元测试中独立验证文本处理逻辑
"""
from __future__ import annotations
from typing import Optional
import re
from douyin.utils.douyin_utils import normalize_countdown_text, extract_prize_value_yuan
def _safe_str(text: Optional[str]) -> str:
"""将输入安全地转换为字符串,None -> 空字符串。"""
if text is None:
return ""
return str(text)
def extract_fudai_content(text: Optional[str]) -> str:
"""从 OCR 文本中提取“福袋内容”相关描述。
当前实现比较宽松:
- 优先截取 “福袋内容:xxx” 或 “内容:xxx” 之后的部分
- 否则返回原始文本(去掉首尾空白)
"""
t = _safe_str(text).strip()
if not t:
return ""
# 常见前缀:福袋内容:xxx / 奖品内容:xxx / 内容:xxx
m = re.search(r"(福袋内容|奖品内容|内容)[::]\s*(.+)", t)
if m:
return m.group(2).strip()
# 如果包含“福袋”关键字,简单返回整句,后续需要时可再细化
if "福袋" in t:
return t
return t
def extract_fudai_countdown(text: Optional[str]) -> str:
"""从 OCR 文本中提取倒计时字符串。
返回值示例:
- ``"05:30"`` / ``"05:30后开奖"``
- 若无法解析则返回空字符串。
"""
t = _safe_str(text)
if not t:
return ""
norm = normalize_countdown_text(t)
return norm or ""
def extract_fudai_value(text: Optional[str]) -> float:
"""从 OCR 文本中提取福袋价值金额(元)。
直接复用 ``douyin_utils.extract_prize_value_yuan``。
"""
return float(extract_prize_value_yuan(_safe_str(text)))
def extract_participants_count(text: Optional[str]) -> int:
"""从 OCR 文本中提取“参与人数”。
支持的常见格式示例:
- ``"共1份1173人已参与"``
- ``"已有1000人参与"``
- ``"1173人已参与"``
- 若无法解析则返回 0。
"""
t = _safe_str(text)
if not t:
return 0
# 优先匹配“xxxx人已参与 / xxxx人参与 / xxxx人”
m = re.search(r"(\d+)\s*人(?:已参与|参与)?", t)
if m:
try:
return int(m.group(1))
except ValueError:
return 0
# 退化:查找所有数字,取中等大小的一个,避免把“份数”等误当成人数
nums = [int(n) for n in re.findall(r"\d+", t) if n.isdigit()]
if not nums:
return 0
# 简化策略:返回最大值(通常人数是文本里最大的数字)
return max(nums)
+4 -7
View File
@@ -32,13 +32,10 @@ def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str:
try:
if not os.path.exists(src):
return cut_pic_name
_raw = Image.open(src)
try:
_raw.load()
# 转灰度
img = _raw.convert("L")
finally:
_raw.close()
img = Image.open(src)
img.load()
# 转灰度
img = img.convert("L")
# 放大两倍(Lanczos)
img = img.resize((img.width * 2, img.height * 2), Image.LANCZOS)
# 自动对比并锐化
+12 -1
View File
@@ -121,4 +121,15 @@ def start_tracing() -> None:
_state["enabled"] = False
__all__ = ["start_tracing"]
def stop_tracing() -> None:
try:
sys.settrace(None)
finally:
_state["enabled"] = False
def is_enabled() -> bool:
return bool(_state.get("enabled"))
__all__ = ["start_tracing", "stop_tracing", "is_enabled"]
-80
View File
@@ -1,80 +0,0 @@
"""底部操作按钮区(开始运行 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的 widget 创建段 + 4 个按钮回调
(``start_run`` / ``stop_run`` / ``force_stop_run`` / ``send_back_key``)。
依赖通过显式参数注入。状态写回主线程通过 ``status_var`` 实现。
"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, RIGHT, X
from typing import Any, Callable
def setup_action_buttons(
actions: ttk.Frame,
*,
runner: Any,
status_var: tk.StringVar,
device_var: tk.StringVar,
on_line: Callable[[str], None],
save_ui_to_config: Callable[[], None],
get_params: Callable[[], Any],
) -> None:
"""构建底部操作按钮区(开始/停止/强制停止/发送返回键 + 状态标签)。"""
def start_run() -> None:
if runner.is_running():
on_line("[运行] 已在运行中")
return
save_ui_to_config()
params = get_params()
wait_display = "∞" if params.wait_minutes == 0 else f"{params.wait_minutes}m"
on_line(
f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} "
f"needswitch={params.needswitch} wait={wait_display} "
f"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} "
f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] "
f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} "
f"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only"
)
status_var.set("运行中")
try:
runner.start(params)
except Exception as e:
status_var.set("启动失败")
on_line(f"[错误] {e}")
def stop_run() -> None:
runner.stop()
status_var.set("已停止")
def force_stop_run() -> None:
"""强制终止后台进程(包括可能残留的子进程)。"""
runner.force_stop()
status_var.set("已停止(强制)")
def send_back_key() -> None:
dev = device_var.get().strip()
try:
runner.send_back_key(dev)
except Exception as e:
on_line(f"[错误] 发送返回键失败: {e}")
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
side=LEFT, padx=(0, 8)
)
# (已移除:测试养号/测试评论 按钮与相关UI)
ttk.Button(actions, text="发送返回键", command=send_back_key).pack(
side=LEFT, padx=(0, 8)
)
ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)
-133
View File
@@ -1,133 +0,0 @@
"""行为日志 Tab 的工具栏(关键字筛选 + 文本搜索)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的搜索栏 widget 创建段 +
配色配置 + 4 个共享 ``nonlocal`` matches state 的搜索闭包。
抽出后用一个 ``ActionsLogToolbarHandles`` 暴露 ``main()`` 仍要用的引用:
- ``refresh_actions_log`` - 刷新回调(被 root.after 调度用)
"""
from __future__ import annotations
import tkinter as tk
from dataclasses import dataclass
from tkinter import ttk
from tkinter.constants import LEFT, X, Y
from typing import Callable
from gui.components.actions_log_view import (
configure_actions_log_colors as _configure_actions_log_colors_impl,
refresh_actions_log as _refresh_actions_log_impl,
)
from gui.components.text_search import generic_search_widget
@dataclass
class ActionsLogToolbarHandles:
"""``main()`` 后续仍要用的 handles。"""
refresh_actions_log: Callable[[], None]
def setup_actions_log_toolbar(
parent: tk.Misc,
*,
actions_log_text: tk.Text,
theme_getter: Callable[[], str],
) -> ActionsLogToolbarHandles:
"""构建行为日志 Tab 顶部的工具栏(配色 + 关键字筛选 + 文本搜索)。
依赖通过显式参数注入:
- ``parent`` - 工具栏父容器(``actions_log_top``)
- ``actions_log_text`` - 行为日志文本 widget
- ``theme_getter`` - ``() -> str`` 返回当前 GUI 主题名
"""
# 配置行为日志颜色标签(使用统一的颜色配置模块)
def configure_actions_log_colors() -> None:
_configure_actions_log_colors_impl(
actions_log_text,
theme_getter=theme_getter,
)
# 初始配置
configure_actions_log_colors()
actions_filter_var = tk.StringVar(value="")
def refresh_actions_log() -> None:
_refresh_actions_log_impl(
actions_log_text,
theme_getter=theme_getter,
filter_getter=lambda: actions_filter_var.get().strip(),
)
ttk.Label(parent, text="关键字筛选:").pack(side=LEFT)
ttk.Entry(parent, textvariable=actions_filter_var, width=16).pack(
side=LEFT, padx=(0, 8)
)
ttk.Button(parent, text="刷新", command=refresh_actions_log).pack(
side=LEFT, padx=(0, 10)
)
# 行为日志搜索功能
ttk.Separator(parent, orient="vertical").pack(
side=LEFT, fill=Y, padx=5, pady=3
)
ttk.Label(parent, text="搜索:").pack(side=LEFT)
actions_search_var = tk.StringVar(value="")
actions_search_entry = ttk.Entry(
parent, textvariable=actions_search_var, width=20
)
actions_search_entry.pack(side=LEFT, padx=(0, 5))
state = {
"matches": [],
"current_index": -1,
}
def search_in_actions_log(direction: int = 1) -> None:
"""在行为日志中搜索文本(使用通用搜索实现)"""
state["current_index"] = generic_search_widget(
actions_log_text,
actions_search_var,
state["matches"],
state["current_index"],
direction,
)
def search_next_in_actions() -> None:
search_in_actions_log(1)
def search_prev_in_actions() -> None:
search_in_actions_log(-1)
def clear_search_in_actions() -> None:
actions_search_var.set("")
actions_log_text.tag_remove("search_highlight", "1.0", "end")
actions_log_text.tag_remove("search_current", "1.0", "end")
state["matches"] = []
state["current_index"] = -1
def on_actions_search_entry_key(event):
if event.keysym == "Return":
search_next_in_actions()
actions_search_entry.bind("<KeyPress>", on_actions_search_entry_key)
ttk.Button(parent, text="搜索", command=search_next_in_actions).pack(
side=LEFT, padx=(0, 2)
)
ttk.Button(parent, text="上一个", command=search_prev_in_actions).pack(
side=LEFT, padx=(0, 2)
)
ttk.Button(parent, text="下一个", command=search_next_in_actions).pack(
side=LEFT, padx=(0, 2)
)
ttk.Button(parent, text="清除", command=clear_search_in_actions).pack(
side=LEFT
)
return ActionsLogToolbarHandles(
refresh_actions_log=refresh_actions_log,
)
-183
View File
@@ -1,183 +0,0 @@
"""行为日志(``logs/actions.log``) Tab 的视图刷新与配色逻辑。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
``configure_actions_log_colors`` 和 ``refresh_actions_log``,
搜索相关的小闭包仍保留在 ``gui_app.py`` 中(它们共享 nonlocal 状态)。
依赖通过显式参数注入:
- ``text_widget`` - 展示用的 Text/ScrolledText
- ``theme_getter`` - 一个 ``() -> str`` 回调,返回当前 GUI 主题名
- ``filter_getter`` - 一个 ``() -> str`` 回调,返回筛选关键字(已 strip)
"""
from __future__ import annotations
import os
import tkinter as tk
from typing import Callable
try:
from gui.components.log_color_config import (
apply_operation_color,
get_color_config,
)
except ImportError:
def get_color_config(theme: str = "litera"): # type: ignore[no-redef]
return {}
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
pass
def configure_actions_log_colors(
text_widget: tk.Text,
*,
theme_getter: Callable[[], str],
) -> None:
"""根据当前主题配置行为日志的颜色标签"""
try:
# 获取当前主题
try:
current_theme = theme_getter()
except Exception:
current_theme = "litera"
# 获取颜色配置
color_config = get_color_config(current_theme)
# 根据主题设置背景和前景色
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
is_light = current_theme.lower() in light_themes
if is_light:
text_widget.configure(
background="#FFFFFF",
foreground="#2C2C2C",
insertbackground="#2C2C2C",
)
else:
text_widget.configure(
background="#1E1E1E",
foreground="#E0E0E0",
insertbackground="#FFFFFF",
)
# 为所有操作类型配置标签
for op_type, colors in color_config.items():
tag_name = f"op_{op_type}"
try:
text_widget.tag_configure(
tag_name,
foreground=colors["foreground"],
background=colors["background"],
)
except Exception:
pass # 忽略标签配置失败
except Exception:
pass # 忽略颜色配置失败
def refresh_actions_log(
text_widget: tk.Text,
*,
theme_getter: Callable[[], str],
filter_getter: Callable[[], str],
) -> None:
"""读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。"""
# 使用统一的路径配置
try:
from douyin.core.path_config import get_actions_log_path
path = get_actions_log_path()
except Exception:
# 回退到旧路径(向后兼容)
# 修正路径:GUI应该读取根目录的logs/actions.log
from douyin.core import path_config
path = path_config.get_actions_log_path()
try:
if os.path.exists(path):
# 仿照 web_gui 的实现:只读最后一小段,避免文件巨大
size = os.path.getsize(path)
if size == 0:
text_widget.delete("1.0", "end")
text_widget.insert("1.0", "行为日志文件为空")
return
read_bytes = min(size, 65536)
with open(path, "rb") as f:
if read_bytes < size:
f.seek(-read_bytes, os.SEEK_END)
data = f.read()
# 尝试多种编码方式
try:
# 先尝试 utf-8-sig(带BOM)
text = data.decode("utf-8-sig", errors="replace")
except Exception:
try:
# 再尝试 utf-8
text = data.decode("utf-8", errors="replace")
except Exception:
# 最后尝试 gbk(Windows常见编码)
text = data.decode("gbk", errors="replace")
lines = text.splitlines()
# 只取最近 300 行
tail = lines[-300:]
# 关键字筛选:若填写了筛选词,只保留包含该关键字的行
kw = filter_getter()
if kw:
tail = [ln for ln in tail if kw in ln]
# 保存当前滚动位置,避免刷新时自动置顶
try:
scroll_position = text_widget.yview()[
0
] # 获取当前滚动位置(顶部可见位置的比例)
except Exception:
scroll_position = 0.0
text_widget.delete("1.0", "end")
if tail:
# 获取当前主题(用于颜色配置)
try:
current_theme = theme_getter()
except Exception:
current_theme = "litera"
# 逐行插入并应用颜色标签
for i, line in enumerate(tail):
start_pos = text_widget.index("end-1c")
# 插入行内容
if i > 0:
text_widget.insert("end", "\n")
text_widget.insert("end", line)
# 使用统一的颜色配置模块应用颜色
end_pos = text_widget.index("end")
try:
apply_operation_color(
text_widget,
start_pos,
end_pos,
line,
current_theme,
)
except Exception:
pass # 忽略颜色应用失败
else:
text_widget.insert("1.0", "暂无匹配的行为日志")
# 恢复之前的滚动位置,避免自动置顶
try:
text_widget.yview_moveto(scroll_position)
except Exception:
pass
else:
text_widget.delete("1.0", "end")
text_widget.insert(
"1.0", "暂无行为日志(logs/actions.log 不存在)"
)
except Exception as e:
text_widget.delete("1.0", "end")
text_widget.insert("1.0", f"读取行为日志失败:{e}")
-678
View File
@@ -1,678 +0,0 @@
"""GUI 配置序列化:从 config.json 加载 → tk Vars,以及 Vars → config.json 保存。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
``load_config_to_ui`` 和 ``save_ui_to_config``,共依赖 122 个 tk Var 和 5 个 Text widget。
依赖通过显式参数注入:
- ``vars_`` - 一个名→Var 的 ``Dict[str, tk.Variable]``,键名与原 main() 中的变量名一致
- ``texts_`` - 一个名→Text widget 的 ``Dict[str, tk.Text]``(want_text/not_want_text 等)
- ``read_config`` - 读配置回调
- ``write_config`` - 写配置回调
- ``on_line`` - 日志回调
``load_config_to_ui`` 把 ``cfg`` 当作 nonlocal 变量原地赋值,这里改为返回新 cfg 让调用方更新。
"""
from __future__ import annotations
import tkinter as tk
from typing import Callable, Dict
def load_config_to_ui(
*,
vars_: Dict[str, tk.Variable],
texts_: Dict[str, tk.Text],
read_config: Callable[[], dict],
) -> dict:
cfg = read_config()
vars_["needswitch_var"].set(bool(cfg.get("needswitch", True)))
vars_["infinite_loop_var"].set(bool(cfg.get("infinite_loop_enabled", False)))
vars_["wait_minutes_var"].set(int(cfg.get("wait_minutes", 5) or 5))
vars_["yg_enabled_var"].set(bool(cfg.get("yanghao_enabled", True)))
vars_["yg_actions_enabled_var"].set(bool(cfg.get("yanghao_enable_actions", True)))
vars_["yg_only_var"].set(bool(cfg.get("yanghao_only", False)))
vars_["yg_recommend_duration_var"].set(
int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
)
vars_["yg_recommend_interval_var"].set(
int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
)
vars_["min_value_var"].set(float(cfg.get("min_prize_value_yuan", 0) or 0))
vars_["min_participants_var"].set(int(cfg.get("min_participants", 0) or 0))
vars_["max_participants_var"].set(int(cfg.get("max_participants", 0) or 0))
vars_["skip_gt_seconds_var"].set(
int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
)
vars_["reset_after_swipes_enabled_var"].set(
bool(cfg.get("reset_after_swipes_enabled", False))
)
vars_["reset_after_swipes_var"].set(int(cfg.get("reset_after_swipes", 10) or 10))
vars_["reset_after_swipes_action_var"].set(
str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
)
vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True)))
vars_["swipe_down_back_enabled_var"].set(
bool(cfg.get("swipe_down_back_enabled", False))
)
vars_["swipe_down_back_count_var"].set(int(cfg.get("swipe_down_back_count", 3) or 3))
vars_["auto_join_var"].set(bool(cfg.get("auto_join_fansclub", False)))
vars_["fansclub_action_var"].set(
str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
)
vars_["streaming_enabled_var"].set(bool(cfg.get("enable_streaming_screenshot", True)))
vars_["lucky_draw_red_ratio_threshold_var"].set(
float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
)
vars_["y_var"].set(int(cfg.get("y_pianyi", 0) or 0))
# Web端新增配置 - 高价值预约相关
vars_["high_value_fudai_enabled_var"].set(
bool(cfg.get("high_value_fudai_enabled", False))
)
vars_["high_value_fudai_threshold_yuan_var"].set(
float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
)
vars_["high_value_fudai_join_ahead_seconds_var"].set(
int(cfg.get("high_value_fudai_join_ahead_seconds", 300) or 300)
)
vars_["high_value_fudai_max_swipe_back_var"].set(
int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
)
vars_["high_value_fudai_max_reservations_var"].set(
int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
)
vars_["high_value_fudai_after_action_var"].set(
str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
)
vars_["high_value_fudai_poll_before_seconds_var"].set(
float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
)
vars_["high_value_room_revisit_enabled_var"].set(
bool(cfg.get("high_value_room_revisit_enabled", True))
)
vars_["high_value_room_revisit_only_current_run_var"].set(
bool(cfg.get("high_value_room_revisit_only_current_run", False))
)
vars_["high_value_room_revisit_min_interval_seconds_var"].set(
int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
)
vars_["high_value_room_revisit_max_per_run_var"].set(
int(cfg.get("high_value_room_revisit_max_per_run", 5))
)
vars_["high_value_room_revisit_min_prize_value_var"].set(
float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
)
vars_["high_value_room_revisit_max_age_days_var"].set(
int(cfg.get("high_value_room_revisit_max_age_days", 30))
)
vars_["reservation_back_verify_enabled_var"].set(
bool(cfg.get("reservation_back_verify_enabled", True))
)
vars_["reservation_back_swipe_delay_var"].set(
float(cfg.get("reservation_back_swipe_delay", 0) or 0)
)
vars_["reservation_back_verify_wait_seconds_var"].set(
float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
)
vars_["fudai_find_max_attempts_var"].set(int(cfg.get("fudai_find_max_attempts", 0) or 0))
vars_["fudai_icon_retry_delay_seconds_var"].set(
float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
)
vars_["fudai_icon_max_wait_seconds_var"].set(
float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
)
vars_["fudai_click_wait_seconds_var"].set(
float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0)
)
vars_["fudai_disable_content_recognition_var"].set(
bool(cfg.get("fudai_disable_content_recognition", False))
)
vars_["fudai_disable_task_recognition_var"].set(
bool(cfg.get("fudai_disable_task_recognition", False))
)
try:
vars_["fudai_exit_after_misses_var"].set(
int(cfg.get("fudai_exit_after_misses", 30) or 30)
)
except Exception:
vars_["fudai_exit_after_misses_var"].set(30)
try:
vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True)))
except Exception:
vars_["enable_back_on_misses_var"].set(True)
try:
vars_["reset_after_swipes_action_var"].set(
str(cfg.get("reset_after_swipes_action", "swipe"))
)
except Exception:
vars_["reset_after_swipes_action_var"].set("swipe")
vars_["switch_room_wait_after_stage_diag_seconds_var"].set(
float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
)
# GUI 主题
try:
vars_["gui_theme_var"].set(
str(cfg.get("gui", {}).get("theme", "litera") or "litera")
)
except Exception:
vars_["gui_theme_var"].set("litera")
vars_["live_room_match_threshold_var"].set(
float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
)
vars_["swipe_duration_ms_var"].set(int(cfg.get("swipe_duration_ms", 600) or 600))
vars_["swipe_up_start_y_var"].set(int(cfg.get("swipe_up_start_y", 1200) or 1200))
vars_["swipe_up_end_y_var"].set(int(cfg.get("swipe_up_end_y", 600) or 600))
vars_["fudai_quiet_hours_enabled_var"].set(
bool(cfg.get("fudai_quiet_hours_enabled", True))
)
vars_["fudai_quiet_start_hour_var"].set(int(cfg.get("fudai_quiet_start_hour", 2) or 2))
vars_["fudai_quiet_end_hour_var"].set(int(cfg.get("fudai_quiet_end_hour", 7) or 7))
vars_["stage_diag_max_time_var"].set(float(cfg.get("stage_diag_max_time", 10.0) or 10.0))
vars_["stage_diag_max_step_time_var"].set(
float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
)
vars_["stage_diag_verbose_var"].set(
bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
)
vars_["enable_ocr_mode1_var"].set(bool(cfg.get("enable_ocr_mode1", False)))
vars_["fudai_template_match_enabled_var"].set(
bool(cfg.get("fudai_template_match_enabled", False))
)
vars_["fudai_template_match_threshold_var"].set(
float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
)
vars_["fudai_detail_template_threshold_var"].set(
float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
)
vars_["coupon_template_match_threshold_var"].set(
float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
)
vars_["attend_button_red_ratio_threshold_var"].set(
float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
)
vars_["fansclub_join_red_ratio_threshold_var"].set(
float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
)
vars_["shopping_redpacket_red_ratio_threshold_var"].set(
float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
)
# 粉丝团等待/点击延迟配置
vars_["fansclub_click_delay_var"].set(float(cfg.get("fansclub_click_delay", 0.6) or 0.6))
vars_["fansclub_auto_wait_var"].set(
float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
)
vars_["fansclub_manual_wait_var"].set(
float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
)
vars_["skip_lt_seconds_var"].set(int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10))
# 调试图像清理配置
debug_captures_config = cfg.get("debug_captures", {})
if isinstance(debug_captures_config, dict):
vars_["debug_captures_enabled_var"].set(
bool(debug_captures_config.get("enabled", False))
)
vars_["debug_captures_auto_cleanup_var"].set(
bool(debug_captures_config.get("auto_cleanup", True))
)
vars_["debug_captures_keep_days_var"].set(
int(debug_captures_config.get("keep_days", 7) or 7)
)
vars_["debug_captures_max_files_var"].set(
int(debug_captures_config.get("max_files", 2000) or 2000)
)
vars_["debug_captures_async_save_var"].set(
bool(debug_captures_config.get("async_save", True))
)
vars_["debug_captures_log_on_complete_var"].set(
bool(debug_captures_config.get("log_on_complete", False))
)
else:
vars_["debug_captures_auto_cleanup_var"].set(True)
vars_["debug_captures_keep_days_var"].set(7)
vars_["debug_captures_max_files_var"].set(2000)
# 日志配置(load_config_to_ui 需要覆盖 UI 变量,避免“保存后再加载不生效”)
logging_config = cfg.get("logging", {})
if isinstance(logging_config, dict):
vars_["logging_beautify_var"].set(bool(logging_config.get("beautify_output", True)))
vars_["logging_color_var"].set(bool(logging_config.get("color_output", True)))
vars_["logging_show_timestamps_var"].set(
bool(logging_config.get("show_timestamps", True))
)
vars_["logging_use_dated_logs_var"].set(
bool(logging_config.get("use_dated_logs", True))
)
vars_["logging_enable_monitor_var"].set(
bool(logging_config.get("enable_monitor", True))
)
vars_["log_unified_enabled_var"].set(bool(cfg.get("log_unified_enabled", True)))
vars_["log_unified_path_var"].set(
str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
)
vars_["logging_keep_days_var"].set(int(logging_config.get("keep_days", 30) or 30))
vars_["logging_compress_logs_var"].set(
bool(logging_config.get("compress_logs", True))
)
vars_["logging_max_total_size_gb_var"].set(
float(logging_config.get("max_total_size_gb", 10.0) or 10.0)
)
vars_["logging_compress_after_days_var"].set(
int(logging_config.get("compress_after_days", 7) or 7)
)
vars_["logging_debug_level_var"].set(
str(logging_config.get("debug_detail_level", "normal") or "normal")
)
vars_["logging_error_level_var"].set(
str(logging_config.get("error_detail_level", "full") or "full")
)
vars_["logging_action_format_var"].set(
str(logging_config.get("action_log_format", "concise") or "concise")
)
vars_["logging_format_mode_var"].set(
str(logging_config.get("log_format_mode", "simple") or "simple")
)
perf_cfg = logging_config.get("performance_tracking", {})
if isinstance(perf_cfg, dict):
vars_["logging_performance_enabled_var"].set(bool(perf_cfg.get("enabled", True)))
vars_["logging_track_functions_var"].set(
bool(perf_cfg.get("track_function_calls", True))
)
vars_["logging_monitor_warning_mb_var"].set(
float(logging_config.get("monitor_warning_mb", 500.0) or 500.0)
)
vars_["logging_monitor_critical_mb_var"].set(
float(logging_config.get("monitor_critical_mb", 2000.0) or 2000.0)
)
vars_["yg_like_prob_var"].set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0))
vars_["yg_fav_prob_var"].set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
vars_["yg_comment_prob_var"].set(float(cfg.get("yanghao_comment_prob", 0.0) or 0.0))
vars_["yg_dwell_on_action_min_var"].set(
float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
)
vars_["yg_dwell_on_action_max_var"].set(
float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
)
vars_["yg_icon_roi_size_var"].set(int(cfg.get("yanghao_icon_roi_size", 240) or 240))
vars_["yg_icon_match_threshold_var"].set(
float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
)
vars_["yg_step_screenshot_var"].set(bool(cfg.get("yanghao_step_screenshot", False)))
vars_["yg_like_roi_offset_x_var"].set(int(cfg.get("yanghao_like_roi_offset_x", 0) or 0))
vars_["yg_like_roi_offset_y_var"].set(int(cfg.get("yanghao_like_roi_offset_y", 0) or 0))
vars_["yg_fav_roi_offset_x_var"].set(int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0))
vars_["yg_fav_roi_offset_y_var"].set(int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0))
vars_["yg_like_icon_x_var"].set(int(cfg.get("yanghao_like_icon_x", 0) or 0))
vars_["yg_like_icon_y_var"].set(int(cfg.get("yanghao_like_icon_y", 0) or 0))
vars_["yg_fav_icon_x_var"].set(int(cfg.get("yanghao_fav_icon_x", 0) or 0))
vars_["yg_fav_icon_y_var"].set(int(cfg.get("yanghao_fav_icon_y", 0) or 0))
vars_["yg_like_template_path_var"].set(
str(
cfg.get("yanghao_like_template_path", "assets/like.png")
or "assets/like.png"
)
)
vars_["yg_fav_template_path_var"].set(
str(
cfg.get("yanghao_fav_template_path", "assets/fav.png")
or "assets/fav.png"
)
)
vars_["yg_after_dwell_direction_var"].set(
str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
)
vars_["yg_after_dwell_distance_var"].set(
int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
)
vars_["yg_comment_btn_x_var"].set(int(cfg.get("yanghao_comment_btn_x", 0) or 0))
vars_["yg_comment_btn_y_var"].set(int(cfg.get("yanghao_comment_btn_y", 0) or 0))
vars_["yg_comment_input_x_var"].set(int(cfg.get("yanghao_comment_input_x", 0) or 0))
vars_["yg_comment_input_y_var"].set(int(cfg.get("yanghao_comment_input_y", 0) or 0))
vars_["yg_comment_send_x_var"].set(int(cfg.get("yanghao_comment_send_x", 0) or 0))
vars_["yg_comment_send_y_var"].set(int(cfg.get("yanghao_comment_send_y", 0) or 0))
vars_["yg_comment_close_x_var"].set(int(cfg.get("yanghao_comment_close_x", 0) or 0))
vars_["yg_comment_close_y_var"].set(int(cfg.get("yanghao_comment_close_y", 0) or 0))
# 仅保留黑名单 contains_not_want
want = cfg.get("contains_want", []) or []
not_want = cfg.get("contains_not_want", []) or []
yg_comment_texts_list = cfg.get("yanghao_comment_texts", []) or []
yg_like_keywords_list = cfg.get("yanghao_like_keywords", []) or []
yg_fav_keywords_list = cfg.get("yanghao_fav_keywords", []) or []
texts_["want_text"].delete("1.0", "end")
texts_["want_text"].insert("1.0", "\n".join(want))
texts_["not_want_text"].delete("1.0", "end")
texts_["not_want_text"].insert("1.0", "\n".join(not_want))
texts_["yg_comment_texts"].delete("1.0", "end")
texts_["yg_comment_texts"].insert("1.0", "\n".join(yg_comment_texts_list))
texts_["yg_like_keywords_text"].delete("1.0", "end")
texts_["yg_like_keywords_text"].insert("1.0", "\n".join(yg_like_keywords_list))
texts_["yg_fav_keywords_text"].delete("1.0", "end")
texts_["yg_fav_keywords_text"].insert("1.0", "\n".join(yg_fav_keywords_list))
return cfg
def save_ui_to_config(
*,
vars_: Dict[str, tk.Variable],
texts_: Dict[str, tk.Text],
cfg: dict,
read_config: Callable[[], dict],
write_config: Callable[[dict], None],
on_line: Callable[[str], None],
) -> None:
want_lines = [
x.strip() for x in texts_["want_text"].get("1.0", "end").splitlines() if x.strip()
]
not_want_lines = [
x.strip() for x in texts_["not_want_text"].get("1.0", "end").splitlines() if x.strip()
]
yg_comment_text_lines = [
x.strip()
for x in texts_["yg_comment_texts"].get("1.0", "end").splitlines()
if x.strip()
]
yg_like_kw_lines = [
x.strip()
for x in texts_["yg_like_keywords_text"].get("1.0", "end").splitlines()
if x.strip()
]
yg_fav_kw_lines = [
x.strip()
for x in texts_["yg_fav_keywords_text"].get("1.0", "end").splitlines()
if x.strip()
]
cfg2 = read_config()
cfg2["needswitch"] = bool(vars_["needswitch_var"].get())
cfg2["infinite_loop_enabled"] = bool(vars_["infinite_loop_var"].get())
cfg2["wait_minutes"] = int(vars_["wait_minutes_var"].get() or 5)
cfg2["y_pianyi"] = int(vars_["y_var"].get() or 0)
cfg2["contains_want"] = want_lines
cfg2["contains_not_want"] = not_want_lines
cfg2["min_prize_value_yuan"] = float(vars_["min_value_var"].get() or 0)
cfg2["min_participants"] = int(vars_["min_participants_var"].get() or 0)
cfg2["max_participants"] = int(vars_["max_participants_var"].get() or 0)
cfg2["skip_if_countdown_gt_seconds"] = int(vars_["skip_gt_seconds_var"].get() or 900)
cfg2["reset_after_swipes_enabled"] = bool(vars_["reset_after_swipes_enabled_var"].get())
cfg2["reset_after_swipes"] = int(vars_["reset_after_swipes_var"].get() or 10)
cfg2["auto_join_fansclub"] = bool(vars_["auto_join_var"].get())
cfg2["fansclub_fail_action"] = str(vars_["fansclub_action_var"].get() or "stay").lower()
cfg2["lucky_draw_red_ratio_threshold"] = float(
vars_["lucky_draw_red_ratio_threshold_var"].get() or 0.9
)
# Web端新增配置 - 高价值预约相关
cfg2["high_value_fudai_enabled"] = bool(vars_["high_value_fudai_enabled_var"].get())
cfg2["high_value_fudai_threshold_yuan"] = float(
vars_["high_value_fudai_threshold_yuan_var"].get() or 1000
)
cfg2["high_value_fudai_join_ahead_seconds"] = int(
vars_["high_value_fudai_join_ahead_seconds_var"].get() or 300
)
cfg2["high_value_fudai_max_swipe_back"] = int(
vars_["high_value_fudai_max_swipe_back_var"].get() or 60
)
cfg2["high_value_fudai_max_reservations"] = int(
vars_["high_value_fudai_max_reservations_var"].get() or 5
)
cfg2["high_value_fudai_after_action"] = str(
vars_["high_value_fudai_after_action_var"].get() or "continue"
).lower()
cfg2["high_value_fudai_poll_before_seconds"] = float(
vars_["high_value_fudai_poll_before_seconds_var"].get() or 10.0
)
cfg2["high_value_room_revisit_enabled"] = bool(
vars_["high_value_room_revisit_enabled_var"].get()
)
cfg2["high_value_room_revisit_only_current_run"] = bool(
vars_["high_value_room_revisit_only_current_run_var"].get()
)
cfg2["high_value_room_revisit_min_interval_seconds"] = int(
vars_["high_value_room_revisit_min_interval_seconds_var"].get()
)
cfg2["high_value_room_revisit_max_per_run"] = int(
vars_["high_value_room_revisit_max_per_run_var"].get()
)
cfg2["high_value_room_revisit_min_prize_value"] = float(
vars_["high_value_room_revisit_min_prize_value_var"].get()
)
cfg2["high_value_room_revisit_max_age_days"] = int(
vars_["high_value_room_revisit_max_age_days_var"].get()
)
cfg2["reservation_back_verify_enabled"] = bool(
vars_["reservation_back_verify_enabled_var"].get()
)
cfg2["reservation_back_swipe_delay"] = float(
vars_["reservation_back_swipe_delay_var"].get() or 0
)
cfg2["reservation_back_verify_wait_seconds"] = float(
vars_["reservation_back_verify_wait_seconds_var"].get() or 5.0
)
cfg2["fudai_find_max_attempts"] = int(vars_["fudai_find_max_attempts_var"].get() or 0)
cfg2["fudai_icon_retry_delay_seconds"] = float(
vars_["fudai_icon_retry_delay_seconds_var"].get() or 0.6
)
cfg2["fudai_icon_max_wait_seconds"] = float(
vars_["fudai_icon_max_wait_seconds_var"].get() or 5.0
)
cfg2["fudai_click_wait_seconds"] = float(
vars_["fudai_click_wait_seconds_var"].get() or 2.0
)
cfg2["fudai_exit_after_misses"] = int(vars_["fudai_exit_after_misses_var"].get() or 30)
cfg2["enable_back_on_misses"] = bool(vars_["enable_back_on_misses_var"].get())
cfg2["swipe_down_back_enabled"] = bool(vars_["swipe_down_back_enabled_var"].get())
cfg2["swipe_down_back_count"] = int(vars_["swipe_down_back_count_var"].get() or 3)
cfg2["reset_after_swipes_action"] = str(
vars_["reset_after_swipes_action_var"].get() or "swipe"
)
cfg2["fudai_disable_content_recognition"] = bool(
vars_["fudai_disable_content_recognition_var"].get()
)
cfg2["fudai_disable_task_recognition"] = bool(
vars_["fudai_disable_task_recognition_var"].get()
)
cfg2["switch_room_wait_after_stage_diag_seconds"] = float(
vars_["switch_room_wait_after_stage_diag_seconds_var"].get() or 7.0
)
cfg2["live_room_match_threshold"] = float(
vars_["live_room_match_threshold_var"].get() or 0.8
)
cfg2["swipe_duration_ms"] = int(vars_["swipe_duration_ms_var"].get() or 600)
cfg2["swipe_up_start_y"] = int(vars_["swipe_up_start_y_var"].get() or 1200)
cfg2["swipe_up_end_y"] = int(vars_["swipe_up_end_y_var"].get() or 600)
cfg2["fudai_quiet_hours_enabled"] = bool(vars_["fudai_quiet_hours_enabled_var"].get())
cfg2["fudai_quiet_start_hour"] = int(vars_["fudai_quiet_start_hour_var"].get() or 0)
cfg2["fudai_quiet_end_hour"] = int(vars_["fudai_quiet_end_hour_var"].get() or 0)
cfg2["stage_diag_max_time"] = float(vars_["stage_diag_max_time_var"].get() or 10.0)
cfg2["stage_diag_max_step_time"] = float(
vars_["stage_diag_max_step_time_var"].get() or 2.0
)
cfg2["enable_ocr_mode1"] = bool(cfg.get("enable_ocr_mode1", False))
cfg2["fudai_template_match_enabled"] = bool(
vars_["fudai_template_match_enabled_var"].get()
)
cfg2["fudai_template_match_threshold"] = float(
vars_["fudai_template_match_threshold_var"].get() or 0.7
)
cfg2["fudai_detail_template_threshold"] = float(
vars_["fudai_detail_template_threshold_var"].get() or 0.7
)
cfg2["coupon_template_match_threshold"] = float(
vars_["coupon_template_match_threshold_var"].get() or 0.75
)
cfg2["attend_button_red_ratio_threshold"] = float(
vars_["attend_button_red_ratio_threshold_var"].get() or 0.25
)
cfg2["fansclub_join_red_ratio_threshold"] = float(
vars_["fansclub_join_red_ratio_threshold_var"].get() or 0.25
)
cfg2["shopping_redpacket_red_ratio_threshold"] = float(
vars_["shopping_redpacket_red_ratio_threshold_var"].get() or 0.15
)
# 粉丝团等待/点击延迟配置
cfg2["fansclub_click_delay"] = float(vars_["fansclub_click_delay_var"].get() or 0.6)
cfg2["fansclub_auto_join_wait_seconds"] = float(
vars_["fansclub_auto_wait_var"].get() or 5.0
)
cfg2["fansclub_manual_wait_seconds"] = float(
vars_["fansclub_manual_wait_var"].get() or 3.0
)
cfg2["skip_if_countdown_lt_seconds"] = int(vars_["skip_lt_seconds_var"].get() or 10)
# 调试图像清理配置
if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict):
cfg2["debug_captures"] = {}
cfg2["debug_captures"]["enabled"] = bool(vars_["debug_captures_enabled_var"].get())
cfg2["debug_captures"]["auto_cleanup"] = bool(
vars_["debug_captures_auto_cleanup_var"].get()
)
cfg2["debug_captures"]["keep_days"] = int(
vars_["debug_captures_keep_days_var"].get() or 7
)
cfg2["debug_captures"]["max_files"] = int(
vars_["debug_captures_max_files_var"].get() or 2000
)
cfg2["debug_captures"]["async_save"] = bool(vars_["debug_captures_async_save_var"].get())
cfg2["debug_captures"]["log_on_complete"] = bool(
vars_["debug_captures_log_on_complete_var"].get()
)
# 日志配置
if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict):
cfg2["logging"] = {}
cfg2["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get())
cfg2["logging"]["color_output"] = bool(vars_["logging_color_var"].get())
cfg2["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get())
cfg2["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get())
cfg2["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get())
cfg2["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get() or 30)
cfg2["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get())
cfg2["logging"]["max_total_size_gb"] = float(
vars_["logging_max_total_size_gb_var"].get() or 10.0
)
cfg2["logging"]["compress_after_days"] = int(
vars_["logging_compress_after_days_var"].get() or 7
)
cfg2["logging"]["debug_detail_level"] = str(
vars_["logging_debug_level_var"].get() or "normal"
)
cfg2["logging"]["error_detail_level"] = str(
vars_["logging_error_level_var"].get() or "full"
)
cfg2["logging"]["action_log_format"] = str(
vars_["logging_action_format_var"].get() or "concise"
)
cfg2["logging"]["log_format_mode"] = str(
vars_["logging_format_mode_var"].get() or "simple"
)
cfg2["logging"]["stage_diag_verbose"] = bool(vars_["stage_diag_verbose_var"].get())
cfg2["logging"]["monitor_warning_mb"] = float(
vars_["logging_monitor_warning_mb_var"].get() or 500.0
)
cfg2["logging"]["monitor_critical_mb"] = float(
vars_["logging_monitor_critical_mb_var"].get() or 2000.0
)
# 性能追踪配置
if "performance_tracking" not in cfg2["logging"] or not isinstance(
cfg2["logging"]["performance_tracking"], dict
):
cfg2["logging"]["performance_tracking"] = {}
cfg2["logging"]["performance_tracking"]["enabled"] = bool(
vars_["logging_performance_enabled_var"].get()
)
cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool(
vars_["logging_track_functions_var"].get()
)
cfg2["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get())
cfg2["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log")
cfg2["yanghao_enabled"] = bool(vars_["yg_enabled_var"].get())
cfg2["yanghao_enable_actions"] = bool(vars_["yg_actions_enabled_var"].get())
cfg2["yanghao_only"] = bool(vars_["yg_only_var"].get())
cfg2["yanghao_recommend_duration_seconds"] = int(
vars_["yg_recommend_duration_var"].get() or 60
)
cfg2["yanghao_recommend_interval_seconds"] = int(
vars_["yg_recommend_interval_var"].get() or 0
)
cfg2["yanghao_like_prob"] = float(vars_["yg_like_prob_var"].get() or 0.0)
cfg2["yanghao_fav_prob"] = float(vars_["yg_fav_prob_var"].get() or 0.0)
cfg2["yanghao_comment_prob"] = float(vars_["yg_comment_prob_var"].get() or 0.0)
cfg2["yanghao_dwell_on_action_min_seconds"] = float(
vars_["yg_dwell_on_action_min_var"].get() or 5
)
cfg2["yanghao_dwell_on_action_max_seconds"] = float(
vars_["yg_dwell_on_action_max_var"].get() or 30
)
cfg2["yanghao_icon_roi_size"] = int(vars_["yg_icon_roi_size_var"].get() or 240)
cfg2["yanghao_icon_match_threshold"] = float(
vars_["yg_icon_match_threshold_var"].get() or 0.72
)
cfg2["yanghao_step_screenshot"] = bool(vars_["yg_step_screenshot_var"].get())
cfg2["yanghao_like_roi_offset_x"] = int(vars_["yg_like_roi_offset_x_var"].get() or 0)
cfg2["yanghao_like_roi_offset_y"] = int(vars_["yg_like_roi_offset_y_var"].get() or 0)
cfg2["yanghao_fav_roi_offset_x"] = int(vars_["yg_fav_roi_offset_x_var"].get() or 0)
cfg2["yanghao_fav_roi_offset_y"] = int(vars_["yg_fav_roi_offset_y_var"].get() or 0)
cfg2["yanghao_like_icon_x"] = int(vars_["yg_like_icon_x_var"].get() or 0)
cfg2["yanghao_like_icon_y"] = int(vars_["yg_like_icon_y_var"].get() or 0)
cfg2["yanghao_fav_icon_x"] = int(vars_["yg_fav_icon_x_var"].get() or 0)
cfg2["yanghao_fav_icon_y"] = int(vars_["yg_fav_icon_y_var"].get() or 0)
cfg2["yanghao_like_template_path"] = str(
vars_["yg_like_template_path_var"].get() or "assets/like.png"
)
cfg2["yanghao_fav_template_path"] = str(
vars_["yg_fav_template_path_var"].get() or "assets/fav.png"
)
cfg2["yanghao_after_dwell_swipe_direction"] = str(
vars_["yg_after_dwell_direction_var"].get() or "up"
)
cfg2["yanghao_after_dwell_swipe_distance_px"] = int(
vars_["yg_after_dwell_distance_var"].get() or 900
)
cfg2["yanghao_comment_btn_x"] = int(vars_["yg_comment_btn_x_var"].get() or 0)
cfg2["yanghao_comment_btn_y"] = int(vars_["yg_comment_btn_y_var"].get() or 0)
cfg2["yanghao_comment_input_x"] = int(vars_["yg_comment_input_x_var"].get() or 0)
cfg2["yanghao_comment_input_y"] = int(vars_["yg_comment_input_y_var"].get() or 0)
cfg2["yanghao_comment_send_x"] = int(vars_["yg_comment_send_x_var"].get() or 0)
cfg2["yanghao_comment_send_y"] = int(vars_["yg_comment_send_y_var"].get() or 0)
cfg2["yanghao_comment_close_x"] = int(vars_["yg_comment_close_x_var"].get() or 0)
cfg2["yanghao_comment_close_y"] = int(vars_["yg_comment_close_y_var"].get() or 0)
cfg2["yanghao_comment_texts"] = yg_comment_text_lines
cfg2["yanghao_like_keywords"] = yg_like_kw_lines
cfg2["yanghao_fav_keywords"] = yg_fav_kw_lines
# 流式后台截图配置
cfg2["enable_streaming_screenshot"] = bool(vars_["streaming_enabled_var"].get())
# GUI 配置
if "gui" not in cfg2 or not isinstance(cfg2["gui"], dict):
cfg2["gui"] = {}
cfg2["gui"]["theme"] = str(vars_["gui_theme_var"].get() or "litera")
cfg2["gui"]["realtime_status"] = {
"refresh_interval_ms": int(
vars_["gui_realtime_refresh_interval_ms_var"].get() or 1000
),
"tail_items": int(vars_["gui_realtime_tail_items_var"].get() or 50),
}
write_config(cfg2)
on_line("[配置] 已保存到 config.json")
# 如果用户关闭了流式后台截图,尝试停止正在运行的服务实例以立即生效
try:
from operations.screenshot_service import ScreenshotService
if not bool(cfg2.get("enable_streaming_screenshot", True)):
try:
ScreenshotService.get_instance().stop()
on_line("[截图服务] 已停止后台流式截图(配置更新)")
except Exception:
on_line("[截图服务] 停止后台截图服务失败(请重启程序以确保生效)")
except Exception:
# ignore if service module not available
pass
-538
View File
@@ -1,538 +0,0 @@
"""GUI Var 工厂:从 ``cfg`` 构建所有 ``tkinter`` Var 实例。
从 ``gui/gui_app.py`` 抽出 127 个 Var 声明。返回名→Var 的 dict,``main()`` 在解构后
继续以原变量名使用(避免改动 134 处现有引用点)。
"""
from __future__ import annotations
import tkinter as tk
from typing import Dict
def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]:
"""从 cfg 构建所有 tk Var 实例,返回名→Var 字典。"""
y_var = tk.IntVar(value=int(cfg.get("y_pianyi", 0) or 0))
enable_back_on_misses_var = tk.BooleanVar(
value=bool(cfg.get("enable_back_on_misses", True))
)
swipe_down_back_enabled_var = tk.BooleanVar(
value=bool(cfg.get("swipe_down_back_enabled", False))
)
swipe_down_back_count_var = tk.IntVar(
value=int(cfg.get("swipe_down_back_count", 3) or 3)
)
needswitch_var = tk.BooleanVar(value=bool(cfg.get("needswitch", True)))
infinite_loop_var = tk.BooleanVar(
value=bool(cfg.get("infinite_loop_enabled", False))
)
wait_minutes_var = tk.IntVar(value=int(cfg.get("wait_minutes", 5) or 5))
min_value_var = tk.DoubleVar(value=float(cfg.get("min_prize_value_yuan", 0) or 0))
min_participants_var = tk.IntVar(value=int(cfg.get("min_participants", 0) or 0))
max_participants_var = tk.IntVar(value=int(cfg.get("max_participants", 0) or 0))
skip_gt_seconds_var = tk.IntVar(
value=int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
)
reset_after_swipes_enabled_var = tk.BooleanVar(
value=bool(cfg.get("reset_after_swipes_enabled", False))
)
reset_after_swipes_var = tk.IntVar(
value=int(cfg.get("reset_after_swipes", 10) or 10)
)
reset_after_swipes_action_var = tk.StringVar(
value=str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
)
enable_back_on_misses_var = tk.BooleanVar(
value=bool(cfg.get("enable_back_on_misses", True))
)
streaming_enabled_var = tk.BooleanVar(
value=bool(cfg.get("enable_streaming_screenshot", True))
)
auto_join_var = tk.BooleanVar(value=bool(cfg.get("auto_join_fansclub", False)))
fansclub_action_var = tk.StringVar(
value=str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
)
fansclub_click_delay_var = tk.DoubleVar(
value=float(cfg.get("fansclub_click_delay", 0.6) or 0.6)
)
fansclub_auto_wait_var = tk.DoubleVar(
value=float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
)
fansclub_manual_wait_var = tk.DoubleVar(
value=float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
)
high_value_fudai_enabled_var = tk.BooleanVar(
value=bool(cfg.get("high_value_fudai_enabled", False))
)
high_value_fudai_threshold_yuan_var = tk.DoubleVar(
value=float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
)
high_value_fudai_join_ahead_seconds_var = tk.IntVar(
value=int(cfg.get("high_value_fudai_join_ahead_seconds", 300) or 300)
)
high_value_fudai_max_swipe_back_var = tk.IntVar(
value=int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
)
high_value_fudai_max_reservations_var = tk.IntVar(
value=int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
)
high_value_fudai_after_action_var = tk.StringVar(
value=str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
)
high_value_fudai_poll_before_seconds_var = tk.DoubleVar(
value=float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
)
high_value_room_revisit_enabled_var = tk.BooleanVar(
value=bool(cfg.get("high_value_room_revisit_enabled", True))
)
high_value_room_revisit_only_current_run_var = tk.BooleanVar(
value=bool(cfg.get("high_value_room_revisit_only_current_run", False))
)
high_value_room_revisit_min_interval_seconds_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
)
high_value_room_revisit_max_per_run_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_max_per_run", 5))
)
high_value_room_revisit_min_prize_value_var = tk.DoubleVar(
value=float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
)
high_value_room_revisit_max_age_days_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_max_age_days", 30))
)
reservation_back_verify_enabled_var = tk.BooleanVar(
value=bool(cfg.get("reservation_back_verify_enabled", True))
)
reservation_back_swipe_delay_var = tk.DoubleVar(
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
)
reservation_back_verify_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
)
fudai_find_max_attempts_var = tk.IntVar(
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
)
fudai_icon_retry_delay_seconds_var = tk.DoubleVar(
value=float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
)
fudai_icon_max_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
)
fudai_disable_content_recognition_var = tk.BooleanVar(
value=bool(cfg.get("fudai_disable_content_recognition", False))
)
fudai_disable_task_recognition_var = tk.BooleanVar(
value=bool(cfg.get("fudai_disable_task_recognition", False))
)
fudai_exit_after_misses_var = tk.IntVar(
value=int(cfg.get("fudai_exit_after_misses", 30) or 30)
)
fudai_click_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0)
)
switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(
value=float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
)
live_room_match_threshold_var = tk.DoubleVar(
value=float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
)
swipe_duration_ms_var = tk.IntVar(
value=int(cfg.get("swipe_duration_ms", 600) or 600)
)
swipe_up_start_y_var = tk.IntVar(
value=int(cfg.get("swipe_up_start_y", 1200) or 1200)
)
swipe_up_end_y_var = tk.IntVar(value=int(cfg.get("swipe_up_end_y", 600) or 600))
yg_enabled_var = tk.BooleanVar(value=bool(cfg.get("yanghao_enabled", True)))
yg_actions_enabled_var = tk.BooleanVar(
value=bool(cfg.get("yanghao_enable_actions", True))
)
yg_only_var = tk.BooleanVar(value=bool(cfg.get("yanghao_only", False)))
yg_recommend_duration_var = tk.IntVar(
value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
)
yg_recommend_interval_var = tk.IntVar(
value=int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
)
yg_like_prob_var = tk.DoubleVar(
value=float(cfg.get("yanghao_like_prob", 0.0) or 0.0)
)
yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
yg_comment_prob_var = tk.DoubleVar(
value=float(cfg.get("yanghao_comment_prob", 0.0) or 0.0)
)
yg_dwell_on_action_min_var = tk.DoubleVar(
value=float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
)
yg_dwell_on_action_max_var = tk.DoubleVar(
value=float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
)
yg_icon_roi_size_var = tk.IntVar(
value=int(cfg.get("yanghao_icon_roi_size", 240) or 240)
)
yg_icon_match_threshold_var = tk.DoubleVar(
value=float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
)
yg_step_screenshot_var = tk.BooleanVar(
value=bool(cfg.get("yanghao_step_screenshot", False))
)
yg_like_roi_offset_x_var = tk.IntVar(
value=int(cfg.get("yanghao_like_roi_offset_x", 0) or 0)
)
yg_like_roi_offset_y_var = tk.IntVar(
value=int(cfg.get("yanghao_like_roi_offset_y", 0) or 0)
)
yg_fav_roi_offset_x_var = tk.IntVar(
value=int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0)
)
yg_fav_roi_offset_y_var = tk.IntVar(
value=int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0)
)
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
yg_like_template_path_var = tk.StringVar(
value=str(
cfg.get("yanghao_like_template_path", "assets/like.png")
or "assets/like.png"
)
)
yg_fav_template_path_var = tk.StringVar(
value=str(
cfg.get("yanghao_fav_template_path", "assets/fav.png") or "assets/fav.png"
)
)
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
yg_after_dwell_direction_var = tk.StringVar(
value=str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
)
yg_after_dwell_distance_var = tk.IntVar(
value=int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
)
yg_comment_btn_x_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_btn_x", 0) or 0)
)
yg_comment_btn_y_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_btn_y", 0) or 0)
)
yg_comment_input_x_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_input_x", 0) or 0)
)
yg_comment_input_y_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_input_y", 0) or 0)
)
yg_comment_send_x_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_send_x", 0) or 0)
)
yg_comment_send_y_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_send_y", 0) or 0)
)
yg_comment_close_x_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_close_x", 0) or 0)
)
yg_comment_close_y_var = tk.IntVar(
value=int(cfg.get("yanghao_comment_close_y", 0) or 0)
)
fudai_quiet_hours_enabled_var = tk.BooleanVar(
value=bool(cfg.get("fudai_quiet_hours_enabled", True))
)
fudai_quiet_start_hour_var = tk.IntVar(
value=int(cfg.get("fudai_quiet_start_hour", 2) or 2)
)
fudai_quiet_end_hour_var = tk.IntVar(
value=int(cfg.get("fudai_quiet_end_hour", 7) or 7)
)
stage_diag_max_time_var = tk.DoubleVar(
value=float(cfg.get("stage_diag_max_time", 10.0) or 10.0)
)
stage_diag_max_step_time_var = tk.DoubleVar(
value=float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
)
stage_diag_verbose_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
)
enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False)))
fudai_template_match_enabled_var = tk.BooleanVar(
value=bool(cfg.get("fudai_template_match_enabled", False))
)
fudai_template_match_threshold_var = tk.DoubleVar(
value=float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
)
fudai_detail_template_threshold_var = tk.DoubleVar(
value=float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
)
lucky_draw_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
)
coupon_template_match_threshold_var = tk.DoubleVar(
value=float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
)
attend_button_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
)
fansclub_join_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
)
shopping_redpacket_red_ratio_threshold_var = tk.DoubleVar(
value=float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
)
debug_captures_enabled_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("enabled", False)
if isinstance(cfg.get("debug_captures"), dict)
else False
)
)
debug_captures_auto_cleanup_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("auto_cleanup", True)
if isinstance(cfg.get("debug_captures"), dict)
else True
)
)
debug_captures_keep_days_var = tk.IntVar(
value=int(
cfg.get("debug_captures", {}).get("keep_days", 7)
if isinstance(cfg.get("debug_captures"), dict)
else 7
)
)
debug_captures_max_files_var = tk.IntVar(
value=int(
cfg.get("debug_captures", {}).get("max_files", 2000)
if isinstance(cfg.get("debug_captures"), dict)
else 2000
)
)
debug_captures_async_save_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("async_save", True)
if isinstance(cfg.get("debug_captures"), dict)
else True
)
)
debug_captures_log_on_complete_var = tk.BooleanVar(
value=bool(
cfg.get("debug_captures", {}).get("log_on_complete", False)
if isinstance(cfg.get("debug_captures"), dict)
else False
)
)
debug_async_success_var = tk.IntVar(value=0)
debug_async_failure_var = tk.IntVar(value=0)
logging_beautify_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("beautify_output", True))
)
logging_color_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("color_output", True))
)
logging_show_timestamps_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("show_timestamps", True))
)
logging_use_dated_logs_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("use_dated_logs", True))
)
logging_enable_monitor_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("enable_monitor", True))
)
log_unified_enabled_var = tk.BooleanVar(
value=bool(cfg.get("log_unified_enabled", True))
)
log_unified_path_var = tk.StringVar(
value=str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
)
logging_keep_days_var = tk.IntVar(
value=int(cfg.get("logging", {}).get("keep_days", 30) or 30)
)
logging_compress_logs_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("compress_logs", True))
)
logging_max_total_size_gb_var = tk.DoubleVar(
value=float(cfg.get("logging", {}).get("max_total_size_gb", 10.0) or 10.0)
)
logging_compress_after_days_var = tk.IntVar(
value=int(cfg.get("logging", {}).get("compress_after_days", 7) or 7)
)
logging_performance_enabled_var = tk.BooleanVar(
value=bool(
cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True)
)
)
logging_track_functions_var = tk.BooleanVar(
value=bool(
cfg.get("logging", {})
.get("performance_tracking", {})
.get("track_function_calls", True)
)
)
logging_debug_level_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("debug_detail_level", "normal"))
)
logging_error_level_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("error_detail_level", "full"))
)
logging_action_format_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("action_log_format", "concise"))
)
logging_format_mode_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("log_format_mode", "simple"))
)
logging_monitor_warning_mb_var = tk.DoubleVar(
value=float(cfg.get("logging", {}).get("monitor_warning_mb", 500.0) or 500.0)
)
logging_monitor_critical_mb_var = tk.DoubleVar(
value=float(cfg.get("logging", {}).get("monitor_critical_mb", 2000.0) or 2000.0)
)
gui_theme_var = tk.StringVar(
value=str(cfg.get("gui", {}).get("theme", "litera") or "litera")
)
gui_realtime_refresh_interval_ms_var = tk.IntVar(
value=int(
cfg.get("gui", {})
.get("realtime_status", {})
.get("refresh_interval_ms", 1000)
or 1000
)
)
gui_realtime_tail_items_var = tk.IntVar(
value=int(
cfg.get("gui", {}).get("realtime_status", {}).get("tail_items", 50) or 50
)
)
skip_lt_seconds_var = tk.IntVar(
value=int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)
)
return {
"y_var": y_var,
"enable_back_on_misses_var": enable_back_on_misses_var,
"swipe_down_back_enabled_var": swipe_down_back_enabled_var,
"swipe_down_back_count_var": swipe_down_back_count_var,
"needswitch_var": needswitch_var,
"infinite_loop_var": infinite_loop_var,
"wait_minutes_var": wait_minutes_var,
"min_value_var": min_value_var,
"min_participants_var": min_participants_var,
"max_participants_var": max_participants_var,
"skip_gt_seconds_var": skip_gt_seconds_var,
"reset_after_swipes_enabled_var": reset_after_swipes_enabled_var,
"reset_after_swipes_var": reset_after_swipes_var,
"reset_after_swipes_action_var": reset_after_swipes_action_var,
"streaming_enabled_var": streaming_enabled_var,
"auto_join_var": auto_join_var,
"fansclub_action_var": fansclub_action_var,
"fansclub_click_delay_var": fansclub_click_delay_var,
"fansclub_auto_wait_var": fansclub_auto_wait_var,
"fansclub_manual_wait_var": fansclub_manual_wait_var,
"high_value_fudai_enabled_var": high_value_fudai_enabled_var,
"high_value_fudai_threshold_yuan_var": high_value_fudai_threshold_yuan_var,
"high_value_fudai_join_ahead_seconds_var": high_value_fudai_join_ahead_seconds_var,
"high_value_fudai_max_swipe_back_var": high_value_fudai_max_swipe_back_var,
"high_value_fudai_max_reservations_var": high_value_fudai_max_reservations_var,
"high_value_fudai_after_action_var": high_value_fudai_after_action_var,
"high_value_fudai_poll_before_seconds_var": high_value_fudai_poll_before_seconds_var,
"high_value_room_revisit_enabled_var": high_value_room_revisit_enabled_var,
"high_value_room_revisit_only_current_run_var": high_value_room_revisit_only_current_run_var,
"high_value_room_revisit_min_interval_seconds_var": high_value_room_revisit_min_interval_seconds_var,
"high_value_room_revisit_max_per_run_var": high_value_room_revisit_max_per_run_var,
"high_value_room_revisit_min_prize_value_var": high_value_room_revisit_min_prize_value_var,
"high_value_room_revisit_max_age_days_var": high_value_room_revisit_max_age_days_var,
"reservation_back_verify_enabled_var": reservation_back_verify_enabled_var,
"reservation_back_swipe_delay_var": reservation_back_swipe_delay_var,
"reservation_back_verify_wait_seconds_var": reservation_back_verify_wait_seconds_var,
"fudai_find_max_attempts_var": fudai_find_max_attempts_var,
"fudai_icon_retry_delay_seconds_var": fudai_icon_retry_delay_seconds_var,
"fudai_icon_max_wait_seconds_var": fudai_icon_max_wait_seconds_var,
"fudai_disable_content_recognition_var": fudai_disable_content_recognition_var,
"fudai_disable_task_recognition_var": fudai_disable_task_recognition_var,
"fudai_exit_after_misses_var": fudai_exit_after_misses_var,
"fudai_click_wait_seconds_var": fudai_click_wait_seconds_var,
"switch_room_wait_after_stage_diag_seconds_var": switch_room_wait_after_stage_diag_seconds_var,
"live_room_match_threshold_var": live_room_match_threshold_var,
"swipe_duration_ms_var": swipe_duration_ms_var,
"swipe_up_start_y_var": swipe_up_start_y_var,
"swipe_up_end_y_var": swipe_up_end_y_var,
"yg_enabled_var": yg_enabled_var,
"yg_actions_enabled_var": yg_actions_enabled_var,
"yg_only_var": yg_only_var,
"yg_recommend_duration_var": yg_recommend_duration_var,
"yg_recommend_interval_var": yg_recommend_interval_var,
"yg_like_prob_var": yg_like_prob_var,
"yg_fav_prob_var": yg_fav_prob_var,
"yg_comment_prob_var": yg_comment_prob_var,
"yg_dwell_on_action_min_var": yg_dwell_on_action_min_var,
"yg_dwell_on_action_max_var": yg_dwell_on_action_max_var,
"yg_icon_roi_size_var": yg_icon_roi_size_var,
"yg_icon_match_threshold_var": yg_icon_match_threshold_var,
"yg_step_screenshot_var": yg_step_screenshot_var,
"yg_like_roi_offset_x_var": yg_like_roi_offset_x_var,
"yg_like_roi_offset_y_var": yg_like_roi_offset_y_var,
"yg_fav_roi_offset_x_var": yg_fav_roi_offset_x_var,
"yg_fav_roi_offset_y_var": yg_fav_roi_offset_y_var,
"yg_like_icon_x_var": yg_like_icon_x_var,
"yg_like_icon_y_var": yg_like_icon_y_var,
"yg_fav_icon_x_var": yg_fav_icon_x_var,
"yg_fav_icon_y_var": yg_fav_icon_y_var,
"yg_like_template_path_var": yg_like_template_path_var,
"yg_fav_template_path_var": yg_fav_template_path_var,
"yg_after_dwell_direction_var": yg_after_dwell_direction_var,
"yg_after_dwell_distance_var": yg_after_dwell_distance_var,
"yg_comment_btn_x_var": yg_comment_btn_x_var,
"yg_comment_btn_y_var": yg_comment_btn_y_var,
"yg_comment_input_x_var": yg_comment_input_x_var,
"yg_comment_input_y_var": yg_comment_input_y_var,
"yg_comment_send_x_var": yg_comment_send_x_var,
"yg_comment_send_y_var": yg_comment_send_y_var,
"yg_comment_close_x_var": yg_comment_close_x_var,
"yg_comment_close_y_var": yg_comment_close_y_var,
"fudai_quiet_hours_enabled_var": fudai_quiet_hours_enabled_var,
"fudai_quiet_start_hour_var": fudai_quiet_start_hour_var,
"fudai_quiet_end_hour_var": fudai_quiet_end_hour_var,
"stage_diag_max_time_var": stage_diag_max_time_var,
"stage_diag_max_step_time_var": stage_diag_max_step_time_var,
"stage_diag_verbose_var": stage_diag_verbose_var,
"enable_ocr_mode1_var": enable_ocr_mode1_var,
"fudai_template_match_enabled_var": fudai_template_match_enabled_var,
"fudai_template_match_threshold_var": fudai_template_match_threshold_var,
"fudai_detail_template_threshold_var": fudai_detail_template_threshold_var,
"lucky_draw_red_ratio_threshold_var": lucky_draw_red_ratio_threshold_var,
"coupon_template_match_threshold_var": coupon_template_match_threshold_var,
"attend_button_red_ratio_threshold_var": attend_button_red_ratio_threshold_var,
"fansclub_join_red_ratio_threshold_var": fansclub_join_red_ratio_threshold_var,
"shopping_redpacket_red_ratio_threshold_var": shopping_redpacket_red_ratio_threshold_var,
"debug_captures_enabled_var": debug_captures_enabled_var,
"debug_captures_auto_cleanup_var": debug_captures_auto_cleanup_var,
"debug_captures_keep_days_var": debug_captures_keep_days_var,
"debug_captures_max_files_var": debug_captures_max_files_var,
"debug_captures_async_save_var": debug_captures_async_save_var,
"debug_captures_log_on_complete_var": debug_captures_log_on_complete_var,
"debug_async_success_var": debug_async_success_var,
"debug_async_failure_var": debug_async_failure_var,
"logging_beautify_var": logging_beautify_var,
"logging_color_var": logging_color_var,
"logging_show_timestamps_var": logging_show_timestamps_var,
"logging_use_dated_logs_var": logging_use_dated_logs_var,
"logging_enable_monitor_var": logging_enable_monitor_var,
"log_unified_enabled_var": log_unified_enabled_var,
"log_unified_path_var": log_unified_path_var,
"logging_keep_days_var": logging_keep_days_var,
"logging_compress_logs_var": logging_compress_logs_var,
"logging_max_total_size_gb_var": logging_max_total_size_gb_var,
"logging_compress_after_days_var": logging_compress_after_days_var,
"logging_performance_enabled_var": logging_performance_enabled_var,
"logging_track_functions_var": logging_track_functions_var,
"logging_debug_level_var": logging_debug_level_var,
"logging_error_level_var": logging_error_level_var,
"logging_action_format_var": logging_action_format_var,
"logging_format_mode_var": logging_format_mode_var,
"logging_monitor_warning_mb_var": logging_monitor_warning_mb_var,
"logging_monitor_critical_mb_var": logging_monitor_critical_mb_var,
"gui_theme_var": gui_theme_var,
"gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var,
"gui_realtime_tail_items_var": gui_realtime_tail_items_var,
"skip_lt_seconds_var": skip_lt_seconds_var,
}
-448
View File
@@ -1,448 +0,0 @@
"""调试参数 Tab UI 创建逻辑(含 30 个 var + 4 个内部闭包)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 430 行的 widget 创建段。
依赖通过显式参数注入:
- ``parent`` - ``left_notebook`` (tab 父容器)
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``,键名同原 ``main()``
"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, BOTH, X
from typing import Dict
def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
debug_tab = ttk.Frame(parent)
# 为调试参数标签页添加滚动条
debug_canvas = tk.Canvas(debug_tab, highlightthickness=0)
debug_scrollbar = ttk.Scrollbar(
debug_tab, orient="vertical", command=debug_canvas.yview
)
debug_scrollable_frame = ttk.Frame(debug_canvas)
debug_scrollable_frame.bind(
"<Configure>",
lambda e: debug_canvas.configure(scrollregion=debug_canvas.bbox("all")),
)
debug_canvas.create_window((0, 0), window=debug_scrollable_frame, anchor="nw")
debug_canvas.configure(yscrollcommand=debug_scrollbar.set)
# 鼠标滚轮支持
def _on_mousewheel(event):
debug_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def _on_shift_mousewheel(event):
debug_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
debug_canvas.bind_all("<MouseWheel>", _on_mousewheel)
debug_canvas.bind_all("<Shift-MouseWheel>", _on_shift_mousewheel)
debug_canvas.pack(side="left", fill="both", expand=True)
debug_scrollbar.pack(side="right", fill="y")
parent.add(debug_tab, text="调试参数")
# 使用scrollable_frame作为容器
debug_container = debug_scrollable_frame
# 调试图像
debug_captures_box = ttk.LabelFrame(debug_container, text="调试图像")
debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))
debug_r0 = ttk.Frame(debug_captures_box)
debug_r0.pack(fill=X, padx=10, pady=(10, 8))
ttk.Checkbutton(
debug_r0,
text="保存调试图像(OCR / 像素 / 模板等)",
variable=vars_["debug_captures_enabled_var"],
).pack(side=LEFT)
ttk.Checkbutton(
debug_r0,
text="异步保存调试图像(默认启用)",
variable=vars_["debug_captures_async_save_var"],
).pack(side=LEFT, padx=(10, 0))
ttk.Checkbutton(
debug_r0,
text="保存完成后记录日志(显示路径)",
variable=vars_["debug_captures_log_on_complete_var"],
).pack(side=LEFT, padx=(10, 0))
# 异步保存计数显示与重置
debug_counts_frame = ttk.Frame(debug_r0)
debug_counts_frame.pack(side=LEFT, padx=(10, 0))
ttk.Label(debug_counts_frame, text="异步保存:").pack(side=LEFT)
ttk.Label(
debug_counts_frame, textvariable=vars_["debug_async_success_var"], foreground="green"
).pack(side=LEFT, padx=(4, 8))
ttk.Label(debug_counts_frame, text="/").pack(side=LEFT)
ttk.Label(
debug_counts_frame, textvariable=vars_["debug_async_failure_var"], foreground="red"
).pack(side=LEFT, padx=(4, 8))
def on_reset_async_counters():
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.reset_async_save_counters()
vars_["debug_async_success_var"].set(0)
vars_["debug_async_failure_var"].set(0)
except Exception:
pass
ttk.Button(
debug_counts_frame, text="重置", command=on_reset_async_counters, width=6
).pack(side=LEFT, padx=(6, 0))
# 周期性更新计数器(2秒)
def _update_async_counters():
try:
from douyin.handlers import douyin_screenshot_manager
s, f = douyin_screenshot_manager.get_async_save_counters()
vars_["debug_async_success_var"].set(s)
vars_["debug_async_failure_var"].set(f)
except Exception:
pass
try:
debug_r0.after(2000, _update_async_counters)
except Exception:
pass
# 启动更新循环
try:
_update_async_counters()
except Exception:
pass
debug_cleanup_box = ttk.LabelFrame(debug_container, text="调试图像清理")
debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))
debug_r1 = ttk.Frame(debug_cleanup_box)
debug_r1.pack(fill=X, padx=10, pady=(10, 8))
ttk.Checkbutton(
debug_r1, text="启用自动清理调试图像", variable=vars_["debug_captures_auto_cleanup_var"]
).pack(side=LEFT)
debug_r2 = ttk.Frame(debug_cleanup_box)
debug_r2.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(debug_r2, text="保留天数:").pack(side=LEFT)
ttk.Spinbox(
debug_r2,
from_=1,
to=30,
increment=1,
textvariable=vars_["debug_captures_keep_days_var"],
width=6,
).pack(side=LEFT)
ttk.Label(debug_r2, text="最大文件数量:").pack(side=LEFT, padx=(20, 0))
ttk.Spinbox(
debug_r2,
from_=100,
to=10000,
increment=100,
textvariable=vars_["debug_captures_max_files_var"],
width=8,
).pack(side=LEFT)
ttk.Label(debug_r2, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0))
# 找福袋参数
fudai_find_box = ttk.LabelFrame(debug_container, text="找福袋参数")
fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))
row4 = ttk.Frame(fudai_find_box)
row4.pack(fill=X, padx=10, pady=(10, 8))
ttk.Label(row4, text="找福袋最大尝试次数:").pack(side=LEFT)
ttk.Spinbox(
row4,
from_=0,
to=50,
increment=1,
textvariable=vars_["fudai_find_max_attempts_var"],
width=6,
).pack(side=LEFT)
ttk.Label(row4, text="(0=使用默认值)").pack(side=LEFT, padx=(6, 0))
row4b = ttk.Frame(fudai_find_box)
row4b.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4b, text="找福袋重试间隔(秒):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.1,
to=3.0,
increment=0.1,
textvariable=vars_["fudai_icon_retry_delay_seconds_var"],
width=6,
).pack(side=LEFT)
ttk.Label(row4b, text=" 最大等待时间(秒):").pack(side=LEFT, padx=(10, 0))
ttk.Spinbox(
row4b,
from_=0.0,
to=30.0,
increment=0.5,
textvariable=vars_["fudai_icon_max_wait_seconds_var"],
width=6,
).pack(side=LEFT)
ttk.Label(row4b, text="(实际识别常见 4-6 秒)").pack(side=LEFT, padx=(6, 0))
row4d = ttk.Frame(fudai_find_box)
row4d.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4d, text="点击福袋后等待时间(秒):").pack(side=LEFT)
ttk.Spinbox(
row4d,
from_=0.5,
to=10.0,
increment=0.1,
textvariable=vars_["fudai_click_wait_seconds_var"],
width=6,
).pack(side=LEFT)
ttk.Label(row4d, text="(等待福袋详情页加载,默认1.0秒)").pack(
side=LEFT, padx=(6, 0)
)
row4c = ttk.Frame(fudai_find_box)
row4c.pack(fill=X, padx=10, pady=(0, 8))
ttk.Checkbutton(
row4c,
text="禁用福袋内容OCR识别",
variable=vars_["fudai_disable_content_recognition_var"],
onvalue=True,
offvalue=False,
).pack(side=LEFT)
ttk.Label(row4c, text="(仅影响 content OCR,不改其它识别模块)").pack(
side=LEFT, padx=(6, 0)
)
# 任务列表 OCR 开关
ttk.Checkbutton(
row4c,
text="禁用福袋任务列表OCR识别",
variable=vars_["fudai_disable_task_recognition_var"],
onvalue=True,
offvalue=False,
).pack(side=LEFT, padx=(12, 0))
row4e = ttk.Frame(fudai_find_box)
row4e.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT)
ttk.Spinbox(
row4e,
from_=0.0,
to=30.0,
increment=0.5,
textvariable=vars_["switch_room_wait_after_stage_diag_seconds_var"],
width=6,
).pack(side=LEFT)
ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack(
side=LEFT, padx=(6, 0)
)
row4c = ttk.Frame(fudai_find_box)
row4c.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(row4c, text="直播间检测阈值(白色像素比例):").pack(side=LEFT)
ttk.Spinbox(
row4c,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["live_room_match_threshold_var"],
width=6,
).pack(side=LEFT)
ttk.Label(
row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)"
).pack(side=LEFT, padx=(6, 0))
# 鼠标配置
mouse_config_box = ttk.LabelFrame(debug_container, text="鼠标配置")
mouse_config_box.pack(fill=X, padx=10, pady=(0, 10))
mouse_r1 = ttk.Frame(mouse_config_box)
mouse_r1.pack(fill=X, padx=10, pady=(10, 8))
ttk.Label(mouse_r1, text="滑动速度(毫秒):").pack(side=LEFT)
ttk.Spinbox(
mouse_r1,
from_=100,
to=2000,
increment=50,
textvariable=vars_["swipe_duration_ms_var"],
width=6,
).pack(side=LEFT)
ttk.Label(mouse_r1, text="(滑动持续时间,默认600ms,值越大滑动越慢)").pack(
side=LEFT, padx=(6, 0)
)
mouse_r2 = ttk.Frame(mouse_config_box)
mouse_r2.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(mouse_r2, text="上滑起始Y坐标:").pack(side=LEFT)
ttk.Spinbox(
mouse_r2,
from_=400,
to=2000,
increment=50,
textvariable=vars_["swipe_up_start_y_var"],
width=6,
).pack(side=LEFT)
ttk.Label(mouse_r2, text="结束Y坐标:").pack(side=LEFT, padx=(10, 0))
ttk.Spinbox(
mouse_r2,
from_=200,
to=1800,
increment=50,
textvariable=vars_["swipe_up_end_y_var"],
width=6,
).pack(side=LEFT)
ttk.Label(mouse_r2, text="(基准1080x2400,默认1200→600,距离600px)").pack(
side=LEFT, padx=(6, 0)
)
# 阶段诊断时间参数(用于调试)
diag_time_box = ttk.LabelFrame(debug_container, text="阶段诊断时间参数")
diag_time_box.pack(fill=X, padx=10, pady=(0, 10))
diag_time_r1 = ttk.Frame(diag_time_box)
diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))
ttk.Label(diag_time_r1, text="最大诊断时间(秒):").pack(side=LEFT)
ttk.Spinbox(
diag_time_r1,
from_=1.0,
to=60.0,
increment=1.0,
textvariable=vars_["stage_diag_max_time_var"],
width=8,
).pack(side=LEFT)
ttk.Label(diag_time_r1, text="每步最大耗时(秒):").pack(side=LEFT, padx=(12, 0))
ttk.Spinbox(
diag_time_r1,
from_=0.5,
to=30.0,
increment=0.5,
textvariable=vars_["stage_diag_max_step_time_var"],
width=8,
).pack(side=LEFT)
ttk.Label(diag_time_r1, text="(用于调试,延长检测时间)").pack(
side=LEFT, padx=(6, 0)
)
diag_time_r2 = ttk.Frame(diag_time_box)
diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))
ttk.Checkbutton(
diag_time_r2, text="详细阶段诊断日志", variable=vars_["stage_diag_verbose_var"]
).pack(side=LEFT)
ttk.Checkbutton(
diag_time_r2, text="启用OCR模式1(二值化)", variable=vars_["enable_ocr_mode1_var"]
).pack(side=LEFT, padx=(20, 0))
diag_time_r2b = ttk.Frame(diag_time_box)
diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))
ttk.Checkbutton(
diag_time_r2b,
text="启用福袋模板匹配",
variable=vars_["fudai_template_match_enabled_var"],
).pack(side=LEFT)
diag_time_r3 = ttk.Frame(diag_time_box)
diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(diag_time_r3, text="福袋模板匹配阈值:").pack(side=LEFT)
ttk.Spinbox(
diag_time_r3,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["fudai_template_match_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(diag_time_r3, text="(0.0-1.0,彩色匹配)").pack(side=LEFT, padx=(6, 0))
diag_time_r3b = ttk.Frame(diag_time_box)
diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(diag_time_r3b, text="福袋详情页模板匹配阈值:").pack(side=LEFT)
ttk.Spinbox(
diag_time_r3b,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["fudai_detail_template_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(
diag_time_r3b, text="(0.0-1.0,默认0.7,区域(398,894)-(658,1179))"
).pack(side=LEFT, padx=(6, 0))
diag_time_r4 = ttk.Frame(diag_time_box)
diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(diag_time_r4, text="开奖页红色占比阈值:").pack(side=LEFT)
ttk.Spinbox(
diag_time_r4,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["lucky_draw_red_ratio_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(diag_time_r4, text="(默认0.90,≥此占比判定开奖页)").pack(
side=LEFT, padx=(6, 0)
)
# 更多模板匹配阈值
diag_time_r5 = ttk.Frame(diag_time_box)
diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))
ttk.Label(diag_time_r5, text="优惠券模板匹配阈值:").pack(side=LEFT)
ttk.Spinbox(
diag_time_r5,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["coupon_template_match_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(diag_time_r5, text="(默认0.75,用于检测优惠券弹窗)").pack(
side=LEFT, padx=(6, 0)
)
# 像素检测阈值
pixel_detect_box = ttk.LabelFrame(debug_container, text="像素检测阈值")
pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))
pixel_r1 = ttk.Frame(pixel_detect_box)
pixel_r1.pack(fill=X, padx=10, pady=(10, 6))
ttk.Label(pixel_r1, text="参与按钮红色占比阈值:").pack(side=LEFT)
ttk.Spinbox(
pixel_r1,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["attend_button_red_ratio_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(pixel_r1, text="(默认0.25,用于检测参与按钮)").pack(
side=LEFT, padx=(6, 0)
)
pixel_r2 = ttk.Frame(pixel_detect_box)
pixel_r2.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(pixel_r2, text="粉丝团加入红色占比阈值:").pack(side=LEFT)
ttk.Spinbox(
pixel_r2,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["fansclub_join_red_ratio_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(pixel_r2, text="(默认0.25,用于检测粉丝团加入按钮)").pack(
side=LEFT, padx=(6, 0)
)
pixel_r3 = ttk.Frame(pixel_detect_box)
pixel_r3.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(pixel_r3, text="购物红包背景红色占比阈值:").pack(side=LEFT)
ttk.Spinbox(
pixel_r3,
from_=0.0,
to=1.0,
increment=0.01,
textvariable=vars_["shopping_redpacket_red_ratio_threshold_var"],
width=8,
).pack(side=LEFT)
ttk.Label(pixel_r3, text="(默认0.15,用于检测购物红包弹窗背景)").pack(
side=LEFT, padx=(6, 0)
)
return debug_tab
-115
View File
@@ -1,115 +0,0 @@
"""筛选设置 Tab UI 创建逻辑(9 个 var)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 100 行的 widget 创建段。
"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, X
from typing import Dict
def setup_filter_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
filter_tab = ttk.Frame(parent)
parent.add(filter_tab, text="筛选设置")
cfg_box = ttk.LabelFrame(filter_tab, text="福袋筛选条件")
cfg_box.pack(fill=X, padx=10, pady=(10, 10))
row = ttk.Frame(cfg_box)
row.pack(fill=X, padx=10, pady=(10, 8))
ttk.Label(row, text="最低价值(元):").pack(side=LEFT)
ttk.Spinbox(
row,
from_=0,
to=99999,
increment=0.01,
format="%.2f",
textvariable=vars_["min_value_var"],
width=10,
).pack(side=LEFT)
rowp = ttk.Frame(cfg_box)
rowp.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(rowp, text="参与人数范围:").pack(side=LEFT)
ttk.Spinbox(
rowp,
from_=0,
to=99999999,
increment=1,
textvariable=vars_["min_participants_var"],
width=10,
).pack(side=LEFT)
ttk.Label(rowp, text=" ~ ").pack(side=LEFT)
ttk.Spinbox(
rowp,
from_=0,
to=99999999,
increment=1,
textvariable=vars_["max_participants_var"],
width=10,
).pack(side=LEFT)
ttk.Label(rowp, text="(填0表示不限制)").pack(side=LEFT)
row2 = ttk.Frame(cfg_box)
row2.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row2, text="倒计时小于(秒)时不参与:").pack(side=LEFT)
ttk.Spinbox(
row2, from_=0, to=300, increment=1, textvariable=vars_["skip_lt_seconds_var"], width=6
).pack(side=LEFT)
ttk.Label(row2, text="(剩余时间太短,不参与)").pack(side=LEFT, padx=(6, 0))
row3 = ttk.Frame(cfg_box)
row3.pack(fill=X, padx=10, pady=(0, 8))
ttk.Checkbutton(
row3, text="自动加入粉丝团(谨慎:可能消耗钻石)", variable=vars_["auto_join_var"]
).pack(side=LEFT)
row4 = ttk.Frame(cfg_box)
row4.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(row4, text="粉丝团失败策略:").pack(side=LEFT)
ttk.Combobox(
row4,
textvariable=vars_["fansclub_action_var"],
values=["stay", "switch"],
width=10,
state="readonly",
).pack(side=LEFT)
ttk.Label(row4, text="(stay=停留,switch=切换直播间)").pack(
side=LEFT, padx=(6, 0)
)
# 粉丝团等待/点击延迟设置
row4b = ttk.Frame(cfg_box)
row4b.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4b, text="粉丝团点击延迟(s):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.1,
to=5.0,
increment=0.1,
textvariable=vars_["fansclub_click_delay_var"],
width=6,
).pack(side=LEFT, padx=(6, 12))
ttk.Label(row4b, text="自动加入等待(s):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.5,
to=10.0,
increment=0.5,
textvariable=vars_["fansclub_auto_wait_var"],
width=6,
).pack(side=LEFT, padx=(6, 12))
ttk.Label(row4b, text="手动加入等待(s):").pack(side=LEFT)
ttk.Spinbox(
row4b,
from_=0.5,
to=10.0,
increment=0.5,
textvariable=vars_["fansclub_manual_wait_var"],
width=6,
).pack(side=LEFT, padx=(6, 0))
# 标签页3:高价值预约
return filter_tab
-39
View File
@@ -1,39 +0,0 @@
"""高价值房间 Tab 视图刷新逻辑。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_high_value_rooms``,
负责读 ``state/high_value_rooms.json`` 并以 JSON 格式渲染到 Tab。
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
"""
from __future__ import annotations
import json
import os
import tkinter as tk
def refresh_high_value_rooms(text_widget: tk.Text) -> None:
try:
from douyin.core.path_config import get_high_value_rooms_path
path = get_high_value_rooms_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
path = path_config.get_high_value_rooms_path()
try:
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
text_widget.delete("1.0", "end")
text_widget.insert(
"1.0", json.dumps(data, ensure_ascii=False, indent=2)
)
else:
text_widget.delete("1.0", "end")
text_widget.insert("1.0", "暂无高价值房间数据")
except Exception as e:
text_widget.delete("1.0", "end")
text_widget.insert("1.0", f"读取高价值房间失败:{e}")
-41
View File
@@ -1,41 +0,0 @@
"""关键词 Tab UI 创建逻辑(白名单 + 黑名单)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 18 行的 widget 创建段。
返回 ``(want_text, not_want_text)`` 两个 ScrolledText widget,供 main() 后续
绑定到 ``_config_io_texts`` 字典用于 load/save 配置。
"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from tkinter.constants import BOTH, X
from typing import Any, Tuple
def setup_keywords_tab(
parent: ttk.Notebook,
*,
ScrolledText_cls: Any,
) -> Tuple[tk.Text, tk.Text]:
"""构建关键词 Tab,返回 ``(want_text, not_want_text)``。"""
keywords_tab = ttk.Frame(parent)
parent.add(keywords_tab, text="关键词")
kw_box = ttk.LabelFrame(keywords_tab, text="关键词(每行一个)")
kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))
ttk.Label(kw_box, text="想要 contains_want(白名单,空=不限制)").pack(
anchor="w", padx=10, pady=(10, 4)
)
want_text = ScrolledText_cls(kw_box, height=6)
want_text.pack(fill=X, padx=10, pady=(0, 10))
ttk.Label(kw_box, text="不想要 contains_not_want(黑名单)").pack(
anchor="w", padx=10, pady=(0, 4)
)
not_want_text = ScrolledText_cls(kw_box, height=8)
not_want_text.pack(fill=X, padx=10, pady=(0, 10))
return want_text, not_want_text
-127
View File
@@ -1,127 +0,0 @@
"""左侧配置区:PanedWindow 布局 + 7 个配置 Tab + load/save_ui_to_config 闭包。
从 ``gui/gui_app.py`` 抽出。包括:
- ``ttk.PanedWindow`` (左/右分栏)
- 左侧 ``ttk.Notebook`` 容器
- 7 个配置 Tab(运行/筛选/高价值预约/养号/调试/日志/关键词)
- ``load_config_to_ui`` / ``save_ui_to_config`` / ``save_logging_config`` 闭包
- 启动时一次 ``load_config_to_ui()``
返回 ``LeftConfigArea`` 暴露给 ``main()`` 的引用:
- ``right_frame``: 右侧分栏(传给后续 setup_main_notebook)
- ``save_ui_to_config``: 保存配置回调
"""
from __future__ import annotations
import tkinter as tk
from dataclasses import dataclass
from tkinter import ttk
from tkinter.constants import BOTH
from typing import Any, Callable, Dict
from gui.components.config_io import (
load_config_to_ui as _load_config_to_ui_impl,
save_ui_to_config as _save_ui_to_config_impl,
)
from gui.components.logging_config_io import save_logging_config as _save_logging_config_impl
from gui.components.run_tab import setup_run_tab
from gui.components.filter_tab import setup_filter_tab
from gui.components.reservation_tab import setup_reservation_tab
from gui.components.yanghao_tab import setup_yanghao_tab
from gui.components.debug_tab import setup_debug_tab
from gui.components.logging_tab import setup_logging_tab
from gui.components.keywords_tab import setup_keywords_tab
@dataclass
class LeftConfigArea:
"""``main()`` 后续仍要用的引用。"""
right_frame: ttk.Frame
save_ui_to_config: Callable[[], None]
def setup_left_config_area(
root: tk.Misc,
*,
vars_: Dict[str, tk.Variable],
cfg: dict,
ScrolledText_cls: Any,
read_config: Callable[[], dict],
write_config: Callable[[dict], None],
on_line: Callable[[str], None],
) -> LeftConfigArea:
"""构建左侧配置区(PanedWindow + 7 Tabs + load/save 闭包)。
``cfg`` 由调用方传入,``load_config_to_ui`` 内部把读到的新 cfg 重新赋回
``cfg`` dict 的内容(不能 reassign 局部 var,所以用 ``dict.clear() + update``)。
"""
# 中部:左侧配置(使用 Notebook 标签页) + 右侧日志/预览(支持拖拽调整宽度)
mid = ttk.PanedWindow(root, orient="horizontal")
mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))
left_wrap = ttk.Frame(mid)
right_frame = ttk.Frame(mid)
mid.add(left_wrap, weight=0) # 左侧配置区域
mid.add(right_frame, weight=1) # 右侧日志/预览区域
# 左侧使用 Notebook 标签页组织配置
left_notebook = ttk.Notebook(left_wrap)
left_notebook.pack(fill=BOTH, expand=True)
def save_logging_config() -> None:
_save_logging_config_impl(
vars_=vars_,
read_config=read_config,
write_config=write_config,
on_line=on_line,
)
# 创建左侧配置标签页
setup_run_tab(left_notebook, vars_=vars_)
setup_filter_tab(left_notebook, vars_=vars_)
setup_reservation_tab(left_notebook, vars_=vars_)
_, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text = setup_yanghao_tab(
left_notebook, vars_=vars_,
)
setup_debug_tab(left_notebook, vars_=vars_)
setup_logging_tab(left_notebook, vars_=vars_, on_save_logging=save_logging_config)
want_text, not_want_text = setup_keywords_tab(
left_notebook, ScrolledText_cls=ScrolledText_cls,
)
texts_ = {
"not_want_text": not_want_text,
"want_text": want_text,
"yg_comment_texts": yg_comment_texts,
"yg_fav_keywords_text": yg_fav_keywords_text,
"yg_like_keywords_text": yg_like_keywords_text,
}
def load_config_to_ui() -> None:
# cfg 是 dict 的 alias,我们替换它的内容(不 reassign 否则丢失 main 的引用)
new_cfg = _load_config_to_ui_impl(
vars_=vars_,
texts_=texts_,
read_config=read_config,
)
cfg.clear()
cfg.update(new_cfg)
def save_ui_to_config() -> None:
_save_ui_to_config_impl(
vars_=vars_,
texts_=texts_,
cfg=cfg,
read_config=read_config,
write_config=write_config,
on_line=on_line,
)
load_config_to_ui()
return LeftConfigArea(
right_frame=right_frame,
save_ui_to_config=save_ui_to_config,
)
-56
View File
@@ -1,56 +0,0 @@
"""GUI 日志管道工厂:queue + 线程安全文件写入 + Runner 集成。
从 ``gui/gui_app.py`` 抽出 on_line 闭包及其依赖。
"""
from __future__ import annotations
import logging
import queue
from typing import Any, Callable, Tuple
from gui.gui_core import Runner
from gui.components.log_writer import ThreadSafeLogWriter
_LOGGER = logging.getLogger("gui.gui_app")
def _format_gui_log_line(line: str) -> str:
"""将完整日志行转换为 GUI 显示用的精简版本。
实际实现位于 ``gui.components.log_viewer``,失败时回退到原始字符串。
"""
try:
from gui.components.log_viewer import format_gui_log_line as _impl
return _impl(line)
except Exception:
return (line or "").rstrip("\n")
def setup_log_pipeline() -> Tuple["queue.Queue[str]", Any, Callable[[str], None], Any]:
"""构建 log queue + ThreadSafeLogWriter + on_line + Runner。
返回 ``(q, log_writer, on_line, runner)``,主程序后续把 ``runner`` 传入按钮回调,
把 ``q`` 传入 ``pump_logs`` 用于 GUI 端消费。
"""
q: "queue.Queue[str]" = queue.Queue()
log_writer = ThreadSafeLogWriter()
def on_line(line: str) -> None:
"""处理日志行:GUI 显示用精简版本,文件写入用完整版本"""
# GUI 显示:使用精简后的版本
try:
display_line = _format_gui_log_line(line)
except Exception:
display_line = line
q.put(display_line)
# 文件:写入完整日志行(不做精简处理)
try:
log_writer.write(line)
except Exception:
pass # 文件写入失败不应影响GUI显示
runner = Runner(on_line=on_line)
return q, log_writer, on_line, runner
-143
View File
@@ -1,143 +0,0 @@
"""GUI 日志泵: 把后台线程发来的日志行批量插入到日志 Text widget。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``pump_logs``,
通过 ``root.after(100, pump_logs)`` 自递归调度。
依赖通过显式参数注入:
- ``log_queue`` - 后台线程往里塞日志行的 ``queue.Queue``
- ``text_widget`` - 展示用的 Text/ScrolledText
- ``filter_getter`` - ``() -> str`` 返回筛选关键字(已 strip)
- ``theme_getter`` - ``() -> str`` 返回当前主题名
- ``root`` - 主窗口(用于自递归 ``after``)
- ``is_running_getter`` - ``() -> bool`` 返回 runner 是否还在跑
- ``status_getter`` - ``() -> str`` 读取状态文本
- ``status_setter`` - ``(str) -> None`` 写入状态文本
"""
from __future__ import annotations
import logging
import queue
import re
import tkinter as tk
from typing import Callable
try:
from gui.components.log_color_config import (
apply_operation_color,
get_operation_type,
)
except ImportError:
def get_operation_type(line: str): # type: ignore[no-redef]
return None
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
pass
_LOGGER = logging.getLogger("gui.gui_app")
def pump_logs(
log_queue: "queue.Queue[str]",
*,
text_widget: tk.Text,
filter_getter: Callable[[], str],
theme_getter: Callable[[], str],
root: tk.Misc,
is_running_getter: Callable[[], bool],
status_getter: Callable[[], str],
status_setter: Callable[[str], None],
) -> None:
changed = False
try:
# 获取当前主题(用于颜色配置)
try:
current_theme = theme_getter()
except Exception:
current_theme = "litera"
while True:
line = log_queue.get_nowait()
# 运行日志关键字筛选(与行为日志一致)
try:
kw = filter_getter()
if kw and kw not in line:
continue
except Exception:
pass
try:
# 插入日志行并应用颜色标签
start_pos = text_widget.index("end-1c")
# 插入文本
text_widget.insert("end", line + "\n")
end_pos = text_widget.index("end-1c")
# 优先级1: 先检查操作类型颜色(更具体)
op_type_applied = False
try:
op_type = get_operation_type(line)
if op_type:
apply_operation_color(
text_widget, start_pos, end_pos, line, current_theme
)
op_type_applied = True
except Exception:
pass # 忽略操作类型颜色应用失败
# 优先级2: 再检查日志级别标签(作为补充,如果操作类型未匹配)
# 只有在没有操作类型颜色时才应用级别标签
if not op_type_applied:
try:
tag = None
if "[INFO]" in line:
tag = "log_info"
elif "[WARNING]" in line:
tag = "log_warning"
elif "[ERROR]" in line:
tag = "log_error"
elif "[CRITICAL]" in line:
tag = "log_critical"
elif "elapsed_seconds=" in line or "耗时" in line:
tag = "log_performance"
elif re.search(r"\[[\w\.]+\]", line):
tag = "log_module"
if tag:
text_widget.tag_add(tag, start_pos, end_pos)
except Exception:
pass # 忽略级别标签应用失败
# 不再自动滚动到底部,让用户自由控制滚动位置
changed = True
except Exception as e:
# 如果插入日志失败,至少记录到 logger(调试用)
_LOGGER.error("[GUI日志错误] 无法插入日志: %s", e)
except queue.Empty:
pass
except Exception as e:
# 捕获其他异常,确保日志循环不会中断
_LOGGER.error("[GUI日志错误] pump_logs异常: %s", e)
try:
if changed and not is_running_getter() and status_getter() == "运行中":
status_setter("已结束")
except Exception:
pass
# 确保递归调用始终执行,即使前面出现异常
try:
root.after(100, lambda: pump_logs(
log_queue,
text_widget=text_widget,
filter_getter=filter_getter,
theme_getter=theme_getter,
root=root,
is_running_getter=is_running_getter,
status_getter=status_getter,
status_setter=status_setter,
)) # type: ignore[arg-type]
except Exception as e:
# 如果 root 已被销毁,停止日志循环
_LOGGER.warning("[GUI日志错误] 无法调度下次日志更新: %s", e)
-134
View File
@@ -1,134 +0,0 @@
"""运行日志 Tab 的搜索工具栏(关键字筛选 + 文本搜索)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的搜索栏 widget 创建段 +
5 个共享 ``nonlocal`` matches state 的搜索闭包。
抽出后用一个 ``LogSearchToolbarHandles`` namedtuple 暴露 main 仍要用的引用:
- ``log_filter_var`` - 关键字筛选 StringVar(被 refresh_run_log/auto_refresh 用)
- ``refresh_run_log`` - 刷新回调(被 root.after 调度用)
"""
from __future__ import annotations
import tkinter as tk
from dataclasses import dataclass
from tkinter import ttk
from tkinter.constants import LEFT, X, Y
from typing import Any, Callable
from gui.components.run_log_view import refresh_run_log as _refresh_run_log_impl
from gui.components.text_search import generic_search_widget
@dataclass
class LogSearchToolbarHandles:
"""``main()`` 后续仍要用的 handles。"""
log_filter_var: tk.StringVar
refresh_run_log: Callable[[], None]
def setup_log_search_toolbar(
parent: tk.Misc,
*,
log_text: tk.Text,
runner: Any,
theme_getter: Callable[[], str],
) -> LogSearchToolbarHandles:
"""构建运行日志 Tab 顶部的搜索工具栏。
依赖通过显式参数注入:
- ``parent`` - 工具栏父容器(``log_box``)
- ``log_text`` - 日志文本 widget(搜索高亮 + 内容刷新的目标)
- ``runner`` - 运行控制器(暴露 ``_lock`` / ``_log`` 给刷新回调)
- ``theme_getter`` - ``() -> str`` 返回当前 GUI 主题名
"""
log_search_frame = ttk.Frame(parent)
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
# 关键字筛选(与行为日志一致)
log_filter_var = tk.StringVar(value="")
ttk.Label(log_search_frame, text="筛选:").pack(side=LEFT)
ttk.Entry(log_search_frame, textvariable=log_filter_var, width=16).pack(
side=LEFT, padx=(0, 8)
)
log_search_var = tk.StringVar(value="")
log_search_entry = ttk.Entry(
log_search_frame, textvariable=log_search_var, width=20
)
def refresh_run_log() -> None:
_refresh_run_log_impl(
runner,
text_widget=log_text,
filter_getter=lambda: log_filter_var.get().strip(),
theme_getter=theme_getter,
)
# 搜索状态用可变容器持有,5 个内层闭包共享。
state = {
"matches": [],
"current_index": -1,
}
def search_in_log_text(direction: int = 1) -> None:
"""在运行日志中搜索文本(调用通用搜索实现)"""
state["current_index"] = generic_search_widget(
log_text,
log_search_var,
state["matches"],
state["current_index"],
direction,
)
def search_next_in_log() -> None:
"""搜索下一个"""
search_in_log_text(1)
def search_prev_in_log() -> None:
"""搜索上一个"""
search_in_log_text(-1)
def clear_search_in_log() -> None:
"""清除搜索高亮"""
log_search_var.set("")
log_text.tag_remove("search_highlight", "1.0", "end")
log_text.tag_remove("search_current", "1.0", "end")
state["matches"] = []
state["current_index"] = -1
# 绑定回车键搜索
def on_log_search_entry_key(event):
if event.keysym == "Return":
search_next_in_log()
log_search_entry.bind("<KeyPress>", on_log_search_entry_key)
# 将 刷新 放在筛选后面,搜索区域与行为日志一致(带分隔条)
ttk.Button(log_search_frame, text="刷新", command=refresh_run_log).pack(
side=LEFT, padx=(0, 8)
)
ttk.Separator(log_search_frame, orient="vertical").pack(
side=LEFT, fill=Y, padx=5, pady=3
)
ttk.Label(log_search_frame, text="搜索:").pack(side=LEFT)
# 把搜索输入框放在分隔符后
log_search_entry.pack(side=LEFT, padx=(0, 5))
ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(
side=LEFT, padx=(0, 2)
)
ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(
side=LEFT, padx=(0, 2)
)
ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(
side=LEFT, padx=(0, 2)
)
ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(
side=LEFT, padx=(0, 5)
)
return LogSearchToolbarHandles(
log_filter_var=log_filter_var,
refresh_run_log=refresh_run_log,
)
-61
View File
@@ -1,61 +0,0 @@
"""运行日志 Tab 的 widget 创建段(log_box + log_text + 搜索工具栏 + 配色)。
从 ``gui/gui_app.py`` 抽出。返回 ``LogTabHandles`` 暴露给 ``main()`` 后续 pump_logs。
"""
from __future__ import annotations
import tkinter as tk
from dataclasses import dataclass
from tkinter import ttk
from tkinter.constants import BOTH
from typing import Any, Callable
from gui.components.log_search_toolbar import (
setup_log_search_toolbar,
LogSearchToolbarHandles,
)
from gui.components.log_text_colors import configure_log_text_colors
@dataclass
class LogTabHandles:
"""``main()`` 后续仍要用的 handles。"""
log_text: tk.Text
log_filter_var: tk.StringVar
refresh_run_log: Callable[[], None]
def setup_log_tab(
log_tab: tk.Misc,
*,
runner: Any,
ScrolledText_cls: Any,
theme_getter: Callable[[], str],
) -> LogTabHandles:
"""构建运行日志 Tab(log_box + log_text + 搜索工具栏 + 配色)。"""
log_box = ttk.Frame(log_tab)
log_box.pack(fill=BOTH, expand=True)
log_text = ScrolledText_cls(log_box)
try:
log_text.configure(font=("Consolas", 10))
except Exception:
pass
log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
handles: LogSearchToolbarHandles = setup_log_search_toolbar(
log_box,
log_text=log_text,
runner=runner,
theme_getter=theme_getter,
)
configure_log_text_colors(log_text, theme_getter=theme_getter)
return LogTabHandles(
log_text=log_text,
log_filter_var=handles.log_filter_var,
refresh_run_log=handles.refresh_run_log,
)
-97
View File
@@ -1,97 +0,0 @@
"""运行日志 widget 的主题颜色配置。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的内联段,根据当前 GUI 主题
为 log_text 配置背景/前景色 + 多种 log_xxx 标签 + 操作类型颜色标签。
依赖通过显式参数注入:
- ``text_widget`` - 待配置的 Text/ScrolledText
- ``theme_getter`` - ``() -> str`` 返回当前主题名
"""
from __future__ import annotations
import tkinter as tk
from typing import Callable
try:
from gui.components.log_color_config import get_color_config
except ImportError:
def get_color_config(theme: str = "litera"): # type: ignore[no-redef]
return {}
def configure_log_text_colors(
text_widget: tk.Text,
*,
theme_getter: Callable[[], str],
) -> None:
# 配置日志颜色标签(如果支持颜色)
try:
# 根据主题调整日志颜色(明亮主题使用深色文字/蓝色系)
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
try:
current_theme = theme_getter()
except Exception:
current_theme = "litera"
if current_theme in light_themes:
# 明亮主题 - 使用更适合人眼观看的颜色组合
text_widget.configure(
background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C"
)
text_widget.tag_configure("log_timestamp", foreground="#8B8B8B") # 柔和的灰色
text_widget.tag_configure(
"log_info", foreground="#1E88E5"
) # 明亮的蓝色,易于阅读
text_widget.tag_configure(
"log_warning", foreground="#F57C00"
) # 橙色,警告色但不过于刺眼
text_widget.tag_configure(
"log_error", foreground="#D32F2F"
) # 深红色,醒目但不刺眼
text_widget.tag_configure(
"log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold")
) # 加粗深红色
text_widget.tag_configure(
"log_performance", foreground="#388E3C"
) # 深绿色,性能指标
text_widget.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识
else:
# 暗色主题 - 优化对比度和可读性
text_widget.configure(
background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF"
)
text_widget.tag_configure(
"log_timestamp", foreground="#A0A0A0"
) # 浅灰色时间戳
text_widget.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级
text_widget.tag_configure(
"log_warning", foreground="#FFB74D"
) # 金色警告,暗色背景下醒目
text_widget.tag_configure(
"log_error", foreground="#EF5350"
) # 亮红色,错误突出
text_widget.tag_configure(
"log_critical", foreground="#F44336", font=("Consolas", 10, "bold")
) # 加粗亮红色
text_widget.tag_configure(
"log_performance", foreground="#81C784"
) # 亮绿色,性能数据
text_widget.tag_configure(
"log_module", foreground="#BA68C8"
) # 亮紫色,模块标识
# 配置操作类型颜色标签(使用模块化配置)
try:
color_config = get_color_config(current_theme)
for op_type, colors in color_config.items():
tag_name = f"op_{op_type}"
text_widget.tag_configure(
tag_name,
foreground=colors["foreground"],
background=colors["background"],
)
except Exception:
pass # 忽略操作类型颜色配置失败
except Exception:
pass # 忽略标签配置失败
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more