Author SHA1 Message Date
CodexandClaude Opus 4.7 273adbb677 refactor(finder): 抽 check_have_fudai_with_ready_screenshot 中"截图获取+加载+失败处理"块到 finder_screenshot
将循环每次的截图相关逻辑(约 78 行)抽到 3 个独立 helper:
- capture_screenshot_for_loop:每次循环开始时获取截图(_shot_and_diagnose + 文件验证 + 兜底)
- load_screenshot_with_retry:读取截图,失败时重新截图后重试,返回 PIL Image 或 None
- handle_screenshot_load_failure:连续失败超阈值返回 "break";否则等待后返回 "continue"

finder.py: 371 → 320 行 (-51)
新增 finder_screenshot.py: 111 行

finder.py 跌破 350 行(1438 → 320,本会话累计削减 1118 行 = -78%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:18:35 +08:00
CodexandClaude Opus 4.7 7aeb0c881c style(finder): 删除 numpy_band_scan 抽取时遗留的重复注释行
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:15:59 +08:00
CodexandClaude Opus 4.7 0629906449 refactor(reservation): 抽 process_reservation_attend_window 中 3 个独立块到 helper
- calculate_dynamic_ahead:计算动态提前量 + 估计回退步数(约 32 行 → 4 行调用)
- log_target_reservation_info:记录目标预约的详细信息日志(约 19 行 → 1 行调用)
- is_queue_full_immediate_attend_mode:检查并记录"队列满立即参与模式"状态(约 22 行 → 1 行调用)

attend_window.py: 293 → 231 行 (-62)
attend_window_helpers.py: 1143 → 1234 行

attend_window.py 跌破 250 行(1437 → 231,本会话累计削减 1206 行 = -84%)
process_reservation_attend_window 函数从约 376 → 215 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:12:02 +08:00
CodexandClaude Opus 4.7 5355e52b06 refactor(reservation): 抽 process_reservation_attend_window 入口检查序列到 process_attend_window_entry_checks
将 110+ 行的入口检查序列抽到 helper:
1. 写函数入口日志
2. 检查是否正在等待预约福袋开奖(如是则跳过)
3. 检查预约队列是否为空
4. 写"开始队列排序"日志
5. 超时检查(排序前)
6. 排序队列(_sort_reservations_inplace)
7. 写"队列排序完成"日志

返回值约定:
- True:所有检查通过,调用方继续后续流程
- False:触发了早返回,调用方应直接 return False

attend_window.py: 405 → 293 行 (-112)
attend_window_helpers.py: 994 → 1143 行

attend_window.py 跌破 300 行(1437 → 293,本会话累计削减 1144 行 = -80%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:09:32 +08:00
CodexandClaude Opus 4.7 8da7dcc819 refactor(finder): 抽 finder.py 中 3 个循环调试日志块到 finder_loop_logging
将 3 个独立的日志记录块抽到独立模块:
- log_fudai_found_and_metrics(约 52 行):命中后写"进入直播间→找到福袋"耗时统计 + 命中调试
- log_loop_progress(约 26 行):每 3 次循环记录一次轻量调试信息
- log_no_fudai_found(约 13 行):未找到时记录总耗时与循环次数

finder.py: 435 → 372 行 (-63)
新增 finder_loop_logging.py: 131 行

finder.py 跌破 400 行(1438 → 372,本会话累计削减 1066 行 = -74%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:05:44 +08:00
CodexandClaude Opus 4.7 2594788a8c refactor(stage): 抽 diagnose_stage_from_current_screen 步骤0"并行像素检测+详情日志"块到独立模块
将 204 行的"并行像素检测 + 详情日志记录"块抽到 douyin_stage_step0.py:run_parallel_pixel_detection。
逻辑:
- 调用 _read_pixel_stage_state 并行采集所有像素特征
- 检查直播间图标像素(白色比例 >= 阈值则判定在直播间)
- 兜底:检测到抽奖结果弹窗也视为在直播间
- 记录每个检测项的详细信息(耗时、分数、阈值、任务数量等)
- 写整体并行检测完成日志

返回 (pixel_state, pixel_details, in_live_room, live_room_score, detection_method) 五元组。

douyin_stage.py: 462 → 273 行 (-189)
新增 douyin_stage_step0.py: 231 行

douyin_stage.py 跌破 300 行(1385 → 273,本会话累计削减 1112 行 = -80%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:01:28 +08:00
CodexandClaude Opus 4.7 1801e50a4c refactor(fudai): 抽 attend_choujiang 中"按钮状态推断 + 并行 OCR 缓存复用"块到 resolve_attend_button_text
将 122 行的"按钮状态解析"逻辑抽到 fudai_attend_branches.resolve_attend_button_text。
逻辑:
- 优先级1:已有的 _fudai_button_text/_fudai_button_status(并行 OCR 设置)
- 优先级2:缺失则从 button_text_raw / 映射表中查找候选 + 推断状态
- 优先级3:检查 OCR 时间戳——5 秒内有效;超时但同房间则复用

返回 attend_button_text(不可用则空字符串)。

fudai_attend.py: 246 → 134 行 (-112)
fudai_attend_branches.py: 366 → 496 行

attend_choujiang 函数从 232 → 120 行
fudai_attend.py 跌破 150 行(1629 → 134,本会话累计削减 1495 行 = -92%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:57:24 +08:00
CodexandClaude Opus 4.7 e5f7434034 style(fudai): 整理 run_once_basic:合并 10 个 import 到方法顶部 + 简化注释
将 run_once_basic 中分散在各早返回前的 10 个独立 import 语句合并到方法顶部
统一导入;删除冗余的旧"主循环 / 直接参与标志"注释。

行为不变。

douyin_fudai.py: 624 → 595 行 (-29)

run_once_basic 函数从 95 → 66 行(纯协调器,10 个 try_xxx 早返回 + 1 个 dispatch_stage)

douyin_fudai.py 跌破 600 行(4121 → 595,本会话累计削减 3526 行 = -86%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:52:29 +08:00
CodexandClaude Opus 4.7 ee6ce26338 refactor(fudai): 抽 _handle_in_fudai_detail 步骤3+4 协调到 step3_step4_coordinator
将"状态分发 + 验证 + 参与决策"组合(约 67 行)抽到
fudai_detail_helpers.step3_step4_coordinator:
- dispatch_last_fudai_detail_status
- 重置 _fudai_detail_consecutive_failures
- validate_detail_or_skip
- extract_future_ts_from_detail
- 写步骤3完成日志
- basic_join_decision → handle_attend_success_post_processing

douyin_fudai.py: 683 → 624 行 (-59)
fudai_detail_helpers.py: 3251 → 3306 行

douyin_fudai.py 跌破 650 行(4121 → 624,本会话累计削减 3497 行 = -85%)
_handle_in_fudai_detail 从 97 → 38 行,run_once_basic 95 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:50:06 +08:00
CodexandClaude Opus 4.7 61e37f6644 refactor(fudai): 抽 run_once_basic 步骤 0.1 完整预约检查块到 run_reservation_check_block
将"开始预约检查 + 初始化队列 + 状态日志 + 高价值预约处理 + 完成日志"组合
约 35 行抽到 fudai_detail_helpers.run_reservation_check_block。

返回值约定:
- True:触发了早返回(队列满等待 / 所有预约完成重置),调用方应直接 return
- False:未触发,调用方继续

douyin_fudai.py: 712 → 683 行 (-29)
fudai_detail_helpers.py: 3213 → 3251 行

douyin_fudai.py 跌破 700 行(4121 → 683,本会话累计削减 3438 行 = -83%)
run_once_basic 函数从 124 → 95 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:47:44 +08:00
CodexandClaude Opus 4.7 48d78147b5 refactor(fudai): 进一步拆 __init__ 到 4 个 helper(基础状态/日志基础设施/诊断超时状态/预约运行时状态)
将 __init__ 中剩余的 4 个独立初始化块抽到 helper:
- init_basic_state:device/分辨率/计数器/operation/config_path(约 11 行)
- init_log_infra:_run_id / _log_seq / _log_kv 闭包(约 24 行)
- init_diag_timeout_state:阶段诊断 + 30分钟超时状态(约 11 行)
- init_reservation_runtime_state:预约运行时状态字段(约 22 行)

douyin_fudai.py: 775 → 712 行 (-63)
fudai_init_defaults.py: 210 → 287 行

douyin_fudai.py 跌破 750 行(4121 → 712,本会话累计削减 3409 行 = -83%)
__init__ 函数从 109 → 46 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:45:51 +08:00
CodexandClaude Opus 4.7 df8942e7b8 refactor(fudai): 抽 _handle_in_fudai_detail 步骤1/2 分发到 step1_or_step2_dispatcher
将"is_second_open True/False 分发"块(约 44 行)整段抽到 helper:
- True:检查保存的详情,有效则直接参与;无则 reread_fudai_detail_fallback 兜底
- False:调用 handle_first_open_step2 完整流程

返回 (detail, skip, skip_reason) 或 None(已早返回)。

douyin_fudai.py: 809 → 775 行 (-34)
fudai_detail_helpers.py: 3174 → 3213 行

douyin_fudai.py 跌破 800 行(4121 → 775,本会话累计削减 3346 行 = -81%)
_handle_in_fudai_detail 从 131 → 96 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:43:35 +08:00
CodexandClaude Opus 4.7 2899c932c4 refactor(fudai): 抽 __init__ 中"日志系统初始化 + 映射表清理 + 运行时状态标志"块到 fudai_init_defaults
将 __init__ 中 3 个独立的初始化块抽到 helper:
- init_logging_system:MDC trace_id + _std_logger 配置(约 28 行)
- cleanup_old_room_pos_map_files:删除 JSON/CSV/MD 旧导出(约 18 行)
- init_runtime_state_flags:运行时状态标志初始化(约 28 行)

douyin_fudai.py: 870 → 809 行 (-61)
fudai_init_defaults.py: 132 → 210 行

douyin_fudai.py 跌破 850 行(4121 → 809,本会话累计削减 3312 行 = -80%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:40:48 +08:00
CodexandClaude Opus 4.7 5383bbc131 refactor(fudai): 抽 _handle_in_fudai_detail 步骤2"第一次打开"整段到 handle_first_open_step2
将 90 行的"第一次打开(数据读取 + 验证 + 筛选检查 + 保存详情)"整段抽到
fudai_detail_helpers.handle_first_open_step2。

返回值约定:
- (detail, skip, skip_reason) 三元组:流程通过,调用方继续步骤3+4
- None:已早返回(验证失败/筛选不通过/记录预约/详情无效)

douyin_fudai.py: 949 → 870 行 (-79)
fudai_detail_helpers.py: 3094 → 3174 行

douyin_fudai.py 跌破 900 行(4121 → 870,本会话累计削减 3251 行 = -79%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:38:12 +08:00
CodexandClaude Opus 4.7 2f21b2a0b4 refactor(fudai): 抽 _maybe_run_yanghao_during_run 实现到 maybe_run_yanghao_during_run
将"按间隔触发推荐页养号"逻辑(约 56 行)抽到 fudai_detail_helpers.maybe_run_yanghao_during_run。
跳过条件:interval <= 0 / 等待开奖 / 参与预约 / 有预约队列 /
预约焦点期内 / 距上次触发不足 interval。

类内方法保留薄包装。

douyin_fudai.py: 999 → 949 行 (-50)
fudai_detail_helpers.py: 3033 → 3094 行

douyin_fudai.py 跌破 950 行(4121 → 949,本会话累计削减 3172 行 = -77%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:36:05 +08:00
CodexandClaude Opus 4.7 acd8f5c387 refactor(fudai): 抽 fudai_choujiang 主循环到 run_loop_with_timeout
将 fudai_choujiang 中"定时模式 + 无限循环模式"主循环(约 78 行)抽到
fudai_choujiang_helpers.run_loop_with_timeout:
- 定时模式(wait_minutes > 0):在 N 分钟内反复跑 run_once_basic
- 无限模式(wait_minutes <= 0):直到 KeyboardInterrupt
- 异常时延迟 2s 后继续,每轮间延迟 1s

顺带删除了 fudai_choujiang 中无用的 try/pass/except 占位块。

douyin_fudai.py 跌破 1000 行(4121 → 999,本会话累计削减 3122 行 = -76%)

douyin_fudai.py: 1078 → 999 行 (-79)
fudai_choujiang_helpers.py: 97 → 167 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:33:05 +08:00
CodexandClaude Opus 4.7 42ef73a9ee refactor(fudai): 抽 fudai_analyse.swipe 实现到 swipe_with_fallback
将 swipe 方法体(约 60 行)抽到 fudai_detail_helpers.swipe_with_fallback。
逻辑:
- 首选 operation.swipe
- 失败回退到 douyin_swipe_ops._adb_swipe_direct
- 最后兜底记录"swipe 失败"日志

类内 swipe 方法保留薄包装。

douyin_fudai.py: 1132 → 1078 行 (-54)
fudai_detail_helpers.py: 2975 → 3033 行

douyin_fudai.py 跌破 1100 行(4121 → 1078,本会话累计削减 3043 行 = -74%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:30:39 +08:00
CodexandClaude Opus 4.7 6d5b2cfb15 refactor(fudai): 抽 run_once_basic 中"阶段分发"块到 dispatch_stage
将 100 行的 if/elif stage 分发链条整段抽到 fudai_detail_helpers.dispatch_stage:
- COUPON_POPUP → handle_coupon_popup
- SHOPPING_REDPACKET_POPUP → handle_shopping_redpacket_popup
- FANSCLUB_JOIN → handle_fansclub_join
- FUDai_DETAIL → analyser._handle_in_fudai_detail
- IN_LIVE_ROOM/LIVE_OR_UNKNOWN → handle_in_live_room_stage
- RECOMMEND_PAGE → handle_recommend_page
- FOLLOW_LIST/LIVE_LIST → reflash_zhibo
- FUDai_RESULT → handle_lottery_result_stage
- LIVE_CLOSED → swipe_up_to_next_live
- 其他 → 写"未匹配到特定阶段"日志

douyin_fudai.py: 1228 → 1132 行 (-96)
fudai_detail_helpers.py: 2890 → 2975 行

run_once_basic 函数从 220 → 124 行,主体只剩入口逻辑 + 7 个 try_xxx 早返回 + 1 个 dispatch_stage。
douyin_fudai.py 跌破 1200 行(4121 → 1132,本会话累计削减 2989 行 = -73%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:27:19 +08:00
CodexandClaude Opus 4.7 01034347f4 refactor(finder): 抽 check_have_fudai_with_ready_screenshot 中"numpy 加速水平带扫描"块到 finder_numpy_scan
将 127 行的 numpy 加速扫描块抽到独立模块。
使用 numpy 批量处理,从最优位置向左右两侧交替搜索福袋图标的特征颜色。

helper 接受 (analyser, detected, detected_x, pic_new, width, height, rx, ry,
y_pianyi_val, optimal_x_scaled),返回更新后的 (detected, detected_x)。

finder.py: 553 → 435 行 (-118)
新增 finder_numpy_scan.py: 156 行

finder.py 跌破 500 行(1438 → 435,本会话累计削减 1003 行 = -70%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:24:50 +08:00
CodexandClaude Opus 4.7 e3daeab024 refactor(finder): 抽 check_have_fudai_with_ready_screenshot 中"逐像素扫描兜底"块到 finder_pixel_scan
将 183 行的"numpy 未命中时的原始逐像素检查"块抽到独立模块。
保留了原代码"找到后退出外层 while 循环"的 break 语义(在调用方
检查返回的 detected 后 break)。

finder.py: 726 → 553 行 (-173)
新增 finder_pixel_scan.py: 207 行

finder.py 跌破 600 行(1438 → 553,本会话累计削减 885 行 = -62%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:22:20 +08:00
CodexandClaude Opus 4.7 411fd96804 refactor(finder): 抽 check_have_fudai_with_ready_screenshot 中"模板匹配兜底"块到 finder_template_match
将 226 行的"OpenCV 模板匹配兜底"独立块抽到独立模块。
当像素检测未命中时,调用 cv2.matchTemplate 在指定区域查找福袋图标。

helper 接受 (analyser, detected, detected_x, pic_new, width, height, rx, ry,
y_pianyi_val, loop) 参数,返回更新后的 (detected, detected_x)。

finder.py: 944 → 726 行 (-218)
新增 finder_template_match.py: 257 行

finder.py 跌破 800 行(1438 → 726,本会话累计削减 712 行 = -50%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:17:18 +08:00
CodexandClaude Opus 4.7 0bd71a5e76 refactor(stage): 抽 diagnose_stage_from_current_screen 中"步骤 1+1.5 福袋详情页/邀你抢红包"块到独立模块
将 313 行的"福袋详情页(任务数量像素检测)+ 邀你抢红包(OCR 检测)"块抽到
douyin_stage_step1.py:detect_fudai_detail_or_invite_redpacket。

逻辑:
- 从 pixel_details 提取任务数量并保存到 analyser._fudai_detail_task_count_from_stage
- has_fudai_detail=True → return ("FUDai_DETAIL", "任务数量检测确认")
- 否则在指定区域 OCR 检测"邀你抢红包"文字 → return ("FUDai_DETAIL", "OCR检测确认")
- 都未命中 → return None

依赖通过参数注入:analyser、pixel_state、pixel_details、trigger_reason、
max_step_time、diag_start、max_diag_time、log_fn/log_summary_fn/log_separator_fn、
preprocess_for_ocr。

douyin_stage.py: 757 → 462 行 (-295)
新增 douyin_stage_step1.py: 347 行

douyin_stage.py 跌破 500 行(1385 → 462,本会话累计削减 923 行 = -67%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:14:04 +08:00
CodexandClaude Opus 4.7 cec4a2d692 refactor(stage): 抽 diagnose_stage_from_current_screen 中"步骤1+1.5 抽奖结果/购物红包"块到独立模块
将"优先级1(抽奖结果弹窗 + 按钮 OCR 确认)"和"优先级1.5(购物红包弹窗 OCR)"
两个相邻的 priority 检测块(约 104 行)抽到 douyin_stage_priority.py:
detect_lottery_or_redpacket_popup。

返回值约定:
- (stage, reason) 二元组:检测到弹窗时
- None:未检测到,调用方继续后续流程

依赖通过参数注入:analyser、pixel_state、max_step_time、diag_start、
max_diag_time、log_fn/log_summary_fn/log_separator_fn、preprocess_for_ocr。

douyin_stage.py: 845 → 757 行 (-88)
新增 douyin_stage_priority.py: 137 行

douyin_stage.py 跌破 800 行(1385 → 757,本会话累计削减 628 行 = -45%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:11:56 +08:00
CodexandClaude Opus 4.7 ca071250be refactor(stage): 抽 diagnose_stage_from_current_screen 中"步骤3 OCR 检测推荐页/关注列表/直播列表"块到独立模块
将 280 行的"OCR 标签栏检测"独立块抽到 douyin_stage_step3.py:detect_tab_pages_via_ocr。
逻辑:
- OCR 检测推荐页标签栏(启用 enable_ocr_mode1 时跑模式 0+1)
- 命中"推荐" → return RECOMMEND_PAGE
- 命中"关注"但没"推荐" → 精确截图 FOLLOW_TAB → return FOLLOW_LIST
- 命中"直播" → 精确截图 LIVE_LIST_TAB → return LIVE_LIST
- 都没命中 → return IN_LIVE_ROOM(默认)

依赖通过参数注入:analyser、enable_ocr_mode1、max_step_time、diag_start、
max_diag_time、log_fn、log_summary_fn、log_separator_fn、preprocess_for_ocr。

douyin_stage.py: 1111 → 845 行 (-266)
新增 douyin_stage_step3.py: 314 行

douyin_stage.py 跌破 900 行(1385 → 845,本会话累计削减 540 行 = -39%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:09:39 +08:00
CodexandClaude Opus 4.7 398133bbb0 refactor(reservation): 抽 process_reservation_attend_window 中"if ok 整段后处理"块到 process_seek_success
将 188 行的"seek 成功后整段后处理"块抽到 helper:
- 写"回退操作成功"日志
- 检查 reservation_back_verify_enabled,启用时:
  - wait_after_seek_and_verify 等待
  - 调用 validate_back_to_reservation
  - 校验失败 → handle_verify_failure_retry_via_mapping
  - 校验通过 → 写日志
- setup_lock_period_and_log_success

返回值约定:
- True:处理成功(含校验通过 OR 校验失败重试成功)
- False:校验失败且重试失败

attend_window.py: 574 → 405 行 (-169)
attend_window_helpers.py: 804 → 994 行

attend_window.py 跌破 500 行(1437 → 405,本会话累计削减 1032 行 = -72%)
process_reservation_attend_window 函数从 1218 → 376 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:05:49 +08:00
CodexandClaude Opus 4.7 06c3e54d26 refactor(reservation): 抽 process_reservation_attend_window 中"成功回退后设置锁定期"块到 setup_lock_period_and_log_success
将 84 行的"成功回退后处理"块抽到 helper:
- focus_until_ts = ft + poll_before(设置锁定期)
- reservation_after_action_pending = True
- 写"已回退到目标直播间"运行日志和"回退成功"行为日志
- write_state_callback
- 写"已触发回退"完成日志

attend_window.py: 637 → 574 行 (-63)
attend_window_helpers.py: 699 → 804 行

attend_window.py 跌破 600 行(1437 → 574,本会话累计削减 863 行 = -60%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:02:28 +08:00
CodexandClaude Opus 4.7 28dcbc75c7 refactor(reservation): 抽 process_reservation_attend_window 中"回退校验失败 → 映射表二次回退"块到独立模块
将 375 行的最大独立块抽到 attend_window_verify_retry.py:handle_verify_failure_retry_via_mapping。
逻辑:
- 写"回退校验失败"日志(log_reservation_error 或 _log_kv)
- 通过映射表查找目标和当前直播间位置
- 计算映射差值,决定是否重试 seek
- 重试成功 → 设置锁定期 + 待处理标志,返回 True
- 重试失败 → 清理锁定相关标志,返回 False

调用方根据返回值 return True/False。

attend_window.py: 991 → 637 行 (-354)
新增 attend_window_verify_retry.py: 420 行

attend_window.py 跌破 700 行(1437 → 637,本会话累计削减 800 行 = -56%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:00:14 +08:00
CodexandClaude Opus 4.7 dadb0b6852 refactor(reservation): 抽 process_reservation_attend_window 中"回退后等待直播间加载"块到 wait_after_seek_and_verify
将 43 行的等待逻辑抽到 helper:
- 读 reservation_back_verify_wait_seconds(默认 5.0,限制 0.1-10.0)
- 写"开始等待"日志
- 调用 operation.delay 或 time.sleep
- 写"等待完成"日志(含实际等待秒数)

attend_window.py: 1030 → 991 行 (-39)
attend_window_helpers.py: 645 → 699 行

attend_window.py 跌破 1000 行(1437 → 991,本会话累计削减 446 行 = -31%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:55:17 +08:00
CodexandClaude Opus 4.7 6aec4ae314 refactor(reservation): 抽 process_reservation_attend_window 末尾"回退失败"块到 log_seek_failure_and_finish
将函数末尾"回退失败:记录日志,等待后续重试或清理"块(约 36 行)抽到 helper:
- 写"回退失败"日志
- 调用 write_state_callback
- 写"未触发回退"完成日志

attend_window.py: 1059 → 1030 行 (-29)
attend_window_helpers.py: 594 → 645 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:53:27 +08:00
CodexandClaude Opus 4.7 4ce62a1907 refactor(reservation): 抽 process_reservation_attend_window 中"执行回退动作前的日志+seek 调用"块到 execute_seek_reservation_with_logging
将 76 行的"进入预约参与窗口"独立块抽到 helper:
- 写"进入预约参与窗口"日志
- 计算 current_room_pos / target_pos / pos_diff
- 写"准备执行回退到预约直播间"日志
- 调用 seek_reservation_room_callback(target)
- 异常时记录错误日志(log_reservation_error 或 _log_kv)

返回值:(ok: bool, current_room_pos: int, target_pos: int, pos_diff: int)

attend_window.py: 1121 → 1059 行 (-62)
attend_window_helpers.py: 496 → 594 行

attend_window.py 跌破 1100 行(1437 → 1059,本会话累计削减 378 行 = -26%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:50:02 +08:00
CodexandClaude Opus 4.7 f0150cb3f4 refactor(reservation): 抽 process_reservation_attend_window 中"锁定期同预约检查"块到 handle_lock_period_same_reservation_check
将 148 行的"锁定期内的复杂检查"独立块抽到 helper:
- 队列满立即参与模式 → 跳过此检查
- 锁定期未结束 + 不是同一预约 → return False(不允许回退)
- 锁定期未结束 + 同一预约 + 已在目标位置 + 时间窗口到达 → return True(需要参与)
- 锁定期未结束 + 同一预约 + 已在目标位置 + 时间窗口未到 → return False(清除待处理标志)
- 锁定期未结束 + 同一预约 + 不在目标位置 → 写日志后 return None(继续检查)

返回值约定(None/True/False 三态):
- True:需要参与,调用方应直接 return True
- False:跳过/不允许回退,调用方应直接 return False
- None:检查通过,调用方继续后续逻辑

attend_window.py: 1247 → 1121 行 (-126)
attend_window_helpers.py: 329 → 496 行

attend_window.py 跌破 1200 行(1437 → 1121,本会话累计削减 316 行 = -22%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:47:41 +08:00
CodexandClaude Opus 4.7 8d426676f6 refactor(fudai): 抽 attend_choujiang 中"粉丝团门槛"分支到 fudai_attend_fansclub
将 attend_choujiang 中"加入粉丝团/粉丝团"分支整段(1054 行)抽到
douyin/fudai/core/fudai_attend_fansclub.py:handle_fansclub_required。

逻辑:
- 保存 debug 截图(标注 OCR 区域)
- 第一步:点击参与按钮(OCR 区域中心 543, 2070)
- 第二步:OCR 识别"加入粉丝团"按钮位置并点击
- 第三步:关闭详情页
- 包含 OCR 重试、坐标缩放、自救恢复等深嵌套逻辑

主文件中保留 elif 分支头 + 7 行调用 helper。

fudai_attend.py: 1295 → 246 行 (-1049)
新增 fudai_attend_fansclub.py: 1075 行

attend_choujiang 函数从 1281 行跌到约 230 行。
fudai_attend.py 是本会话削减幅度最大的文件之一(1629 → 246,-85%)。

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:45:11 +08:00
CodexandClaude Opus 4.7 f5b603e39e refactor(fudai): 抽 run_once_basic 中"高价值预约整段处理"块到 process_high_value_reservation_check
将 high_value_enabled and reservations_list 分支整段(含 4 个回调闭包 + 6 步处理流程)
约 99 行抽到 process_high_value_reservation_check helper,内部组合:
- try_handle_queue_full_wait
- log_skip_preemption_reason
- reset_to_first_room_after_all_reservations_done
- log_first_reservation_check
- process_reservation_multi_room_mode(多间模式)
- cleanup_expired_reservations_single_room(单间模式)

返回值约定:
- True:触发了早返回(队列满等待 / 所有预约完成重置),调用方应直接 return
- False:未触发早返回,调用方继续

douyin_fudai.py: 1319 → 1228 行 (-91)
fudai_detail_helpers.py: 2804 → 2890 行

douyin_fudai.py 跌破 1300 行(4121 → 1228,本会话累计削减 2893 行 = -70%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:41:27 +08:00
CodexandClaude Opus 4.7 b1f70aa94d refactor(fudai): 抽 run_once_basic 中"跳过预约回退检查的原因日志"块到 log_skip_preemption_reason
将 27 行的纯日志分支抽到 helper:
- _waiting_for_lottery_result=True:写"正在等待开奖"日志
- _current_attending_reservation_fudai=True:写"正在参与预约福袋"日志
- queue_full_waiting_at_earliest=True:原代码无日志,保持原样

douyin_fudai.py: 1341 → 1319 行 (-22)
fudai_detail_helpers.py: 2776 → 2804 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:39:34 +08:00
CodexandClaude Opus 4.7 81b82e6cba refactor(fudai): 抽 _handle_in_fudai_detail 中"提取 future_ts"和"detail 为 None 早返回"两块
- extract_future_ts_from_detail:从 detail tuple 提取倒计时 future_ts 写入 _current_fudai_future_ts
- handle_detail_none_in_step4:步骤4 detail 为 None 时的早返回处理

douyin_fudai.py: 1355 → 1341 行 (-14)
fudai_detail_helpers.py: 2742 → 2776 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:37:30 +08:00
CodexandClaude Opus 4.7 2ba2168665 refactor(fudai): 抽 _handle_live_room_has_or_not_fudai 中两块到 helper
- try_skip_to_in_fudai_detail_when_verified(约 22 行):已验证过详情页则直接处理详情
- handle_no_fudai_in_live_room(约 35 行):无福袋时调用 flow_control 处理 + 写完成日志

douyin_fudai.py: 1404 → 1355 行 (-49)
fudai_detail_helpers.py: 2659 → 2742 行

douyin_fudai.py 跌破 1400 行(4121 → 1355,本会话累计削减 2766 行 = -67%)
_handle_live_room_has_or_not_fudai 从 90 行 → 41 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:33:25 +08:00
CodexandClaude Opus 4.7 d9323f2012 refactor(fudai): 抽 run_once_basic 入口"记录直播间标题"块到 record_room_title_if_not_just_switched
将 run_once_basic 入口的"记录直播间标题"块(约 14 行)抽到 helper:
- 检查 _just_switched_room 标志
- 未刚切换时调用 _record_room_title_and_pos
- 刚切换时写"跳过重复记录"日志

douyin_fudai.py: 1412 → 1404 行 (-8)
fudai_detail_helpers.py: 2640 → 2659 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:30:36 +08:00
CodexandClaude Opus 4.7 e3372fa51d refactor(fudai): 抽 _handle_in_fudai_detail 中"状态分发"和"保存详情"两块到 helper
将两个相邻的独立逻辑抽到 helper:
- dispatch_last_fudai_detail_status:根据 _last_fudai_detail_status 分发到 4 个 helper(coupon_popup/watch_task/validation_failed/error)
- save_first_open_detail:筛选通过后保存详情数据并写日志

douyin_fudai.py: 1468 → 1412 行 (-56)
fudai_detail_helpers.py: 2567 → 2640 行

douyin_fudai.py 跌破 1500 行(4121 → 1412,本会话累计削减 2709 行 = -66%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:29:02 +08:00
CodexandClaude Opus 4.7 0b3d69d28b refactor(fudai): 抽 _handle_in_fudai_detail 中"额外验证 + 兜底检查"两块到 validate_detail_or_skip
将两个相邻的早返回检查(约 64 行)抽到 helper:
1. 额外验证:调用 validate_fudai_detail,失败则关闭详情 + 写完成日志
2. 兜底检查:content 为空且 prize_value_yuan=0 → 判定为无效详情

返回值约定:
- True:检查命中早返回(调用方应直接 return)
- False:检查通过,调用方继续后续流程

douyin_fudai.py: 1525 → 1468 行 (-57)
fudai_detail_helpers.py: 2493 → 2567 行

douyin_fudai.py 跌破 1500 行(4121 → 1468,本会话累计削减 2653 行 = -64%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:27:06 +08:00
CodexandClaude Opus 4.7 0eb4670d46 refactor(fudai): 抽 _handle_in_fudai_detail 中"task_count_zero 错误处理"块到 handle_task_count_zero_error
将"last_status == error 且 reason == task_count_zero"分支(约 87 行深嵌套)抽到 helper:
- 累加 _fudai_detail_consecutive_failures 计数
- 连续 3 次失败:强制关闭详情 + 切换直播间 + 重置计数 + 写完成日志
- 否则:写日志 + 写完成日志

返回值约定:
- True:已处理 task_count_zero 错误(调用方应直接 return)
- False:不是 task_count_zero 错误或处理异常,调用方继续

douyin_fudai.py: 1606 → 1525 行 (-81)
fudai_detail_helpers.py: 2398 → 2493 行

douyin_fudai.py 跌破 1600 行(4121 → 1525,本会话累计削减 2596 行 = -63%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:22:18 +08:00
CodexandClaude Opus 4.7 5f713afc5c refactor(fudai): 抽 run_once_basic 中"多间模式预约抢占"块到 process_reservation_multi_room_mode
将多间模式调用 process_reservation_attend_window 的逻辑(约 64 行)抽到 helper:
- 写"开始调用"日志
- 调用 process_reservation_attend_window
- 写返回结果日志
- 同步回写 focus_ref 和 after_action_ref 到 analyser
- 抢占成功时设置 _current_attending_reservation_fudai=True

douyin_fudai.py: 1648 → 1606 行 (-42)
fudai_detail_helpers.py: 2328 → 2398 行

douyin_fudai.py 跌破 1700 行(4121 → 1606,本会话累计削减 2515 行 = -61%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:20:02 +08:00
CodexandClaude Opus 4.7 722b57a7b9 refactor(fudai): 抽 run_once_basic 中"预约队列满等待"块到 try_handle_queue_full_wait
将"队列已满 + 未在等待最早开奖"判定块(约 33 行)抽到 helper:
- 检查 reservations 数量 >= max_reservations 且 queue_full_waiting_at_earliest=False
- 满足时调用 douyin_reservation_logic.handle_queue_full_wait_at_earliest
- 成功 → 设置 queue_full_waiting_at_earliest 和 focus_until + 写完成日志

返回值约定:
- True:队列已满且已回退等待,调用方应直接 return
- False:队列未满或未触发回退,调用方继续

douyin_fudai.py: 1670 → 1648 行 (-22)
fudai_detail_helpers.py: 2273 → 2328 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:17:37 +08:00
CodexandClaude Opus 4.7 43da92f6e6 refactor(fudai): 抽 run_once_basic 中"单间模式清理过期预约"块到 cleanup_expired_reservations_single_room
将单间模式下"清理过期预约"逻辑(约 24 行)抽到 helper:
- 写说明日志
- 调用 douyin_reservation_logic.cleanup_expired_reservations
- 异常时记录错误日志

douyin_fudai.py: 1688 → 1670 行 (-18)
fudai_detail_helpers.py: 2242 → 2273 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:15:56 +08:00
CodexandClaude Opus 4.7 798286776d refactor(fudai): 抽 run_once_basic 中"所有预约完成回退到第一个直播间"块到 reset_to_first_room_after_all_reservations_done
将"queue_full_waiting_at_earliest=True 且 reservations 为空时回退"独立块
(约 36 行)抽到 helper:
- 写日志
- 清除 queue_full_waiting_at_earliest 和 reservation_focus_until_ts
- 回退 room_pos 次(最多 100 次)
- 重置 room_pos 和 _swipe_times

返回值约定:
- True:触发了重置(调用方应直接 return)
- False:条件不满足或异常,调用方继续

douyin_fudai.py: 1715 → 1688 行 (-27)
fudai_detail_helpers.py: 2185 → 2242 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:14:16 +08:00
CodexandClaude Opus 4.7 77d7113ca1 refactor(fudai): 抽 _handle_in_fudai_detail 中"高价值跳过决策"块到 check_high_value_skip_decision
将筛选不通过后的"高价值福袋决策"逻辑(约 91 行深嵌套)抽到 helper:
- 检查是否高价值福袋(启用 + 价值达阈值 + 倒计时有效)
- 倒计时大于阈值 + 剩余秒数在 join_ahead 内 → 返回 "attend"(取消 skip)
- 倒计时大于阈值 + 剩余秒数 > join_ahead → 调用 handle_high_value_record_reservation 后返回 "recorded"
- 其他:返回 "skip" 让调用方走筛选不通过分支

返回值约定:
- "attend":调用方将 skip 设为 False 继续立即参与
- "recorded":已记录预约(调用方应直接 return)
- "skip":保持 skip=True 走筛选不通过分支

douyin_fudai.py: 1804 → 1715 行 (-89)
fudai_detail_helpers.py: 2083 → 2185 行

douyin_fudai.py 跌破 1800 行(4121 → 1715,本会话累计削减 2406 行 = -58%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:12:31 +08:00
CodexandClaude Opus 4.7 b8ccb899c0 refactor(fudai): 抽 _handle_in_fudai_detail 步骤1"重新读取详情兜底"块到 reread_fudai_detail_fallback
将"未找到保存的详情数据时的兜底重读"逻辑(约 22 行)抽到 helper:
- 写说明日志
- 调用 read_fudai_detail_with_retries 重新读取
- 成功则更新 _last_fudai_detail_tuple 和 _current_fudai_content
- 返回 detail(成功)或 None(失败)

douyin_fudai.py: 1821 → 1804 行 (-17)
fudai_detail_helpers.py: 2047 → 2083 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:09:45 +08:00
CodexandClaude Opus 4.7 d109e94c68 refactor(fudai): 抽 _handle_in_fudai_detail 步骤1"第二次打开直接参与"块到 handle_second_open_direct_attend
将 116 行的"第二次打开使用保存详情直接参与"块抽到 helper:
- 从 _last_fudai_detail_tuple 读取保存的详情
- 设置 _current_fudai_future_ts / _current_fudai_content
- 调用 attend_choujiang 直接参与
- 更新连续失败计数器(成功重置/失败 +1)
- 清除标志 + 写步骤1完成日志

返回值约定:
- True:已完成第二次打开的直接参与处理(调用方应直接 return)
- False:保存的详情数据无效或参与异常,调用方继续兜底逻辑

douyin_fudai.py: 1921 → 1821 行 (-100)
fudai_detail_helpers.py: 1930 → 2047 行

douyin_fudai.py 跌破 1900 行(4121 → 1821,本会话累计削减 2300 行 = -56%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:07:55 +08:00
CodexandClaude Opus 4.7 887f8bad3e refactor(fudai): 抽 _handle_in_fudai_detail 中"筛选不通过"块到 handle_filter_skip
将筛选不通过分支(约 50 行)抽到 helper:
- 写"筛选不通过"日志
- 关闭详情页
- 按 needswitch 切换直播间
- clear_task_count_flag
- 写完成日志

douyin_fudai.py: 1962 → 1921 行 (-41)
fudai_detail_helpers.py: 1876 → 1930 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:05:29 +08:00
CodexandClaude Opus 4.7 c2a44f2544 refactor(fudai): 抽 _handle_in_fudai_detail 中"高价值福袋记录预约"块到 handle_high_value_record_reservation
将剩余秒数 > 预约参与阈值时的预约记录分支(约 50 行)抽到 helper:
- 写"记录预约"日志(含 reason / value / threshold / remain_seconds)
- 调用 basic_join_decision 记录预约(内部已关闭详情)
- 写完成日志(无论 basic_join_decision 是否成功)

douyin_fudai.py: 1996 → 1962 行 (-34)
fudai_detail_helpers.py: 1809 → 1876 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:03:39 +08:00
CodexandClaude Opus 4.7 f2b5aaa2c4 refactor(fudai): 抽 _handle_in_fudai_detail 步骤2"第一次打开数据验证失败"块到 handle_first_open_validation_failed
将 36 行的早返回块抽到 helper:
- 写跳过日志(含 validation_reason)
- 关闭详情页
- 写步骤2完成日志
- clear_task_count_flag
- 写主流程完成日志

douyin_fudai.py: 2020 → 1996 行 (-24)
fudai_detail_helpers.py: 1769 → 1809 行

douyin_fudai.py 跌破 2000 行(4121 → 1996,本会话累计削减 2125 行 = -52%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:01:22 +08:00
CodexandClaude Opus 4.7 4f042f95cd refactor(fudai): 抽 _handle_in_fudai_detail 步骤4"参与成功后处理"块到 handle_attend_success_post_processing
将参与成功后的清理逻辑(约 90 行)抽到
fudai_detail_helpers.handle_attend_success_post_processing。逻辑:
- 检查 _last_successful_attend_ts 是否更新
- 从 detail 提取倒计时
- 设置 _waiting_for_lottery_result / _lottery_result_expected_ts
- 调用 handle_reservation_after_attend_success
- 关闭详情页(如未由 attend_choujiang 关闭)
- 清除标志 + 写步骤4完成日志

顺带删除了 1984-1996 行重复 2 次的"清除第一次读取标志"块。

douyin_fudai.py: 2102 → 2020 行 (-82)
fudai_detail_helpers.py: 1678 → 1769 行

douyin_fudai.py 跌破 2100 行(4121 → 2020,本会话累计削减 2101 行 = -51%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:59:18 +08:00
CodexandClaude Opus 4.7 23e24a9f27 refactor(fudai): 抽 _handle_live_room_has_or_not_fudai 中"锁定期内时间窗口未到"块到 should_skip_fudai_search_in_lock_period
将 49 行的早返回检查抽到 helper:
- focus_until > now_ts(在锁定期内)
- queue_full_waiting_at_earliest=True
- 队头预约 future_ts - join_ahead > now_ts → 跳过查找避免重复打开详情

返回值约定:
- True:满足跳过条件,已写完成日志,调用方应直接 return
- False:不满足,调用方继续正常流程

douyin_fudai.py: 2144 → 2102 行 (-42)
fudai_detail_helpers.py: 1614 → 1678 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:56:51 +08:00
CodexandClaude Opus 4.7 c5a70d4a62 refactor(fudai): 抽 _handle_in_fudai_detail 中"参与成功后预约处理"块到 handle_reservation_after_attend_success
将参与成功后的预约清理逻辑(约 116 行)抽到
fudai_detail_helpers.handle_reservation_after_attend_success。逻辑:
- 如果还有其他预约:设置 10 秒保护期确保依次参与
- 如果没有其他预约:清除锁定期
- 从队列中移除当前刚完成的预约(5 秒误差匹配)
- 重新排序剩余队列

douyin_fudai.py: 2260 → 2144 行 (-116)
fudai_detail_helpers.py: 1495 → 1614 行

douyin_fudai.py 跌破 2200 行(4121 → 2144,本会话累计削减 1977 行 = -48%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:54:02 +08:00
CodexandClaude Opus 4.7 3de07d7a66 refactor(fudai): 抽 _handle_in_fudai_detail 中"简单跳过状态"的 3 个分支到 handle_simple_skip_status
last_status == "coupon_popup" / "watch_task" / "validation_failed" 三个分支
结构完全相同(写日志 → clear_task_count_flag → 写完成日志 → return),
统一抽到 handle_simple_skip_status 通用模板。

douyin_fudai.py: 2281 → 2260 行 (-21)
fudai_detail_helpers.py: 1468 → 1495 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:51:39 +08:00
CodexandClaude Opus 4.7 d35fadde54 refactor(fudai): 复用 fallback_swipe_up_to_next_live helper 替换"task_count_zero 连续失败"分支重复代码
_handle_in_fudai_detail 中"连续3次任务数量为0"分支也有 65 行结构完全相同的
兜底 ADB 上滑逻辑(与上一 commit 抽出的 fallback_swipe_up_to_next_live 完全一致),
复用同一个 helper。

douyin_fudai.py: 2336 → 2281 行 (-55)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:49:39 +08:00
CodexandClaude Opus 4.7 241c35f21d refactor(fudai): 抽 _handle_in_fudai_detail 中"兜底上滑切房"块到 fallback_swipe_up_to_next_live
将筛选不通过后的兜底切换逻辑(67 行深度嵌套)抽到
fudai_detail_helpers.fallback_swipe_up_to_next_live。逻辑:
- 优先 swipe_up_to_next_live
- 兜底直接调用 ADB shell input swipe(基于 1080x2400 基准坐标缩放)
- 最终回退到 operation.swipe

douyin_fudai.py: 2400 → 2336 行 (-64)
fudai_detail_helpers.py: 1403 → 1468 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:47:44 +08:00
CodexandClaude Opus 4.7 1468d14d0e refactor(fudai): 抽 _handle_in_fudai_detail 入口诊断日志到 log_handle_in_fudai_detail_entry
将 17 行的入口 flags 日志(reservation_after_action_pending /
reservation_focus_until_ts / waiting_for_lottery / room_pos)抽到
fudai_detail_helpers.log_handle_in_fudai_detail_entry。

douyin_fudai.py: 2412 → 2400 行 (-12)
fudai_detail_helpers.py: 1382 → 1403 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:41:52 +08:00
CodexandClaude Opus 4.7 45f925b597 refactor(fudai): 抽 run_once_basic 中"截图+阶段诊断"块到 take_screenshot_and_diagnose
将步骤 1(截图最多 3 次重试 + 阶段诊断 + 写日志)独立块(约 64 行)抽到
fudai_detail_helpers.take_screenshot_and_diagnose。

返回值约定:
- (stage, seen) 二元组:截图成功,调用方继续后续流程
- None:截图失败已写完成日志,调用方应直接 return

douyin_fudai.py: 2468 → 2412 行 (-56)
fudai_detail_helpers.py: 1311 → 1382 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:39:38 +08:00
CodexandClaude Opus 4.7 e21e5a5fca refactor(fudai): 抽 run_once_basic 中"第一个预约检查日志"块到 log_first_reservation_check
将 40 行的纯日志块抽到 fudai_detail_helpers.log_first_reservation_check。
输出 needswitch 配置 + 队列长度 + 第一个预约的详细信息(future_ts、
剩余秒数、目标位置等)。

douyin_fudai.py: 2503 → 2468 行 (-35)
fudai_detail_helpers.py: 1266 → 1311 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:37:35 +08:00
CodexandClaude Opus 4.7 7694e233f9 refactor(fudai): 抽 run_once_basic 中"预约回退触发条件日志"块到 log_reservation_check_status
将 65 行的纯日志块抽到 fudai_detail_helpers.log_reservation_check_status。
输出 3 类日志(无副作用):
1. 触发条件详情(含队列前 3 项)
2. high_value_enabled=False 时的提示
3. 队列为空时的提示

douyin_fudai.py: 2558 → 2503 行 (-55)
fudai_detail_helpers.py: 1198 → 1266 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:33:37 +08:00
CodexandClaude Opus 4.7 a90a885a51 refactor(fudai): 抽 run_once_basic 中"预约状态文件写入"闭包到 write_reservations_state_throttled
将 run_once_basic 中的 _write_state 内联闭包(约 87 行)抽到模块级
fudai_detail_helpers.write_reservations_state_throttled。该闭包:
- 节流(1 秒内重复调用直接返回)避免高频写盘卡顿
- 格式化 reservations 为 dict 列表 + 写 JSON 状态文件

主文件中保留薄包装的 _write_state 闭包仅一行调用 helper,
保持原有签名供 process_reservation_attend_window 等回调使用。

douyin_fudai.py: 2638 → 2558 行 (-80)
fudai_detail_helpers.py: 1115 → 1198 行

douyin_fudai.py 跌破 2600 行(4121 → 2558,本会话累计削减 1563 行 = -38%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:31:12 +08:00
CodexandClaude Opus 4.7 48f4af5848 refactor(fudai): 抽 run_once_basic 中"初始化预约队列"块到 initialize_reservations_queue
将 run_once_basic 步骤 0.1.1"第一次运行:清空预约队列 + 写状态文件"
独立块(约 122 行)抽到 fudai_detail_helpers.initialize_reservations_queue。

逻辑:
- 第一次运行:reservations = [] + 写空队列到状态文件 + _first_run_once_basic = False
- 非第一次:保留当前队列,仅记录调试日志

douyin_fudai.py: 2755 → 2638 行 (-117)
fudai_detail_helpers.py: 993 → 1115 行

douyin_fudai.py 跌破 2700 行(4121 → 2638,本会话累计削减 1483 行 = -36%)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:26:14 +08:00
CodexandClaude Opus 4.7 3af7c6d894 style(fudai): 删除 run_once_basic 中重复的注释行
提取 try_wait_for_lottery_result 时遗留了一行重复的步骤 0 注释。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:24:04 +08:00
CodexandClaude Opus 4.7 6f796a8aaf refactor(fudai): 抽 run_once_basic 中"等待开奖持续 OCR 检测"块到 try_wait_for_lottery_result
将 run_once_basic 步骤 0"如果正在等待开奖,持续 OCR 检测开奖结果"独立块
(约 161 行)抽到 fudai_detail_helpers.try_wait_for_lottery_result。逻辑:
- 超时(future_ts + 10s):清除等待标志,调用方继续后续流程
- 持续轮询 OCR:命中 → 处理结果 + 写完成日志 + return
- 轮询结束未命中:清除标志 + 按 needswitch 切换 + return

返回值约定:
- True:已处理开奖等待路径并写完成日志(调用方应直接 return)
- False:未在等待开奖或超时立即清除(调用方继续)

douyin_fudai.py: 2910 → 2756 行 (-154)
fudai_detail_helpers.py: 819 → 993 行

douyin_fudai.py 跌破 2800 行(4121 → 2756,本会话累计削减 1365 行)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:21:51 +08:00
CodexandClaude Opus 4.7 e351745e92 refactor(fudai): 抽 run_once_basic 中"30分钟超时检查"块到 try_no_attend_timeout
将步骤 0"30分钟未参与成功福袋则返回推荐页"独立块(约 68 行)抽到
fudai_detail_helpers.try_no_attend_timeout。逻辑:
- 如果距离 _last_successful_attend_ts > _no_attend_timeout_minutes 触发
- 如果从未参与且运行时长 > _no_attend_timeout_minutes 触发
- 触发时调用 _return_to_recommend_and_reenter_live + 写完成日志

返回值约定:
- True:触发超时处理,调用方应直接 return
- False:未触发,调用方继续

douyin_fudai.py: 2971 → 2910 行 (-61)
fudai_detail_helpers.py: 745 → 819 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:19:53 +08:00
CodexandClaude Opus 4.7 0114af2321 refactor(fudai): 抽 run_once_basic 中"跳过阶段检测"块到 try_skip_stage_diagnosis
将步骤 0.5"点击参与抽奖后跳过阶段检测,直接查找福袋"独立块(约 19 行)
抽到 fudai_detail_helpers.try_skip_stage_diagnosis。

返回值约定:
- True:跳过阶段检测路径完成,调用方应直接 return
- False:正常流程,继续阶段检测

douyin_fudai.py: 2983 → 2971 行 (-12)
fudai_detail_helpers.py: 716 → 745 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:18:18 +08:00
CodexandClaude Opus 4.7 849160304e refactor(fudai): 抽 run_once_basic 中"刚记录预约后切换直播间"块到 try_just_recorded_reservation_switch
将 run_once_basic 步骤"检查是否刚刚记录了预约,如果是则强制切换直播间"
独立块(约 47 行)抽到 fudai_detail_helpers.try_just_recorded_reservation_switch。

返回值约定:
- True:刚记录预约,已尝试切换并写完成日志(调用方应直接 return)
- False:未触发,调用方继续正常流程

douyin_fudai.py: 3022 → 2983 行 (-39)
fudai_detail_helpers.py: 657 → 716 行

douyin_fudai.py 跌破 3000 行(4121 → 2983,本会话累计削减 1138 行)

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:16:38 +08:00
CodexandClaude Opus 4.7 7307b2abb5 refactor(fudai): 抽 run_once_basic 中"COUPON_POPUP"和"SHOPPING_REDPACKET_POPUP"分支到 helper
将两个简单的弹窗处理分支抽到独立 helper:
- handle_coupon_popup:按返回键关闭优惠券弹窗
- handle_shopping_redpacket_popup:点击 (530, 1647) 关闭购物红包弹窗

douyin_fudai.py: 3042 → 3022 行 (-20)
fudai_detail_helpers.py: 618 → 657 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:14:54 +08:00
CodexandClaude Opus 4.7 c9a07cc91e refactor(fudai): 抽 run_once_basic 中"IN_LIVE_ROOM"分支到 handle_in_live_room_stage
将"在直播间"阶段的处理逻辑(约 44 行)抽到
fudai_detail_helpers.handle_in_live_room_stage。逻辑:
- 如果刚切换直播间(_just_switched_room=True),等待福袋加载
  (switch_room_wait_after_stage_diag_seconds 秒)
- 调用 _handle_live_room_has_or_not_fudai 寻找福袋图标
- 写完成日志

douyin_fudai.py: 3071 → 3042 行 (-29)
fudai_detail_helpers.py: 572 → 618 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:12:21 +08:00
CodexandClaude Opus 4.7 b5d7943af0 refactor(fudai): 抽 run_once_basic 中"FUDai_RESULT"分支到 handle_lottery_result_stage
将抽奖结果弹窗处理独立块(约 30 行)抽到
fudai_detail_helpers.handle_lottery_result_stage。逻辑:
- 清除 _waiting_for_lottery_result / _current_attending_reservation_fudai
- OCR 识别开奖结果文本
- 命中则 _handle_lottery_result_by_ocr;未命中则返回键 + 切下个直播间
- 写完成日志

douyin_fudai.py: 3092 → 3071 行 (-21)
fudai_detail_helpers.py: 535 → 572 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:10:48 +08:00
CodexandClaude Opus 4.7 da552d18cc refactor(fudai): 抽 run_once_basic 中"RECOMMEND_PAGE"分支到 handle_recommend_page
将识别到推荐页面后的处理逻辑(约 56 行)抽到
fudai_detail_helpers.handle_recommend_page。逻辑:
- 点击进入直播页 (718, 169)
- 连点两次进入直播间 (103, 382)
- 多段延迟(FOLLOW_TAB_CLICK_DELAY / ENTER_LIVE_CLICK_DELAY /
  RETURN_STEP_DELAY_SECONDS / ENTER_LIVE_FINAL_DELAY)
- 异常时按返回键 + delay 1s

douyin_fudai.py: 3132 → 3092 行 (-40)
fudai_detail_helpers.py: 477 → 535 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:09:26 +08:00
CodexandClaude Opus 4.7 40b4169aac refactor(fudai): 抽 run_once_basic 中"桌面自救检测"块到 try_desktop_recovery
将 run_once_basic 步骤 1.5 桌面自救独立块(约 95 行)抽到
fudai_detail_helpers.try_desktop_recovery。

返回值约定:
- True:检测到不在抖音前台,已尝试自救并递归调用 run_once_basic
  (调用方应直接 return)
- False:在抖音前台或检测异常,调用方继续正常流程

douyin_fudai.py: 3220 → 3132 行 (-88)
fudai_detail_helpers.py: 372 → 477 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:07:34 +08:00
CodexandClaude Opus 4.7 265a533cf0 refactor(fudai): 抽 run_once_basic 中"高价值房间重访"块到 try_high_value_room_revisit
将 run_once_basic 步骤 2.0 高价值房间重访检查独立块(约 78 行)抽到
fudai_detail_helpers.try_high_value_room_revisit。

返回值约定:
- True:重访成功,调用方应直接 return(结束本轮 run_once_basic)
- False:未触发或重访失败,调用方继续正常流程

douyin_fudai.py: 3290 → 3220 行 (-70)
fudai_detail_helpers.py: 284 → 372 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:06:09 +08:00
CodexandClaude Opus 4.7 37b3454e32 refactor(fudai): 抽 run_once_basic 中"FANSCLUB_JOIN"分支到 handle_fansclub_join
将 run_once_basic 中"粉丝团加入"分支(约 164 行)整段抽到
fudai_detail_helpers.handle_fansclub_join。逻辑:
- 第一步:点击参与按钮(基于 OCR 区域中心 543, 2070)
- 第二步:连续两次点击预设位置(527, 567)
- 第三步:关闭详情页(点击 500, 470)
- 异常分支:按 auto_join_fansclub 决定是否再次诊断 + 重试 + 点击返回
- 最终:按 fansclub_fail_action 决定是否切换直播间

douyin_fudai.py: 3447 → 3290 行 (-157)
fudai_detail_helpers.py: 120 → 284 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:02:56 +08:00
CodexandClaude Opus 4.7 77351bafd4 refactor(fudai): 抽 run_once_basic 中"截图失败多次重试"日志块到 log_screenshot_failed
将 run_once_basic 中"获取截图失败(多次重试后仍失败)"的多字段日志块
(22 行)抽到 fudai_detail_helpers.log_screenshot_failed。

douyin_fudai.py: 3460 → 3447 行 (-13)
fudai_detail_helpers.py: 83 → 120 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 11:00:56 +08:00
CodexandClaude Opus 4.7 9675df2cdb refactor(fudai): 抽 _handle_in_fudai_detail 中重复的"清除任务数量标志"块到 clear_task_count_flag
_handle_in_fudai_detail 中有 11 处结构完全相同的"清除任务数量标志"
try/except 嵌套块(每处 12 行),统一抽到 clear_task_count_flag helper。
逻辑:set _fudai_detail_task_count_from_stage = None + log_kv("福袋详情",
"_handle_in_fudai_detail:清除任务数量标志", log_type="DEBUG")。

douyin_fudai.py: 3588 → 3460 行 (-128)
fudai_detail_helpers.py: 63 → 83 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:57:59 +08:00
CodexandClaude Opus 4.7 d34e39ec9c refactor(fudai): 抽 _handle_in_fudai_detail 中"连续参与失败次数过多"块到 fudai_detail_helpers
将 49 行的"连续参与失败兜底"块抽到 fudai_modules/fudai_detail_helpers.py:
handle_consecutive_failures_exceeded。逻辑:
- 写日志 + 关闭详情页
- 按 needswitch 切换直播间或保持单间模式
- 重置 _consecutive_attend_failures 计数器

douyin_fudai.py: 3627 → 3588 行 (-39)
新增 fudai_detail_helpers.py: 63 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:52:59 +08:00
CodexandClaude Opus 4.7 34bdf44d73 refactor(fudai): 抽 attend_choujiang 中"开始观看"/"参与"分支用 handle_simple_click
新增 handle_simple_click 通用模板,覆盖结构完全相同的 2 个分支:
- "开始观看" → click(543, 2070) + log + return True
- "参与" → click(543, 2070) + log + return True

每个分支原本 11 行(含坐标注释),合并后 4 行调用。

fudai_attend.py: 1309 → 1295 行 (-14)
fudai_attend_branches.py: 349 → 366 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:49:21 +08:00
CodexandClaude Opus 4.7 6f4dbb2d8b refactor(fudai): 抽 attend_choujiang 中"评论"和"参与抽奖"分支到 handle_attend_click
将 attend_choujiang 中两个结构高度重叠的"点击参与按钮"分支抽到通用
handle_attend_click(analyser, mode) helper:

- 评论模式:仅点击 + 记 metric,return True
- 参与抽奖模式(mode="普通"):额外
  - 设置 _skip_stage_diagnosis_and_find_fudai 标志
  - 写 debug log(开始设置等待开奖标志)
  - 设置 _waiting_for_lottery_result / _lottery_result_expected_ts
  - 写 debug log(成功设置等待开奖标志)

fudai_attend.py: 1446 → 1309 行 (-137)
fudai_attend_branches.py: 217 → 349 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:47:24 +08:00
CodexandClaude Opus 4.7 4e89fadd2e refactor(stage): 提取"步骤2.5 购物红包OCR复查"块到 verify_redpacket_outside_live_room
将 douyin_stage.py 中"不在直播间但像素检测到购物红包背景"的 OCR 复查
独立块(约 153 行)抽到 douyin_stage_helpers.verify_redpacket_outside_live_room。
逻辑:
- 截图 SHOPPING_REDPACKET_AREA
- OCR 模式0 → 关键词未命中且 enable_ocr_mode1 → 跑模式1
- 关键词匹配 OR 置信度 ≥ shopping_redpacket_ocr_confidence_threshold → 判定
依赖通过参数注入:pixel_state、pixel_details、enable_ocr_mode1、
max_step_time、diag_start、_log/_log_summary、preprocess_for_ocr。

douyin_stage.py: 1247 → 1111 行 (-136)
douyin_stage_helpers.py: 199 → 383 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:40:26 +08:00
CodexandClaude Opus 4.7 331860ee5c refactor(reservation): 抽 attend_window 中 2 个时间窗口日志块
将 process_reservation_attend_window 中两个纯日志块抽到 helper:
- log_time_window_not_yet:时间窗口未到,跳过回退
- log_missed_window:已明显错过开奖时间,记录 missed_seconds

attend_window.py: 1276 → 1247 行 (-29)
attend_window_helpers.py: 276 → 329 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:35:18 +08:00
CodexandClaude Opus 4.7 4abd053957 refactor(reservation): 抽 attend_window 的"详细检查日志"块到 log_attend_window_detail_check
将 process_reservation_attend_window 中"详细调试日志"块(约 50 行)抽到
log_attend_window_detail_check helper。该块仅做日志输出,无副作用,
依赖通过参数注入:now_ts / focus_until / ft / dynamic_ahead / join_ahead /
poll_before / est_back_times。

attend_window.py: 1314 → 1276 行 (-38)
attend_window_helpers.py: 213 → 276 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:33:35 +08:00
CodexandClaude Opus 4.7 8fea99a168 refactor(reservation): 抽 attend_window 的"锁定期处理"块到 process_lock_period
将 process_reservation_attend_window 中"锁定期内:优先处理锁定的预约"
独立块(51 行)抽到 process_lock_period helper。逻辑:
- 在 reservations 中找与 focus_until 对应的预约(误差 ≤5 秒)
- 找不到 → 视为锁定失效,清除 focus_until_ts_ref,返回 0.0
- 找到但不在队头 → 移到队头,返回原 focus_until
- 已在队头 → 不动,返回原 focus_until

attend_window.py: 1352 → 1314 行 (-38)
attend_window_helpers.py: 143 → 213 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:31:53 +08:00
CodexandClaude Opus 4.7 51d859150d refactor(reservation): 抽 attend_window 中重复的"超时检查"模式到 check_total_timeout
process_reservation_attend_window 内有 2 处结构完全相同的超时检查块
("排序前"和"排序后"),各 13 行。统一抽到 check_total_timeout helper,
通过 stage_label 参数区分日志。

attend_window.py: 1372 → 1352 行 (-20)
attend_window_helpers.py: 116 → 143 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:30:32 +08:00
CodexandClaude Opus 4.7 c509bf1262 refactor(reservation): 提取 attend_window 中 2 个早返回块到 attend_window_helpers
将 process_reservation_attend_window 中两个结构相同的早返回块抽出:
- handle_already_participated:检测到 ft 已被参与,移除队头并写状态
- handle_invalid_future_ts:future_ts ≤ 0,丢弃队头并写状态

新增私有 _write_state_unified 封装"safe_write_state vs 裸 callback"
两条路径,避免主流程重复 if/else。

attend_window.py: 1437 → 1372 行 (-65)
新增 attend_window_helpers.py: 116 行

验证:
- pytest 1013 passed
- compile OK
- stub 调用两条早返回路径均返回 False

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:28:50 +08:00
CodexandClaude Opus 4.7 3b600c9f64 fix(reservation): 补 _RESERVATION_ERROR_UTILS_AVAILABLE import 修复运行时 NameError
attend_window.py 中 9 处使用 _RESERVATION_ERROR_UTILS_AVAILABLE 标志,
但 import 语句只导入了 ReservationItem / format_reservation_context /
log_reservation_error / safe_write_state,没有导入这个标志。

发现路径:尝试为该文件提取 helper 时,stub 测试触发到第 360 行的
"future_ts 无效"分支,立即抛出 NameError。
原代码中此分支被 try/except 覆盖的概率较高(外层 try 会吞噬),
但只要执行流落在 line 64/95/113/167/296/360/371/...(共 9 处)
任意一个 if 判断上,就会 NameError。

修复:把 _RESERVATION_ERROR_UTILS_AVAILABLE 加入 ._common 的
import 列表。

验证:
- stub 测试通过
- pytest 1013 passed

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:27:21 +08:00
CodexandClaude Opus 4.7 d7201866a5 refactor(stage): 提取 diagnose_stage_from_current_screen 中"步骤3 OCR确认弹窗"块到 douyin_stage_helpers
将 1203-1359 行(约 157 行)的"OCR弹窗确认"独立块抽到
douyin/stage/douyin_stage_helpers.py:verify_popup_via_ocr。
该块当所有像素检测都未命中特定阶段、但像素检测到弹窗背景特征时
执行 OCR 二次确认(优惠券"开心收下"/购物红包关键词)。
依赖通过参数注入:pixel_state、enable_ocr_mode1、max_step_time、
diag_start、max_diag_time、_log/_log_summary 闭包、preprocess_for_ocr。

douyin_stage.py: 1385 → 1247 行 (-138)
新增 douyin_stage_helpers.py: 199 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:22:07 +08:00
CodexandClaude Opus 4.7 a3fe7b3ef0 refactor(fudai): 抽 attend_choujiang 中 3 个简单失败分支用通用 helper
新增 handle_simple_fail 通用模板,覆盖结构完全相同的 3 个分支:
- watch_required(还需看播)
- cannot_participate(无法参与)
- watch_duration_insufficient(时长不足)

每个分支的逻辑都是:set fail_reason → log → metric → click(500,470) → return False。

fudai_attend.py: 1471 → 1446 行 (-25)
fudai_attend_branches.py: 184 → 217 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:19:14 +08:00
CodexandClaude Opus 4.7 1c1f0abfc0 refactor(fudai): 提取 attend_choujiang 中 4 个独立分支到 fudai_attend_branches
将 attend_choujiang 内 4 个 button_text 命中的早返回分支抽出:
- handle_no_parallel_ocr:并行OCR结果不可用
- handle_condition_not_met:不满足参与条件
- handle_attend_already_success:已参与/参与成功
- handle_activity_ended:活动已结束/福袋超时

每个 helper 处理一个分支并返回 True/False,与原代码 return 值一致。

fudai_attend.py: 1629 → 1471 行 (-158)
新增 fudai_attend_branches.py: 184 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:08:16 +08:00
CodexandClaude Opus 4.7 5d2a0ac3ff refactor(fudai): 提取 __init__ 中默认配置块到 fudai_init_defaults
将 fudai_analyse.__init__ 中 137 行简单的 self.X = literal 配置默认值赋值
统一抽到 fudai_modules/fudai_init_defaults.py 的 init_default_config 函数。
所有字段语义、默认值、类型注解保持完全一致;load_config() 仍然会用
config.json 覆盖这些默认值。

douyin_fudai.py: 3760 → 3627 行 (-133)
新增 fudai_init_defaults.py: 132 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:04:31 +08:00
CodexandClaude Opus 4.7 c8df6a1588 refactor(fudai): 提取 fudai_choujiang 中 3 个独立子块到 fudai_choujiang_helpers
将 douyin_fudai.py:fudai_choujiang 内 3 个无业务状态依赖的独立块抽出:
- cleanup_stale_screenshot:启动时清理旧截图
- resolve_device_resolution:分辨率解析(5 次重试 + 默认回退)
- write_actions_log:写运行起止标记到 actions.log(原代码重复 3 次)

douyin_fudai.py: 3861 → 3760 行 (-101)
新增 fudai_choujiang_helpers.py: 97 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:01:51 +08:00
CodexandClaude Opus 4.7 b1ee0e6b4e refactor(fudai): 提取 _capture_roi_screenshot 和 _match_icon_template 到 fudai_image_helpers
将 douyin_fudai.py 中两个图像处理工具方法(共 274 行)提取为
fudai_modules/fudai_image_helpers.py 模块级函数:
- capture_roi_screenshot(analyser, ...)
- match_icon_template(analyser, ...)

类内保留薄包装方法,调用签名不变,外部调用方(douyin_yanghao.py)
无需改动。

douyin_fudai.py: 4121 → 3861 行 (-260)
新增 fudai_image_helpers.py: 281 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 07:59:24 +08:00
CodexandClaude Opus 4.7 b9f0389e58 chore(finder): 删除 check_have_fudai_with_ready_screenshot 中 return False 之后的不可达死代码
第 938-1431 行(共 494 行)位于函数 return 语句之后,永远不会执行。
这是早期像素检测改用模板匹配后的遗留代码。函数末尾的模块级注释
"像素检测代码已删除,使用模板匹配替代" 已说明该段代码无用。

验证:
- AST 解析通过
- pytest 1013 passed
- 函数边界从 19-1431 缩到 19-936

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 07:54:25 +08:00
215 changed files with 25347 additions and 35959 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
@@ -0,0 +1,167 @@
"""fudai_choujiang 辅助函数
从 douyin_fudai.py:fudai_choujiang 中提取的独立子块:
- cleanup_stale_screenshot:清理启动时残留的旧截图
- resolve_device_resolution:解析设备分辨率(带重试和默认回退)
- write_actions_log:写运行起止标记到 actions.log
- run_loop_with_timeout:fudai_choujiang 的主循环(定时/无限)
"""
from __future__ import annotations
import logging
import os
import time
from datetime import datetime
# 用于 write_actions_log 的 log_dir_anchor:从 helper 文件位置回溯到 douyin_fudai.py 所在目录
_ANCHOR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "douyin_fudai.py")
def cleanup_stale_screenshot(analyser) -> None:
"""启动时清理旧截图文件,避免复用过期截图。"""
try:
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
os.remove(pic_path)
analyser._log_kv(
"启动",
"清理旧截图文件,避免复用过期截图",
path=pic_path,
log_type="SCREENSHOT",
)
except Exception as e:
try:
analyser._log_kv(
"启动",
f"清理旧截图文件失败 - {str(e)}",
level="WARNING",
error=str(e),
)
except Exception:
pass
def resolve_device_resolution(analyser) -> None:
"""获取设备分辨率(重试 5 次),失败回退到 1080x2400 默认值。
直接写入 analyser.resolution_ratio_x / analyser.resolution_ratio_y。
"""
resolved = False
if analyser.device_id:
for attempt in range(5):
try:
rx, ry = analyser.operation.get_device_resolution(analyser.device_id)
analyser.resolution_ratio_x = int(rx or 1080)
analyser.resolution_ratio_y = int(ry or 2400)
resolved = True
break
except Exception as e:
try:
analyser._log_kv(
"截图",
"获取分辨率失败,重试中",
attempt=attempt + 1,
error=str(e),
)
except Exception:
logging.warning(
f"[DEBUG] get_device_resolution attempt {attempt + 1} failed: {e}"
)
time.sleep(1.0)
if not resolved:
try:
analyser._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
except Exception:
pass
analyser.resolution_ratio_x, analyser.resolution_ratio_y = 1080, 2400
def run_loop_with_timeout(analyser, wait_minutes: int) -> None:
"""fudai_choujiang 主循环:定时模式 vs 无限循环模式。
定时模式(wait_minutes > 0):在 wait_minutes 分钟内反复跑 run_once_basic。
无限模式(wait_minutes <= 0):直到 Ctrl+C。
异常时延迟 2s 后继续,每轮之间延迟 1s 避免频繁截图。
"""
if wait_minutes and wait_minutes > 0:
end_ts = time.time() + int(wait_minutes) * 60
while time.time() < end_ts:
try:
analyser.run_once_basic()
except Exception as exc:
try:
analyser._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
analyser.operation.delay(2.0)
except Exception:
time.sleep(2.0)
continue
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
write_actions_log("程序运行结束(时间到)", _ANCHOR)
else:
analyser._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
while True:
try:
analyser.run_once_basic()
except KeyboardInterrupt:
analyser._log_kv("循环", "收到中断信号,退出循环")
write_actions_log("程序运行结束(中断退出)", _ANCHOR)
raise
except Exception as exc:
try:
analyser._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
analyser.operation.delay(2.0)
except Exception:
time.sleep(2.0)
continue
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
def write_actions_log(message: str, log_dir_anchor: str) -> None:
"""写一条带时间戳的标记到 logs/actions.log。
log_dir_anchor 用于定位 logs 目录(通常是 douyin_fudai 模块所在目录)。
"""
try:
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
actions_log_path = os.path.join(
os.path.dirname(log_dir_anchor), "logs", "actions.log"
)
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write("=" * 80 + "\n")
f.write(f"{ts} - [GUI] - [运行] {message}\n")
f.flush()
except Exception:
pass
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,281 @@
"""福袋图像辅助函数
从 douyin_fudai.py 中提取的图像处理工具函数:
- capture_roi_screenshot:捕获 ROI 截图
- match_icon_template:模板匹配
这两个函数原本是 fudai_analyse 类的方法 (_capture_roi_screenshot / _match_icon_template),
对 self 的依赖很轻,提取为模块级函数后,类内方法变为薄包装。
"""
from __future__ import annotations
import io
import os
import time
from typing import Tuple
from PIL import Image, UnidentifiedImageError # type: ignore[import]
import numpy as np # type: ignore[import]
def capture_roi_screenshot(
analyser,
label: str,
sx: int,
sy: int,
size: int,
screenshot_path: str | None = 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 = None
for attempt in range(6):
try:
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
except Exception:
pass
if not os.path.exists(pic_path):
time.sleep(0.08)
continue
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)
if not data:
return ""
try:
img = Image.open(io.BytesIO(data))
img.load()
except UnidentifiedImageError:
return ""
except Exception:
try:
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
except Exception:
pass
with open(pic_path, "rb") as f:
data2 = f.read()
if (
data2
and data2.startswith(b"\x89PNG")
and b"IEND" in data2[-512:]
):
try:
img = Image.open(io.BytesIO(data2))
img.load()
except Exception:
return ""
else:
return ""
except Exception:
return ""
w, h = img.size
left = max(0, min(left, w - 1))
top = max(0, min(top, h - 1))
right = max(1, min(right, w))
bottom = max(1, min(bottom, h))
roi = img.crop((left, top, right, bottom))
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 match_icon_template(
analyser,
roi_path: str,
template_path: str,
threshold: float | None = None,
) -> Tuple[bool, float]:
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。
返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。
"""
try:
if not roi_path or not os.path.exists(roi_path):
return False, 0.0
if not template_path or not os.path.exists(template_path):
return False, 0.0
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)
if (
roi_gray.shape[0] == tpl_gray.shape[0]
and roi_gray.shape[1] == tpl_gray.shape[1]
):
A = roi_gray.flatten()
B = tpl_gray.flatten()
else:
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
if ih >= th and iw >= tw:
cy = ih // 2 - th // 2
cx = iw // 2 - tw // 2
cy = max(0, min(cy, ih - th))
cx = max(0, min(cx, iw - tw))
window = roi_gray[cy : cy + th, cx : cx + tw]
a = window.flatten()
b = tpl_gray.flatten()
a = a - a.mean()
b = b - b.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom > 1e-6:
score = float(np.dot(a, b) / denom)
else:
score = -1.0
if score >= 0.55:
used_thr = (
float(threshold)
if threshold is not None
else float(
getattr(analyser, "yanghao_icon_match_threshold", 0.70)
or 0.70
)
)
detected = score >= used_thr
return bool(detected), float(score)
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
best = -1.0
step_y = max(1, th // 6)
step_x = max(1, tw // 6)
for y in range(0, ih - th + 1, step_y):
for x in range(0, iw - tw + 1, step_x):
window = roi_gray[y : y + th, x : x + tw]
a = window.flatten()
b = tpl_gray.flatten()
a = a - a.mean()
b = b - b.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom <= 1e-6:
continue
score = float(np.dot(a, b) / denom)
if score > best:
best = score
if best < -0.5:
return False, 0.0
score = float(best)
used_thr = (
float(threshold)
if threshold is not None
else float(
getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70
)
)
detected = score >= used_thr
return bool(detected), float(score)
A = roi_gray.flatten()
B = tpl_gray.flatten()
A = A - A.mean()
B = B - B.mean()
denom = np.linalg.norm(A) * np.linalg.norm(B)
if denom <= 1e-6:
return False, 0.0
score = float(np.dot(A, B) / denom)
used_thr = (
float(threshold)
if threshold is not None
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
)
detected = score >= used_thr
return bool(detected), float(score)
except Exception:
try:
analyser._log_kv(
"检测",
"_match_icon_template 异常",
roi_path=roi_path,
template_path=template_path,
)
except Exception:
pass
return False, 0.0
@@ -0,0 +1,287 @@
"""福袋分析器默认配置初始化
从 douyin_fudai.py:fudai_analyse.__init__ 中提取的默认配置块。
所有字段都是简单的 self.X = literal 赋值,无逻辑分支。
后续 load_config() 会从 config.json 读取覆盖这些默认值。
"""
from __future__ import annotations
def init_basic_state(self) -> None:
"""初始化基础状态字段:device、分辨率、计数器、operation、config_path。"""
from douyin.core.underlying_operations import underlying_operations
self.device_id: str = ""
self.y_pianyi: int = 0
self.resolution_ratio_x: int = 1080
self.resolution_ratio_y: int = 2400
self._swipe_times: int = 0
self.operation = underlying_operations()
self.config_path = "config/config.json"
def init_log_infra(self) -> None:
"""初始化日志相关字段:_run_id、_log_seq、_log_kv 闭包等。"""
import logging
import time as _time
try:
from datetime import datetime
self._run_id = datetime.now().strftime("%Y%m%d%H%M%S")
except Exception as e:
logging.debug("生成 run_id 失败,回退到时间戳: %s", e)
self._run_id = str(int(_time.time()))
self._log_seq = 0
self._log_kv_orig = None
self._use_real_timestamp = False
from douyin.logging import douyin_logging_wrapper
self._log_kv = lambda *args, **kwargs: douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(
self, *args, **kwargs
)
self._last_log_tag = None
self._std_logger = None # type: ignore[assignment]
def init_diag_timeout_state(self) -> None:
"""初始化阶段诊断 + 30 分钟超时相关状态字段。"""
import time as _time
self._last_diag_stage: str = "INIT"
self._last_diag_seen: str = "-"
self._last_diag_ts: float = 0.0
self._last_successful_attend_ts: float = 0.0
self._no_attend_timeout_minutes: float = 30.0
self._run_start_ts: float = _time.time()
self._reservations_state_last_write_ts: float = 0.0
self.last_fudai_x: int = 0
def init_reservation_runtime_state(self) -> None:
"""初始化预约运行时状态字段(单次运行内有效)。"""
import os
from typing import Any
self.reservations: list[dict[str, Any]] = []
self._first_run_once_basic: bool = True
self.room_pos: int = 0
self.reservation_focus_until_ts: float = 0.0
self.reservation_after_action_pending: bool = False
self.reset_to_list_after_reservations: bool = False
self.queue_full_waiting_at_earliest: bool = False
# 预约队列状态文件(供 WebGUI / 其他进程查看)
try:
from douyin.core import path_config as _pc
self._reservations_state_path: str = _pc.get_reservations_path()
except Exception:
self._reservations_state_path = os.path.join(
os.path.dirname(__file__), "state", "reservations.json"
)
def init_logging_system(self) -> None:
"""初始化统一日志系统 + traceId(MDC)。
设置 self._std_logger 和 trace_id(基于 _run_id)。
"""
import logging
try:
from douyin.logging import douyin_logging
if not getattr(douyin_logging, "_logging_configured", False):
douyin_logging.configure_logging()
except Exception as e:
logging.warning("日志系统初始化失败: %s", e)
try:
from douyin.logging.unified_logger import MDC, get_unified_logger
MDC.set_trace_id(f"run_{self._run_id}")
self._std_logger = get_unified_logger("douyin.fudai")
except ImportError:
self._std_logger = logging.getLogger("douyin.fudai")
root_logger = logging.getLogger()
if not root_logger.handlers:
try:
from douyin.logging import douyin_logging
douyin_logging.configure_logging()
except Exception:
pass
def cleanup_old_room_pos_map_files(self) -> None:
"""每次重新运行时丢弃磁盘上旧的映射表导出文件(JSON/CSV/MD)。"""
import os
try:
state_dir = os.path.dirname(self._reservations_state_path)
state_path = os.path.join(state_dir, "room_pos_map.json")
csv_path = os.path.join(state_dir, "room_pos_map.csv")
md_path = os.path.join(state_dir, "room_pos_map.md")
for p in (state_path, csv_path, md_path):
try:
if os.path.exists(p):
os.remove(p)
except Exception:
pass
except Exception:
pass
def init_runtime_state_flags(self) -> None:
"""初始化运行时状态标志(避免在外部定义属性的警告)。
包括等待开奖、预约参与、跳过阶段、刚切换、高价值重访、福袋详情等状态字段。
"""
import time
from typing import Any, Optional, Tuple
self.needswitch: bool | None = None
self._waiting_for_lottery_result: bool = False
self._current_attending_reservation_fudai: bool = False
self._skip_stage_diagnosis_and_find_fudai: bool = False
self._just_switched_room: bool = False
self._last_high_value_revisit_ts: float = time.time()
self._current_run_revisit_count: int = 0
self._current_run_high_value_rooms: list[dict[str, Any]] = []
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = None
self._current_fudai_future_ts: float = 0.0
self._current_fudai_content: str = ""
self._fudai_detail_first_read: bool = False
self._fudai_detail_consecutive_failures: int = 0
self._detail_closed_by_attend: bool = False
self._lottery_result_expected_ts: float = 0.0
self._lottery_wait_start_ts: float = 0.0
def init_default_config(self) -> None:
"""初始化所有配置字段的默认值。
分组:
- 福袋筛选与基础配置
- 福袋图标检测节流
- 优化查找器与阈值
- 直播间检测阈值
- 高价值福袋 / 预约
- 粉丝团
- 预约回退
- 滑动次数重置
- 意外返回桌面自救
- 养号配置
"""
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
self.contains_not_want: list[str] = []
self.contains_want: list[str] = []
self.min_prize_value_yuan: float = 0.0
self.min_participants: int = 0
self.max_participants: int = 0
self.skip_if_countdown_gt_seconds: int = 900
self.skip_if_countdown_lt_seconds: int = 0
self.no_fudai_watchdog_enabled: bool = False
# 福袋图标检测节流
self.fudai_icon_retry_delay_seconds: float = 0.6
self.fudai_icon_max_wait_seconds: float = 5.0
self.fudai_exit_after_misses: int = 999999
self.enable_back_on_misses: bool = False
self.fudai_click_wait_seconds: float = 1.0
self.switch_room_wait_after_stage_diag_seconds: float = 7.0
self.swipe_duration_ms: int = 600
self.fudai_find_max_attempts: int = 10
# 优化查找器
self.fudai_finder_optimized_enabled: bool = True
self.fudai_click_verify_enabled: bool = True
self.fudai_find_max_retries: int = 3
self.screenshot_diagnose_min_interval_seconds: float = 8.0
self.lucky_draw_red_ratio_threshold: float = 0.9
self.coupon_template_match_threshold: float = 0.75
self.attend_button_red_ratio_threshold: float = 0.25
self.fansclub_join_red_ratio_threshold: float = 0.25
# 直播间检测阈值
self.live_room_match_threshold: float = 0.8
self.fudai_template_match_enabled: bool = False
self.fudai_template_match_threshold: float = 0.7
# 高价值福袋 / 预约
self.high_value_fudai_enabled: bool = False
self.high_value_fudai_threshold_yuan: float = 500.0
self.high_value_fudai_join_ahead_seconds: int = 100
self.high_value_fudai_max_swipe_back: int = 35
self.high_value_fudai_max_reservations: int = 3
self.high_value_fudai_after_action: str = "continue"
self.high_value_fudai_after_stay_seconds: int = 120
self.high_value_fudai_poll_before_seconds: float = 10.0
# 高价值直播间回访
self.high_value_room_revisit_enabled: bool = False
self.high_value_room_revisit_only_current_run: bool = False
self.high_value_room_revisit_min_interval_seconds: int = 300
self.high_value_room_revisit_max_per_run: int = 5
self.high_value_room_revisit_min_prize_value: float = 0.0
self.high_value_room_revisit_max_age_days: int = 30
# 粉丝团
self.auto_join_fansclub: bool = False
self.fansclub_fail_action: str = "stay"
# 预约回退
self.reservation_back_verify_enabled: bool = True
self.reservation_back_swipe_delay: float = 0.6
# 滑动次数重置
self.reset_after_swipes_enabled: bool = False
self.reset_after_swipes: int = 10
# 意外返回桌面自救
self.desktop_icon_x: int = 153
self.desktop_icon_y: int = 260
self.yanghao_fallback_live_x: int = 540
self.yanghao_fallback_live_y: int = 2000
self.yanghao_fallback_enter_live_x: int = 540
self.yanghao_fallback_enter_live_y: int = 1200
# 养号配置
self.yanghao_enabled: bool = True
self.yanghao_enable_actions: bool = True
self.yanghao_step_screenshot: bool = False
self.yanghao_recommend_duration_seconds: int = 60
self.yanghao_recommend_interval_seconds: int = 0
self.yanghao_like_prob: float = 0.15
self.yanghao_fav_prob: float = 0.05
self.yanghao_comment_prob: float = 0.0
self.yanghao_dwell_on_action_min_seconds: float = 5.0
self.yanghao_dwell_on_action_max_seconds: float = 30.0
self.yanghao_icon_roi_size: int = 180
self.yanghao_icon_match_threshold: float = 0.70
self.yanghao_like_roi_scale: float = 1.5
self.yanghao_fav_roi_scale: float = 1.5
self.yanghao_like_icon_match_threshold: float | None = None
self.yanghao_fav_icon_match_threshold: float | None = None
self.yanghao_like_icon_x: int = 0
self.yanghao_like_icon_y: int = 0
self.yanghao_fav_icon_x: int = 0
self.yanghao_fav_icon_y: int = 0
self.yanghao_like_roi_offset_x: int = 0
self.yanghao_like_roi_offset_y: int = 0
self.yanghao_fav_roi_offset_x: int = 0
self.yanghao_fav_roi_offset_y: int = 0
self._last_yanghao_ts: float = 0.0
self.yanghao_comment_btn_x: int = 0
self.yanghao_comment_btn_y: int = 0
self.yanghao_comment_input_x: int = 0
self.yanghao_comment_input_y: int = 0
self.yanghao_comment_send_x: int = 0
self.yanghao_comment_send_y: int = 0
self.yanghao_comment_close_x: int = 0
self.yanghao_comment_close_y: int = 0
self.yanghao_comment_texts: list[str] = []
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)
+68 -172
View File
@@ -118,86 +118,34 @@ def check_have_fudai_with_ready_screenshot(
break
# 每次循环都重新截图(除了第一次如果已经提供了截图)
if not (screenshot_ready and loop == 0):
try:
analyser._shot_and_diagnose(
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
)
except Exception:
# 如果截图失败,尝试直接调用 get_screenshot 并验证文件可读性(避免半写入/截断图片导致后续 PIL 打开失败)
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
# 简单验证:文件存在、大小足够且能由 PIL 打开/加载
valid = False
try:
if (
os.path.exists(pic1_path)
and os.path.getsize(pic1_path) >= 1024
):
from PIL import Image as PILImage
from douyin.detection.detection_pkg.finder_screenshot import (
capture_screenshot_for_loop,
handle_screenshot_load_failure,
load_screenshot_with_retry,
)
with PILImage.open(pic1_path) as _im:
_im.verify()
valid = True
except Exception:
valid = False
if not valid:
# 再尝试一次直接截图作为最后回退
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
except Exception:
pass
except Exception:
pass
capture_screenshot_for_loop(analyser, screenshot_ready, loop, pic1_path)
# 读取截图
pic = None
try:
pic = Image.open(pic1_path)
pic.load()
except Exception:
# 如果读取失败,尝试重新截图
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
pic = Image.open(pic1_path)
pic.load()
except Exception:
pass
pic = load_screenshot_with_retry(analyser, pic1_path)
# 如果截图读取失败,等待后继续下一次循环
if pic is None:
loop += 1
consecutive_failures += 1
# 如果连续失败太多次,提前退出
if consecutive_failures >= max_consecutive_failures:
try:
analyser._log_kv(
"[找福袋图标] 警告",
"连续截图失败次数过多,提前退出",
consecutive_failures=consecutive_failures,
elapsed_s=round(time.time() - func_start, 2),
)
except Exception:
pass
action = handle_screenshot_load_failure(
analyser,
consecutive_failures,
max_consecutive_failures,
func_start,
max_wait_s,
retry_delay_s,
)
if action == "break":
break
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
pic_new = pic.convert("RGBA")
pic.close()
width, height = pic_new.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
@@ -269,82 +217,47 @@ 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 加速扫描水平带(性能优化:批量处理)
from douyin.detection.detection_pkg.finder_numpy_scan import (
numpy_band_scan,
)
if detected and _detected_x is not None:
detected_x = _detected_x
# 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
)
if detected and _detected_x is not None:
detected_x = _detected_x
detected, detected_x = numpy_band_scan(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, optimal_x_scaled,
)
# numpy 未命中/不可用时回退到原始逐像素检查
from douyin.detection.detection_pkg.finder_pixel_scan import (
pixel_scan_fallback,
)
detected, detected_x = pixel_scan_fallback(
analyser, detected, detected_x, pic_new, rx, ry, y_pianyi_val,
)
if detected:
break # 找到后退出外层 while 循环
# 像素检测未命中时,使用模板匹配作为兜底
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:
detected = True
detected_x = _x
from douyin.detection.detection_pkg.finder_template_match import (
template_match_fallback,
)
detected, detected_x = template_match_fallback(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, loop,
)
if detected and detected_x is not None:
# 重置连续失败计数
consecutive_failures = 0
# 统计:每次"进入直播间"后首次找到福袋图标耗时
try:
enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0)
except Exception:
enter_ts = 0.0
try:
already = bool(getattr(analyser, "_enter_live_fudai_logged", False))
except Exception:
already = False
if (enter_ts > 0) and (not already):
try:
dt = float(time.time() - enter_ts)
except Exception:
dt = -1.0
if dt >= 0:
try:
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
except Exception:
reason = ""
try:
analyser._enter_live_fudai_logged = True
except Exception:
pass
try:
analyser._log_kv(
"性能",
"进入直播间后找到福袋耗时",
seconds=round(dt, 2),
enter_reason=reason,
fudai_x=int(detected_x or 0),
)
except Exception:
pass
# 记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
from douyin.detection.detection_pkg.finder_loop_logging import (
log_fudai_found_and_metrics,
)
# 命中时记录调试信息
try:
elapsed_ms = int((time.time() - func_start) * 1000)
scan_y_for_log = 403 * ry // 2400 + y_pianyi_val
analyser._log_kv(
"[找福袋图标] 命中",
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y_for_log,
x=detected_x,
)
except Exception:
pass
log_fudai_found_and_metrics(
analyser, detected_x, func_start, loop, ry, y_pianyi_val
)
return int(detected_x or 0)
loop += 1
@@ -366,33 +279,15 @@ def check_have_fudai_with_ready_screenshot(
pass
break
# 每轮记录一次轻量调试信息(帮助诊断为何未命中)
# 只在每3次循环记录一次,减少日志量
if loop % 3 == 0:
try:
elapsed_ms = int((time.time() - func_start) * 1000)
sample_color = None
try:
mid_x = (scan_x_start + scan_x_end) // 2
if 0 <= scan_y < height and 0 <= mid_x < width:
pix_sample = pic_new.load()
sample_color = pix_sample[mid_x, scan_y]
except Exception:
sample_color = None
analyser._log_kv(
"[找福袋图标] 循环中",
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y,
scan_x_start=scan_x_start,
scan_x_end=scan_x_end,
sample_color=(
str(sample_color) if sample_color is not None else "None"
),
consecutive_failures=consecutive_failures,
)
except Exception:
pass
# 每轮记录一次轻量调试信息(每 3 次循环一次,减少日志量)
from douyin.detection.detection_pkg.finder_loop_logging import (
log_loop_progress,
)
log_loop_progress(
analyser, loop, func_start, pic_new, width, height,
scan_x_start, scan_x_end, scan_y, consecutive_failures,
)
# 检查是否还有剩余时间
elapsed = time.time() - func_start
@@ -409,16 +304,17 @@ def check_have_fudai_with_ready_screenshot(
break
# 像素检测未找到时,返回 False,并记录总耗时与循环次数
try:
total_elapsed_ms = int((time.time() - func_start) * 1000)
analyser._log_kv(
"[找福袋图标] 未找到福袋图标",
elapsed_ms=total_elapsed_ms,
total_loops=loop,
max_wait_s=max_wait_s,
retry_delay_s=retry_delay_s,
)
except Exception:
pass
from douyin.detection.detection_pkg.finder_loop_logging import (
log_no_fudai_found,
)
log_no_fudai_found(analyser, func_start, loop, max_wait_s, retry_delay_s)
return False
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
# 像素检测代码已删除,使用模板匹配替代
# 如需恢复像素检测,请参考 git 历史记录
@@ -0,0 +1,131 @@
"""find_fudai 辅助:循环中的调试日志
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
- log_fudai_found_and_metrics:命中福袋后记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
- log_loop_progress:每 3 次循环记录一次轻量调试信息
- log_no_fudai_found:未找到时记录总耗时与循环次数
"""
from __future__ import annotations
import time
from typing import Any
def log_fudai_found_and_metrics(
analyser: Any,
detected_x,
func_start: float,
loop: int,
ry: int,
y_pianyi_val: int,
) -> None:
"""命中福袋后:记录"进入直播间→找到福袋"耗时统计 + 命中调试信息。"""
# 统计:每次"进入直播间"后首次找到福袋图标耗时
try:
enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0)
except Exception:
enter_ts = 0.0
try:
already = bool(getattr(analyser, "_enter_live_fudai_logged", False))
except Exception:
already = False
if (enter_ts > 0) and (not already):
try:
dt = float(time.time() - enter_ts)
except Exception:
dt = -1.0
if dt >= 0:
try:
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
except Exception:
reason = ""
try:
analyser._enter_live_fudai_logged = True
except Exception:
pass
try:
analyser._log_kv(
"性能",
"进入直播间后找到福袋耗时",
seconds=round(dt, 2),
enter_reason=reason,
fudai_x=int(detected_x or 0),
)
except Exception:
pass
# 命中时记录调试信息
try:
elapsed_ms = int((time.time() - func_start) * 1000)
scan_y_for_log = 403 * ry // 2400 + y_pianyi_val
analyser._log_kv(
"[找福袋图标] 命中",
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y_for_log,
x=detected_x,
)
except Exception:
pass
def log_loop_progress(
analyser: Any,
loop: int,
func_start: float,
pic_new,
width: int,
height: int,
scan_x_start: int,
scan_x_end: int,
scan_y: int,
consecutive_failures: int,
) -> None:
"""每 3 次循环记录一次轻量调试信息(帮助诊断为何未命中)。"""
if loop % 3 != 0:
return
try:
elapsed_ms = int((time.time() - func_start) * 1000)
sample_color = None
try:
mid_x = (scan_x_start + scan_x_end) // 2
if 0 <= scan_y < height and 0 <= mid_x < width:
pix_sample = pic_new.load()
sample_color = pix_sample[mid_x, scan_y]
except Exception:
sample_color = None
analyser._log_kv(
"[找福袋图标] 循环中",
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y,
scan_x_start=scan_x_start,
scan_x_end=scan_x_end,
sample_color=(
str(sample_color) if sample_color is not None else "None"
),
consecutive_failures=consecutive_failures,
)
except Exception:
pass
def log_no_fudai_found(
analyser: Any,
func_start: float,
loop: int,
max_wait_s: float,
retry_delay_s: float,
) -> None:
"""像素检测未找到时记录总耗时与循环次数。"""
try:
total_elapsed_ms = int((time.time() - func_start) * 1000)
analyser._log_kv(
"[找福袋图标] 未找到福袋图标",
elapsed_ms=total_elapsed_ms,
total_loops=loop,
max_wait_s=max_wait_s,
retry_delay_s=retry_delay_s,
)
except Exception:
pass
@@ -1,47 +1,33 @@
"""douyin/detection/detection_pkg/finder_numpy_scan - numpy 加速福袋图标像素扫描
"""find_fudai 辅助: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])
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
使用 numpy 批量处理,从最优位置向左右两侧交替搜索福袋图标的特征颜色。
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
from typing import Any, Tuple
def scan_with_numpy(
def numpy_band_scan(
analyser: Any,
detected: bool,
detected_x,
pic_new,
width: int,
height: int,
rx: int,
ry: int,
y_pianyi_val: int,
optimal_x_scaled: int,
) -> Tuple[bool, Optional[int]]:
"""numpy 加速扫描福袋图标的水平像素带。
) -> Tuple[bool, Any]:
"""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 切换到逐像素扫描。
返回更新后的 (detected, detected_x)。
"""
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
@@ -50,120 +36,121 @@ def scan_with_numpy(
y_top = max(0, y0 - 3)
y_bottom = min(height, y0 + 4)
if not (x1 < x2 and y_top < y_bottom):
return False, None
# 边界检查
if x1 < x2 and y_top < y_bottom:
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
# 双截图记录:保存实时操作截图(像素检测区域)
try:
from douyin.handlers import douyin_screenshot_manager
# 双截图记录:保存实时操作截图(像素检测区域)
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
)
except Exception:
pass
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
)
except Exception:
pass
arr = _np.array(roi)
if arr.size > 0:
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 valid_cols.any():
# 优化:从最优位置开始向左右两侧搜索
roi_width = x2 - x1
optimal_col = optimal_x_scaled - x1 # 转换为ROI内的列索引
optimal_col = max(0, min(optimal_col, roi_width - 1))
arr = _np.array(roi)
if arr.size == 0:
return False, None
# 从最优位置开始,向左右两侧交替搜索
found_col = None
search_range = max(optimal_col, roi_width - optimal_col)
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
# 先检查最优位置本身
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
# 从最优位置开始向左右两侧交替搜索
roi_width = x2 - x1
optimal_col = optimal_x_scaled - x1
optimal_col = max(0, min(optimal_col, roi_width - 1))
# 如果没找到,回退到原来的方法(从左到右)
if found_col is None:
found_col = int(_np.argmax(valid_cols))
found_col: Optional[int] = None
search_range = max(optimal_col, roi_width - optimal_col)
col_idx = found_col
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
detected = True
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
# 保存找到的位置作为下次的最优位置
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
if found_col is None:
# 兜底:从左到右第一个匹配
found_col = int(_np.argmax(valid_cols))
# 双截图记录:保存成功识别存档截图
try:
from douyin.handlers import douyin_screenshot_manager
col_idx = found_col
# 1080 基准坐标
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
douyin_screenshot_manager.save_last_success(
roi, operation_type="pixel_detect"
)
# 保存找到的位置作为下次的最优起点
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
# 保存完整截图(检测成功)
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:
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
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
# numpy不可用或计算错误,回退到逐像素检测
detected = False
return detected, detected_x
@@ -1,205 +1,207 @@
"""douyin/detection/detection_pkg/finder_pixel_scan - 逐像素福袋图标扫描兜底
"""find_fudai 辅助:逐像素扫描兜底
当 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]。
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
当 numpy 加速扫描未命中或不可用时,回退到原始逐像素检查。
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
from typing import Any, 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(
def pixel_scan_fallback(
analyser: Any,
detected: bool,
detected_x,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
) -> Tuple[bool, Optional[int]]:
"""逐像素遍历兜底(numpy 不可用 / 未命中时使用)。
) -> Tuple[bool, Any]:
"""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, detected_x)。
"""
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
if not detected:
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))
# 获取最优搜索起始位置(使用历史记录或默认值)
try:
# 尝试获取上次找到的福袋位置(1080基准)
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:
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
optimal_x_scaled = 169 * rx // 1080
except Exception:
# 使用默认最优位置
optimal_x_scaled = 169 * rx // 1080
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
# 确保最优位置在搜索范围内
optimal_x_scaled = max(
scan_x_start, min(optimal_x_scaled, scan_x_end - 1)
)
if found_x is None:
continue
# 命中:转换回 1080 基准
detected_x = int(found_x * 1080.0 / max(1, rx))
detected = True
# 确保y坐标在有效范围内
if 0 <= scan_y < pic_height:
# 精度优化:同时检查上下几行像素,提高检测准确性
for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行
check_y = scan_y + offset_y
if not (0 <= check_y < pic_height):
continue
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),
# 优化:从最优位置开始向左右两侧搜索
found_x = None
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
).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:
px = pix[optimal_x_scaled, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = optimal_x_scaled
except (IndexError, TypeError):
pass
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
break # 找到后退出 offset_y 循环
except Exception:
# 像素检测失败,记录但不影响主流程
pass
# 如果最优位置没找到,向左右两侧交替搜索
if found_x is None:
for offset in range(1, search_range + 1):
# 先检查右侧
right_x = optimal_x_scaled + offset
if right_x < scan_x_end:
try:
px = pix[right_x, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = right_x
break
except (IndexError, TypeError):
continue
# 再检查左侧
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start:
try:
px = pix[left_x, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = left_x
break
except (IndexError, TypeError):
continue
# 如果还是没找到,回退到原来的方法(从左到右)
if found_x is None:
for x_scaled in range(scan_x_start, scan_x_end):
try:
px = pix[x_scaled, check_y]
if isinstance(px, tuple) and len(px) >= 3:
if (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
found_x = x_scaled
break
except (IndexError, TypeError):
continue
if found_x is not None:
# 转换回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
@@ -0,0 +1,111 @@
"""find_fudai 辅助:截图获取 + 验证 + 重试
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional, Tuple
def capture_screenshot_for_loop(analyser: Any, screenshot_ready: bool, loop: int, pic1_path: str) -> None:
"""每次循环开始时获取截图(除了第一次如果已提供)。
流程:
1. 调用 _shot_and_diagnose 截图(diagnose=False)
2. 失败时调用 get_screenshot 并用 PIL 验证文件完整性
3. 如验证失败再尝试一次截图作为最后回退
"""
if screenshot_ready and loop == 0:
return
try:
analyser._shot_and_diagnose(
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
)
except Exception:
# 如果截图失败,尝试直接调用 get_screenshot 并验证文件可读性
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
valid = False
try:
if (
os.path.exists(pic1_path)
and os.path.getsize(pic1_path) >= 1024
):
from PIL import Image as PILImage
with PILImage.open(pic1_path) as _im:
_im.verify()
valid = True
except Exception:
valid = False
if not valid:
# 再尝试一次直接截图作为最后回退
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
except Exception:
pass
except Exception:
pass
def load_screenshot_with_retry(analyser: Any, pic1_path: str):
"""读取截图,失败时重新截图后重试。返回 PIL Image 或 None。"""
from PIL import Image
pic = None
try:
pic = Image.open(pic1_path)
pic.load()
except Exception:
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
pic = Image.open(pic1_path)
pic.load()
except Exception:
pass
return pic
def handle_screenshot_load_failure(
analyser: Any,
consecutive_failures: int,
max_consecutive_failures: int,
func_start: float,
max_wait_s: float,
retry_delay_s: float,
) -> str:
"""截图读取失败时的处理:
- 连续失败超过阈值 → 写警告日志,返回 "break"(外层 while 应 break)
- 否则等待 retry_delay_s 秒后返回 "continue"(外层 while 应 continue)
"""
if consecutive_failures >= max_consecutive_failures:
try:
analyser._log_kv(
"[找福袋图标] 警告",
"连续截图失败次数过多,提前退出",
consecutive_failures=consecutive_failures,
elapsed_s=round(time.time() - func_start, 2),
)
except Exception:
pass
return "break"
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
return "continue"
@@ -1,279 +1,257 @@
"""douyin/detection/detection_pkg/finder_template_match - OpenCV 模板匹配兜底
"""find_fudai 辅助:模板匹配兜底(OpenCV)
像素检测(numpy + 逐像素)都失败时的最后兜底:用 OpenCV 模板匹配
(TM_CCOEFF_NORMED)在搜索区域里找 fudai.png 模板。
入口:match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) -> (detected, x)
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
当像素检测未命中时,使用 cv2.matchTemplate 在指定区域查找福袋图标。
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional, Tuple
from typing import Any, 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(
def template_match_fallback(
analyser: Any,
detected: bool,
detected_x,
pic_new,
width: int,
height: int,
rx: int,
ry: int,
y_pianyi_val: int,
loop: int,
) -> Tuple[bool, Optional[int]]:
"""像素检测全部失败后的模板匹配兜底。
) -> Tuple[bool, Any]:
"""像素检测未命中时的 OpenCV 模板匹配兜底。
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, detected_x)。
"""
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
# 获取匹配阈值
# 像素检测未命中时,使用模板匹配作为兜底
if not detected or detected_x is None:
try:
template_threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
)
except Exception:
template_threshold = 0.7
import cv2
import numpy as np
# 读取模板
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is None:
return False, None
# 获取模板路径
try:
from douyin.core import path_config
# 将 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]
template_path = path_config.get_assets_dir() + "/fudai.png"
except Exception:
# 回退到旧路径(向后兼容)
base_dir = os.path.dirname(__file__)
template_path = os.path.join(base_dir, "assets", "fudai.png")
# 定义搜索区域: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 os.path.exists(template_path):
# 获取匹配阈值
try:
template_threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
except Exception:
template_threshold = 0.7
if not (x1 < x2 and y_top < y_bottom):
# 读取模板
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is not None:
# 将PIL图片转换为OpenCV格式
pic_rgb = pic_new.convert("RGB")
screenshot_bgr = cv2.cvtColor(
np.array(pic_rgb), cv2.COLOR_RGB2BGR
)
# 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
x1 = max(0, 156 * rx // 1080)
x2 = min(width, 269 * rx // 1080)
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
if x1 < x2 and y_top < y_bottom:
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
if search_roi.size > 0:
th, tw = template.shape[:2]
rh, rw = search_roi.shape[:2]
# 保存搜索区域截图到 last_match.png
try:
base_dir = os.path.dirname(__file__)
pic_base = os.path.join(base_dir, "pic")
match_dir = os.path.join(pic_base, "template_match")
os.makedirs(match_dir, exist_ok=True)
last_match_path = os.path.join(
match_dir, "last_match.png"
)
# 保存截图并检查是否成功
save_success = cv2.imwrite(
last_match_path, search_roi
)
if save_success:
try:
analyser._log_kv(
"[找福袋图标] 已保存搜索区域截图",
loop=loop,
文件路径=last_match_path,
搜索区域尺寸=f"{rw}x{rh}",
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图失败",
loop=loop,
文件路径=last_match_path,
)
except Exception:
pass
except Exception as save_err:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图异常",
loop=loop,
错误类型=type(save_err).__name__,
错误信息=str(save_err),
)
except Exception:
pass
# 如果模板太大,缩小模板
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template = cv2.resize(
template,
(
max(1, int(tw * scale)),
max(1, int(th * scale)),
),
)
th, tw = template.shape[:2]
# 执行模板匹配
if th <= rh and tw <= rw:
res = cv2.matchTemplate(
search_roi, template, cv2.TM_CCOEFF_NORMED
)
_min_val, max_val, _min_loc, max_loc = (
cv2.minMaxLoc(res)
)
# 双截图记录:保存实时操作截图(搜索区域)
try:
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:
# 双截图记录:保存成功识别存档截图
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
# 计算检测到的X坐标(1080基准)
detected_x_in_roi = max_loc[0]
detected_x = int(
(x1 + detected_x_in_roi + tw // 2)
* 1080.0
/ max(1, rx)
)
detected = True
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
else:
# 模板尺寸不匹配,记录调试信息
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-尺寸不匹配",
loop=loop,
模板尺寸=f"{tw}x{th}",
搜索区域尺寸=f"{rw}x{rh}",
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
)
except Exception:
pass
else:
# 搜索区域为空,记录调试信息
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-搜索区域为空",
loop=loop,
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
截图尺寸=f"{width}x{height}",
)
except Exception:
pass
else:
# 搜索区域坐标无效,记录调试信息
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-坐标无效",
loop=loop,
x1=x1,
x2=x2,
y_top=y_top,
y_bottom=y_bottom,
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
)
except Exception:
pass
except (ImportError, Exception) as e:
# OpenCV不可用或模板匹配失败,继续使用像素检测结果
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-坐标无效",
"[找福袋图标] 模板匹配异常",
loop=loop,
x1=x1,
x2=x2,
y_top=y_top,
y_bottom=y_bottom,
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
错误类型=type(e).__name__,
错误信息=str(e),
)
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
return detected, detected_x
+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)
+54 -501
View File
@@ -11,281 +11,36 @@ from typing import Any
from douyin.core import path_config
from .coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK
def attend_choujiang(analyser) -> bool:
"""点击参与抽奖。"""
analyser.last_attend_fail_reason = ""
click_times = 0
while click_times < 2:
# 优化:优先使用并行OCR中已识别的按钮状态(避免重复识别)
attend_button_text = ""
button_status = getattr(analyser, "_fudai_button_status", None)
button_text = getattr(analyser, "_fudai_button_text", "")
try:
current_room_pos = int(getattr(analyser, "room_pos", 0) or 0)
except Exception:
current_room_pos = 0
try:
cached_room_pos = int(getattr(analyser, "_fudai_button_room_pos", 0) or 0)
except Exception:
cached_room_pos = 0
# 解析参与按钮文本(从并行 OCR / 缓存 / 映射表中获取)
from douyin.fudai.core.fudai_attend_branches import resolve_attend_button_text
# 如果并行OCR属性缺失或不完整,尝试从其它缓存字段复用识别结果(例如 button_text_raw 或映射表)
if not button_text or not button_status:
try:
candidate = getattr(analyser, "button_text_raw", None)
if not candidate:
try:
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
room_map = getattr(analyser, "_room_pos_to_title_map", {}) or {}
if room_map and room_pos in room_map:
info = room_map.get(room_pos) or {}
if isinstance(info, dict):
fudai_detail = info.get("fudai_detail") or {}
candidate = (
fudai_detail.get("button_text")
or fudai_detail.get("button_text_raw")
or None
)
except Exception:
pass
if candidate:
bt = str(candidate or "").strip()
if bt:
# 推断按钮状态(与并行OCR的判断逻辑保持一致)
if "参与成功" in bt or "等待开奖" in bt:
bs = "已参与"
elif "加入粉丝团" in bt or "粉丝团" in bt:
bs = "需要加入粉丝团"
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
bs = "需要评论"
elif "还需看播" in bt or "开始观看" in bt:
bs = "需要观看"
elif "未达成" in bt:
bs = "未达成要求"
elif "参与抽奖" in bt or "参与" in bt:
bs = "可以参与"
else:
bs = "未知状态"
try:
analyser._fudai_button_status = bs
analyser._fudai_button_text = bt
analyser._fudai_button_ocr_time = time.time()
try:
analyser._fudai_button_room_pos = int(
getattr(analyser, "room_pos", 0) or 0
)
except Exception:
pass
analyser._log_kv(
"参与",
"复用缓存的并行OCR文本作为按钮状态",
button_text=(bt[:100] if bt else ""),
button_status=bs,
)
except Exception:
pass
button_text = bt
button_status = bs
except Exception:
pass
# 使用并行OCR识别的按钮状态(如果可用且在有效期内)
try:
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
current_time = time.time()
if button_text and button_status and current_time - button_ocr_time < 5.0:
attend_button_text = button_text
analyser._log_kv(
"参与",
"使用并行OCR识别的按钮状态",
button_text=(
attend_button_text[:100] if attend_button_text else ""
),
button_status=button_status,
)
elif button_text and button_status:
same_room = (
not current_room_pos
or not cached_room_pos
or current_room_pos == cached_room_pos
)
if same_room:
attend_button_text = button_text
try:
age_ms = int(
max(0.0, current_time - float(button_ocr_time)) * 1000
)
except Exception:
age_ms = None
analyser._log_kv(
"参与",
"使用并行OCR缓存的按钮状态(超时复用)",
button_text=(
attend_button_text[:100] if attend_button_text else ""
),
button_status=button_status,
age_ms=age_ms,
room_pos=current_room_pos,
)
except Exception:
pass
attend_button_text = resolve_attend_button_text(analyser)
# 如果并行OCR结果不可用,直接放弃参与(决策已由福袋详情中的并行OCR进行)
if not attend_button_text:
analyser.last_attend_fail_reason = "no_parallel_ocr_result"
analyser._log_kv("参与", "并行OCR结果不可用,放弃参与", result="不参与")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="no_parallel_ocr_result",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
from douyin.fudai.core.fudai_attend_branches import handle_no_parallel_ocr
return handle_no_parallel_ocr(analyser)
# 基于并行OCR结果进行决策
if attend_button_text and "不满足参与条件" in attend_button_text:
analyser.last_attend_fail_reason = "condition_not_met"
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="condition_not_met",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
from douyin.fudai.core.fudai_attend_branches import handle_condition_not_met
return handle_condition_not_met(analyser)
elif (
attend_button_text and "参与成功" in attend_button_text
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
from douyin.fudai.core.fudai_attend_branches import (
handle_attend_already_success,
)
# future_ts 可能尚未在此分支前赋值,先做兜底初始化(供 metric 使用)
future_ts = 0.0
try:
future_ts = float(
getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
)
except Exception:
future_ts = 0.0
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
future_ts=int(future_ts) if future_ts else None,
)
except Exception:
pass
# 记录最后一次成功参与的时间
try:
analyser._last_successful_attend_ts = time.time()
except Exception:
pass
# 记录已参与的福袋(通过 future_ts 标识),避免重复参与
future_ts = 0.0
try:
# 从 detail 中获取 future_ts(如果可用)
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
# 如果没有从 detail 中获取到 future_ts,尝试直接解析当前详情页的倒计时文本
if not future_ts:
try:
from douyin.fudai import douyin_fudai_core
content, time_text, participants, copies, prize_value_yuan = (
douyin_fudai_core.get_fudai_contain(analyser, renwu=1)
)
# 尝试用 operation.check_countdown 解析 time_text
try:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
_, parsed_future = res
future_ts = float(parsed_future or 0.0)
except Exception:
pass
except Exception:
pass
if future_ts > 0:
participated_fudai_ts = getattr(
analyser, "_participated_fudai_future_ts", set()
)
if not isinstance(participated_fudai_ts, set):
participated_fudai_ts = set()
participated_fudai_ts.add(future_ts)
analyser._participated_fudai_future_ts = participated_fudai_ts
analyser._log_kv(
"参与",
"记录已参与福袋",
future_ts=future_ts,
total_participated=len(participated_fudai_ts),
)
except Exception:
pass
# 设置开奖等待状态(如果 future_ts 可用)
if future_ts > 0:
try:
current_time = time.time()
remain_seconds = max(0, future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts
analyser._lottery_wait_start_ts = current_time
analyser._log_kv(
"参与",
"参与成功,设置等待开奖标志",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
lottery_result_expected_ts=int(
analyser._lottery_result_expected_ts
),
)
else:
analyser._log_kv(
"参与",
"参与成功,但倒计时已过期,不设置等待标志",
future_ts=int(future_ts),
remain_seconds=int(remain_seconds),
)
except Exception as e:
analyser._log_kv(
"参与",
"设置开奖等待状态时出错",
error=str(e),
error_type=type(e).__name__,
)
# 设置标志:已经关闭了详情,避免后续再次点击返回键
try:
analyser._detail_closed_by_attend = True
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击刚才打开福袋的旁边位置
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
return handle_attend_already_success(analyser, attend_button_text)
elif attend_button_text and (
("活动已结束" in attend_button_text)
or ("活动己结束" in attend_button_text)
@@ -293,265 +48,63 @@ def attend_choujiang(analyser) -> bool:
or ("活动超时" in attend_button_text)
or ("已超时" in attend_button_text)
):
# 活动结束/福袋超时:按一次返回键退出详情
analyser.last_attend_fail_reason = "activity_ended"
try:
analyser._log_kv(
"参与",
"活动已结束/福袋超时:按返回键退出详情",
result="activity_ended",
)
except Exception:
pass
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="activity_ended",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
except Exception:
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
except Exception:
pass
return False
from douyin.fudai.core.fudai_attend_branches import handle_activity_ended
return handle_activity_ended(analyser)
elif (
attend_button_text and "还需看播" in attend_button_text
): # 如果识别到需要看播
analyser.last_attend_fail_reason = "watch_required"
analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="watch_required",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
from douyin.fudai.core.fudai_attend_branches import handle_simple_fail
return handle_simple_fail(
analyser, "需要看播时长:默认不参与", "看播门槛", "watch_required"
)
elif attend_button_text and "无法参与" in attend_button_text:
analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="cannot_participate",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
from douyin.fudai.core.fudai_attend_branches import handle_simple_fail
return handle_simple_fail(
analyser,
"无法参与(条件不满足)",
"无法参与",
"cannot_participate",
)
elif attend_button_text and "时长不足" in attend_button_text:
analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="watch_duration_insufficient",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
from douyin.fudai.core.fudai_attend_branches import handle_simple_fail
return handle_simple_fail(
analyser,
"无法参与(看播时长不足)",
"时长不足",
"watch_duration_insufficient",
)
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._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode="评论",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
mode="评论",
)
except Exception:
pass
return True
from douyin.fudai.core.fudai_attend_branches import handle_attend_click
return handle_attend_click(analyser, "评论")
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._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode="普通",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
mode="普通",
)
except Exception:
pass
from douyin.fudai.core.fudai_attend_branches import handle_attend_click
# 设置标志:点击参与抽奖后直接查找福袋,跳过阶段检测
# 注意:点击参与按钮后会自动关闭详情页,返回直播间
try:
analyser._skip_stage_diagnosis_and_find_fudai = True
except Exception:
pass
# 设置等待开奖标志,避免参与后立即切换直播间
# #region agent log - set countdown
import json
from douyin.core.path_config import get_debug_log_path
current_ts_debug = int(time.time() * 1000)
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_set_countdown_start",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:186",
"message": "开始设置等待开奖标志",
"data": {
"future_ts": getattr(
analyser, "_current_fudai_future_ts", 0.0
)
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
)
+ "\n"
)
# #endregion
try:
# 从 detail 中获取 future_ts(如果可用)
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
if future_ts > 0:
current_time = time.time()
remain_seconds = int(future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts
analyser._lottery_wait_start_ts = current_time
# #region agent log - countdown set
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_countdown_set",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:195",
"message": "成功设置等待开奖标志",
"data": {
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
"future_ts": future_ts,
"current_time": current_time,
"remain_seconds": remain_seconds,
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
)
+ "\n"
)
# #endregion
analyser._log_kv(
"参与",
"点击参与抽奖后,设置等待开奖标志",
future_ts=int(future_ts),
remain_seconds=remain_seconds,
expected_result_ts=int(
analyser._lottery_result_expected_ts
),
)
except Exception as e:
try:
analyser._log_kv(
"参与",
"点击参与抽奖后,设置等待开奖标志时出错",
error=str(e),
)
except Exception:
pass
analyser._log_kv(
"参与",
"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",
)
return True
return handle_attend_click(analyser, "普通")
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_required,
)
return handle_fansclub_branch(analyser, attend_button_text)
return handle_fansclub_required(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._log_kv(
"参与",
"点击开始观看(基于截图优化坐标)",
action="点击观看",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
from douyin.fudai.core.fudai_attend_branches import handle_simple_click
return handle_simple_click(
analyser, "点击观看", "点击开始观看(基于截图优化坐标)"
)
return True
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._log_kv(
"参与",
"点击参与(基于截图优化坐标)",
action="点击参与",
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
from douyin.fudai.core.fudai_attend_branches import handle_simple_click
return handle_simple_click(
analyser, "点击参与", "点击参与(基于截图优化坐标)"
)
return True
# 未命中任何已知按钮文案时,避免死循环:限次重试并稍作等待
click_times += 1
+496
View File
@@ -0,0 +1,496 @@
"""attend_choujiang 分支辅助函数
从 douyin/fudai/core/fudai_attend.py:attend_choujiang 中提取的相对独立的早返回分支。
每个 helper 处理一个 button_text 命中情况,返回 True/False(与原代码 return 值一致)。
"""
from __future__ import annotations
import time
def resolve_attend_button_text(analyser):
"""从 analyser 缓存解析"参与按钮文本"。
优先级:
1. 已有的 _fudai_button_text + _fudai_button_status(并行 OCR 设置)
2. 缺失则从 button_text_raw / 映射表中查找候选并推断状态
3. 检查 OCR 时间戳:5 秒内有效 → 直接使用;超时但同房间 → 复用
返回 attend_button_text(若不可用则返回空字符串)。
"""
button_status = getattr(analyser, "_fudai_button_status", None)
button_text = getattr(analyser, "_fudai_button_text", "")
try:
current_room_pos = int(getattr(analyser, "room_pos", 0) or 0)
except Exception:
current_room_pos = 0
try:
cached_room_pos = int(getattr(analyser, "_fudai_button_room_pos", 0) or 0)
except Exception:
cached_room_pos = 0
# 如果并行 OCR 属性缺失或不完整,尝试从其它缓存字段复用识别结果
if not button_text or not button_status:
try:
candidate = getattr(analyser, "button_text_raw", None)
if not candidate:
try:
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
room_map = getattr(analyser, "_room_pos_to_title_map", {}) or {}
if room_map and room_pos in room_map:
info = room_map.get(room_pos) or {}
if isinstance(info, dict):
fudai_detail = info.get("fudai_detail") or {}
candidate = (
fudai_detail.get("button_text")
or fudai_detail.get("button_text_raw")
or None
)
except Exception:
pass
if candidate:
bt = str(candidate or "").strip()
if bt:
# 推断按钮状态(与并行 OCR 的判断逻辑保持一致)
if "参与成功" in bt or "等待开奖" in bt:
bs = "已参与"
elif "加入粉丝团" in bt or "粉丝团" in bt:
bs = "需要加入粉丝团"
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
bs = "需要评论"
elif "还需看播" in bt or "开始观看" in bt:
bs = "需要观看"
elif "未达成" in bt:
bs = "未达成要求"
elif "参与抽奖" in bt or "参与" in bt:
bs = "可以参与"
else:
bs = "未知状态"
try:
analyser._fudai_button_status = bs
analyser._fudai_button_text = bt
analyser._fudai_button_ocr_time = time.time()
try:
analyser._fudai_button_room_pos = int(
getattr(analyser, "room_pos", 0) or 0
)
except Exception:
pass
analyser._log_kv(
"参与",
"复用缓存的并行OCR文本作为按钮状态",
button_text=(bt[:100] if bt else ""),
button_status=bs,
)
except Exception:
pass
button_text = bt
button_status = bs
except Exception:
pass
# 使用并行 OCR 识别的按钮状态(如果可用且在有效期内)
attend_button_text = ""
try:
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
current_time = time.time()
if button_text and button_status and current_time - button_ocr_time < 5.0:
attend_button_text = button_text
analyser._log_kv(
"参与",
"使用并行OCR识别的按钮状态",
button_text=(
attend_button_text[:100] if attend_button_text else ""
),
button_status=button_status,
)
elif button_text and button_status:
same_room = (
not current_room_pos
or not cached_room_pos
or current_room_pos == cached_room_pos
)
if same_room:
attend_button_text = button_text
try:
age_ms = int(
max(0.0, current_time - float(button_ocr_time)) * 1000
)
except Exception:
age_ms = None
analyser._log_kv(
"参与",
"使用并行OCR缓存的按钮状态(超时复用)",
button_text=(
attend_button_text[:100] if attend_button_text else ""
),
button_status=button_status,
age_ms=age_ms,
room_pos=current_room_pos,
)
except Exception:
pass
return attend_button_text
def handle_simple_click(analyser, action_label: str, log_message: str) -> bool:
"""通用"点击 543,2070 + 简单日志"分支模板,覆盖"开始观看"/"参与"等无额外副作用的点击。
流程:click(543, 2070) → 记录日志 → 返回 True。
"""
analyser.click(543, 2070)
analyser._log_kv(
"参与",
log_message,
action=action_label,
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
return True
def handle_attend_already_success(analyser, attend_button_text: str) -> bool:
"""处理"参与成功/已参与"分支:记录、设置等待开奖标志、关闭详情。返回 True。"""
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
future_ts = 0.0
try:
future_ts = float(getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0)
except Exception:
future_ts = 0.0
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
future_ts=int(future_ts) if future_ts else None,
)
except Exception:
pass
try:
analyser._last_successful_attend_ts = time.time()
except Exception:
pass
future_ts = 0.0
try:
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
if not future_ts:
try:
from douyin.fudai import douyin_fudai_core
content, time_text, participants, copies, prize_value_yuan = (
douyin_fudai_core.get_fudai_contain(analyser, renwu=1)
)
try:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
_, parsed_future = res
future_ts = float(parsed_future or 0.0)
except Exception:
pass
except Exception:
pass
if future_ts > 0:
participated_fudai_ts = getattr(
analyser, "_participated_fudai_future_ts", set()
)
if not isinstance(participated_fudai_ts, set):
participated_fudai_ts = set()
participated_fudai_ts.add(future_ts)
analyser._participated_fudai_future_ts = participated_fudai_ts
analyser._log_kv(
"参与",
"记录已参与福袋",
future_ts=future_ts,
total_participated=len(participated_fudai_ts),
)
except Exception:
pass
if future_ts > 0:
try:
current_time = time.time()
remain_seconds = max(0, future_ts - current_time)
if remain_seconds > 0:
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts
analyser._lottery_wait_start_ts = current_time
analyser._log_kv(
"参与",
"参与成功,设置等待开奖标志",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
lottery_result_expected_ts=int(
analyser._lottery_result_expected_ts
),
)
else:
analyser._log_kv(
"参与",
"参与成功,但倒计时已过期,不设置等待标志",
future_ts=int(future_ts),
remain_seconds=int(remain_seconds),
)
except Exception as e:
analyser._log_kv(
"参与",
"设置开奖等待状态时出错",
error=str(e),
error_type=type(e).__name__,
)
try:
analyser._detail_closed_by_attend = True
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
def handle_activity_ended(analyser) -> bool:
"""处理"活动已结束/福袋超时"分支:按返回键退出详情。返回 False。"""
analyser.last_attend_fail_reason = "activity_ended"
try:
analyser._log_kv(
"参与",
"活动已结束/福袋超时:按返回键退出详情",
result="activity_ended",
)
except Exception:
pass
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="activity_ended",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
except Exception:
try:
analyser.click(500, 470)
except Exception:
pass
return False
def handle_no_parallel_ocr(analyser) -> bool:
"""处理"并行OCR结果不可用"分支:放弃参与并关闭详情。返回 False。"""
analyser.last_attend_fail_reason = "no_parallel_ocr_result"
analyser._log_kv("参与", "并行OCR结果不可用,放弃参与", result="不参与")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="no_parallel_ocr_result",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
def handle_condition_not_met(analyser) -> bool:
"""处理"不满足参与条件"分支:放弃参与并关闭详情。返回 False。"""
analyser.last_attend_fail_reason = "condition_not_met"
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="condition_not_met",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
def handle_simple_fail(
analyser, log_message: str, log_result: str, fail_reason: str
) -> bool:
"""通用"简单失败 + 关闭详情"模板,覆盖 watch_required / cannot_participate / watch_duration_insufficient 等。
流程:
1. 设置 last_attend_fail_reason = fail_reason
2. 记录"参与"日志(log_message + result=log_result)
3. 记录 metric: fudai_attend / fail / reason=fail_reason
4. click(500, 470) 关闭详情
5. 返回 False
"""
try:
analyser.last_attend_fail_reason = fail_reason
except Exception:
pass
analyser._log_kv("参与", log_message, result=log_result)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason=fail_reason,
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
def handle_attend_click(analyser, mode: str) -> bool:
"""处理"评论"或"参与抽奖"分支:点击参与按钮、记录 metric。返回 True。
"参与抽奖"模式下还会:
- 设置 _skip_stage_diagnosis_and_find_fudai 标志
- 写 debug log(开始设置等待开奖标志)
- 设置 _waiting_for_lottery_result / _lottery_result_expected_ts
- 写 debug log(成功设置等待开奖标志)
"""
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心 X = 543, Y = 2070
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode=mode,
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
mode=mode,
)
except Exception:
pass
if mode != "普通":
# 评论分支:直接返回,不设置等待开奖标志
return True
# 参与抽奖分支:设置标志 + 等待开奖
try:
analyser._skip_stage_diagnosis_and_find_fudai = True
except Exception:
pass
import json as _json
import time as _time
from douyin.core.path_config import get_debug_log_path
current_ts_debug = int(_time.time() * 1000)
try:
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
_json.dumps(
{
"id": f"log_{current_ts_debug}_set_countdown_start",
"timestamp": current_ts_debug,
"location": "fudai_attend_branches.py:handle_attend_click",
"message": "开始设置等待开奖标志",
"data": {
"future_ts": getattr(
analyser, "_current_fudai_future_ts", 0.0
)
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
)
+ "\n"
)
except Exception:
pass
try:
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
if future_ts > 0:
current_time = _time.time()
remain_seconds = int(future_ts - current_time)
if remain_seconds > 0:
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts
analyser._lottery_wait_start_ts = current_time
try:
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
_json.dumps(
{
"id": f"log_{current_ts_debug}_countdown_set",
"timestamp": current_ts_debug,
"location": "fudai_attend_branches.py:handle_attend_click",
"message": "成功设置等待开奖标志",
"data": {
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
"future_ts": future_ts,
"current_time": current_time,
"remain_seconds": remain_seconds,
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
)
+ "\n"
)
except Exception:
pass
analyser._log_kv(
"参与",
"点击参与抽奖后,设置等待开奖标志",
future_ts=int(future_ts),
remain_seconds=remain_seconds,
expected_result_ts=int(analyser._lottery_result_expected_ts),
)
except Exception as e:
try:
analyser._log_kv(
"参与",
"点击参与抽奖后,设置等待开奖标志时出错",
error=str(e),
)
except Exception:
pass
analyser._log_kv(
"参与",
"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",
)
return True
@@ -1,23 +1,25 @@
"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler - 粉丝团门槛分支
"""粉丝团门槛处理 helper
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 行)。
"""
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_required(analyser, attend_button_text: str) -> bool:
"""处理"加入粉丝团/粉丝团"分支:先点击参与按钮,再 OCR 识别"加入粉丝团"按钮位置点击,最后关闭详情页。
def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
"""处理"需要粉丝团门槛"分支:先点参与按钮 → OCR 找加入粉丝团按钮 → 点击 → 关闭详情 → 等待 → 恢复 → 返回 True。"""
返回:
- True/False:与原代码 return 行为一致
"""
analyser.last_attend_fail_reason = "fansclub_required"
# 需要粉丝团门槛:先点击参与按钮,再使用OCR识别"加入粉丝团"按钮位置并点击,最后关闭详情页
analyser.last_attend_fail_reason = "fansclub_required"
# 保存debug截图:标注OCR识别区域(参与按钮区域)
@@ -29,40 +31,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 +102,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 +186,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 +310,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 +414,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 +631,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 +690,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 +787,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 +1071,5 @@ 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:
# 回退校验时强制重新识别直播间标题,避免复用切换前的旧截图
@@ -11,6 +11,7 @@ from typing import Any, Callable, Dict, List, Optional
from ._common import (
ReservationItem,
_RESERVATION_ERROR_UTILS_AVAILABLE,
format_reservation_context,
log_reservation_error,
safe_write_state,
@@ -52,74 +53,12 @@ def process_reservation_attend_window(
except Exception:
total_timeout_s = 20.0
# 添加函数入口日志
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 函数入口",
reservations_count=len(reservations) if reservations else 0,
room_pos=room_pos,
)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="记录函数入口日志",
)
else:
pass
# 入口检查序列:函数入口日志 + 等待开奖检查 + 队列空检查 + 排序
from .attend_window_helpers import process_attend_window_entry_checks
# 检查是否正在等待开奖且当前参与的是预约福袋,如果是则不抢占
try:
waiting_for_lottery = bool(
getattr(analyser, "_waiting_for_lottery_result", False)
)
current_attending_reservation = bool(
getattr(analyser, "_current_attending_reservation_fudai", False)
)
if waiting_for_lottery and current_attending_reservation:
try:
analyser._log_kv(
"预约",
"[预约] 正在等待预约福袋开奖,不抢占其他预约",
waiting_for_lottery=waiting_for_lottery,
current_attending_reservation=current_attending_reservation,
)
except Exception:
pass
return False
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="检查是否正在等待预约福袋开奖",
)
else:
pass
if not reservations:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:预约队列为空,跳过",
)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
{},
level="WARNING",
stage="记录队列为空日志",
)
else:
pass
if not process_attend_window_entry_checks(
analyser, reservations, room_pos, start_time, total_timeout_s
):
return False
now_ts = _now_ts()
@@ -136,131 +75,23 @@ def process_reservation_attend_window(
poll_before = 10.0
poll_before = max(0.0, poll_before)
# 按统一规则排序(防止外部遗漏 sort)
# 这里不依赖外部 sort_reservations_callback:避免回调内部潜在阻塞/死锁导致主流程卡死。
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:开始队列排序",
reservations_count=len(reservations) if reservations else 0,
)
except Exception:
pass
# 超时检查
try:
if (time.time() - start_time) > total_timeout_s:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:超时退出(排序前)",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return False
except Exception:
pass
try:
_sort_reservations_inplace(reservations)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="队列排序",
)
else:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序异常(忽略)",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序完成",
earliest_future_ts=(
int(float((reservations[0].get("future_ts") or 0.0)))
if reservations
else 0
),
)
except Exception:
pass
# 锁定期内:优先处理“锁定的预约”,避免被队头其它预约打断。
# 同时,如果锁定期对应的预约已不在队列(例如刚参与成功并移除),视为“锁定失效”,清除锁定期。
if focus_until > 0 and now_ts < focus_until:
locked_idx = None
try:
for i, item in enumerate(reservations):
try:
item_ft = float(item.get("future_ts") or 0.0)
except Exception:
continue
if item_ft <= 0:
continue
expected_focus_until = item_ft + max(0.0, poll_before)
if abs(focus_until - expected_focus_until) <= 5.0:
locked_idx = i
break
except Exception:
locked_idx = None
from .attend_window_helpers import process_lock_period
if locked_idx is None:
try:
analyser._log_kv(
"预约",
"[预约] 检测到锁定期已失效(锁定预约不在队列),清除锁定期",
focus_until=int(focus_until),
lock_period_remain_seconds=int(focus_until - now_ts),
reservations_count=len(reservations),
)
except Exception:
pass
try:
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = 0.0
else:
reservation_focus_until_ts_ref.append(0.0)
except Exception:
pass
focus_until = 0.0
elif locked_idx != 0:
try:
locked_item = reservations.pop(locked_idx)
reservations.insert(0, locked_item)
analyser._log_kv(
"预约",
"[预约] 锁定期内固定处理锁定预约(忽略队头其他预约)",
focus_until=int(focus_until),
locked_future_ts=int(float(locked_item.get("future_ts") or 0.0)),
moved_from_index=int(locked_idx),
)
except Exception:
pass
focus_until = process_lock_period(
analyser,
reservations,
focus_until,
now_ts,
poll_before,
reservation_focus_until_ts_ref,
)
# 超时检查
try:
if (time.time() - start_time) > total_timeout_s:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:超时退出(排序后)",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return False
except Exception:
pass
if check_total_timeout(analyser, start_time, total_timeout_s, "排序后"):
return False
# 取队头(最早需要处理的一条;若在锁定期内已将锁定目标移动到队头,则这里即为锁定目标)
target = reservations[0]
@@ -270,645 +101,130 @@ def process_reservation_attend_window(
ft = 0.0
# 检查是否已经参与过该预约(通过 _participated_fudai_future_ts)
try:
participated_fudai_ts = getattr(
analyser, "_participated_fudai_future_ts", set()
)
if not isinstance(participated_fudai_ts, set):
participated_fudai_ts = set()
# 检查是否已经参与过(允许5秒误差)
already_participated = False
for participated_ts in participated_fudai_ts:
if abs(ft - participated_ts) <= 5.0:
already_participated = True
break
if already_participated:
# 已经参与过,从预约队列中移除
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:检测到已参与过该预约,从队列中移除",
target_future_ts=int(ft) if ft > 0 else 0,
)
except Exception:
pass
reservations.pop(0)
if _RESERVATION_ERROR_UTILS_AVAILABLE:
safe_write_state(
write_state_callback,
analyser,
format_reservation_context(
item=target,
reservations=reservations,
reason="已参与过",
),
)
else:
try:
write_state_callback()
except Exception:
pass
return False
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
item=target,
reservations=reservations,
),
level="WARNING",
stage="检查是否已参与",
)
else:
pass
from .attend_window_helpers import (
calculate_dynamic_ahead,
handle_already_participated,
handle_invalid_future_ts,
is_queue_full_immediate_attend_mode,
log_target_reservation_info,
)
if handle_already_participated(
analyser, reservations, target, ft, write_state_callback
):
return False
# 添加目标预约的详细信息日志
try:
from datetime import datetime
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft > 0
else "无效"
)
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 获取目标预约",
target_future_ts=int(ft) if ft > 0 else 0,
target_future_str=ft_str,
target_value=float(target.get("prize_value_yuan", 0)),
target_pos_seen=int(target.get("pos_seen", 0)),
target_content=str(target.get("content", ""))[:50],
)
except Exception:
pass
log_target_reservation_info(analyser, target, ft)
# 没有合法 future_ts,则直接丢弃
if ft <= 0:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:预约 future_ts 无效,丢弃",
future_ts=ft,
target=target,
)
except Exception:
pass
reservations.pop(0)
if _RESERVATION_ERROR_UTILS_AVAILABLE:
safe_write_state(
write_state_callback,
analyser,
format_reservation_context(
item=target,
reservations=reservations,
reason="future_ts 无效",
),
)
else:
try:
write_state_callback()
except Exception:
pass
handle_invalid_future_ts(
analyser, reservations, target, ft, write_state_callback
)
return False
# 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退
try:
join_ahead = float(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100
)
except Exception:
join_ahead = 100.0
# poll_before 已在函数前部统一计算
# 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过
dynamic_ahead = int(join_ahead)
est_back_times = 0
try:
target_pos = int(target.get("pos_seen") or 0)
est_back_times = max(0, int(room_pos) - target_pos)
try:
max_back = int(
getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60
)
except Exception:
max_back = 60
if max_back > 0:
est_back_times = min(est_back_times, max_back)
# 动态提前量 = max(基础提前量, 回退步数 * 延迟 + 额外缓冲)
reservation_back_swipe_delay_s_val = float(
reservation_back_swipe_delay_s or 0.6
)
dynamic_ahead = int(
max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18)
)
except Exception:
dynamic_ahead = int(join_ahead)
# 仅在"即将开奖窗口"内才触发回退:计算动态提前量
join_ahead, dynamic_ahead, est_back_times = calculate_dynamic_ahead(
analyser, target, room_pos, reservation_back_swipe_delay_s
)
# 添加详细的调试日志:记录锁定期状态和时间窗口检查结果
try:
from datetime import datetime
from .attend_window_helpers import log_attend_window_detail_check
now_str = datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S")
time_window_start_ts = ft - dynamic_ahead
time_window_start_str = (
datetime.fromtimestamp(time_window_start_ts).strftime("%Y-%m-%d %H:%M:%S")
if time_window_start_ts > 0
else "无效"
)
time_window_end_ts = ft + max(0.0, poll_before)
time_window_end_str = (
datetime.fromtimestamp(time_window_end_ts).strftime("%Y-%m-%d %H:%M:%S")
if time_window_end_ts > 0
else "无效"
)
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft > 0
else "无效"
)
log_attend_window_detail_check(
analyser,
now_ts,
focus_until,
ft,
dynamic_ahead,
join_ahead,
poll_before,
est_back_times,
)
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 详细检查",
now_ts=int(now_ts),
now_str=now_str,
focus_until=int(focus_until) if focus_until > 0 else 0,
target_future_ts=int(ft),
target_future_str=ft_str,
dynamic_ahead=dynamic_ahead,
join_ahead=join_ahead,
poll_before=poll_before,
est_back_times=est_back_times,
time_window_start=int(time_window_start_ts),
time_window_start_str=time_window_start_str,
time_window_end=int(time_window_end_ts),
time_window_end_str=time_window_end_str,
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
remain_seconds_to_window=(
int(time_window_start_ts - now_ts)
if time_window_start_ts > now_ts
else 0
),
in_lock_period=bool(focus_until > 0 and now_ts < focus_until),
in_time_window=bool(now_ts >= time_window_start_ts),
passed_time_window=bool(now_ts > time_window_end_ts),
)
except Exception:
pass
# 优化锁定期检查(详细规则见 helper docstring)
from .attend_window_helpers import handle_lock_period_same_reservation_check
# 优化锁定期检查:
# 1. 如果没有锁定期(focus_until = 0),直接允许检查时间窗口
# 2. 如果锁定期已过期(now_ts >= focus_until),允许检查时间窗口
# 3. 如果锁定期还没结束,但预约时间已经到了,检查是否是同一个预约
# - 如果是同一个预约,允许回退(通常已经在目标直播间了)
# - 如果不是同一个预约,不允许回退(需要等待当前预约完成)
# 4. 特殊情况:如果是队列满后立即参与模式(通过标志判断),允许检查时间窗口
# 先检查是否是队列满立即参与模式
is_queue_full_immediate_attend_check = False
try:
queue_full_waiting_check = bool(
getattr(analyser, "queue_full_waiting_at_earliest", False) or False
)
if queue_full_waiting_check:
is_queue_full_immediate_attend_check = True
except Exception:
pass
if (
focus_until > 0
and now_ts < focus_until
and abs(focus_until - now_ts) > 1.0
and not is_queue_full_immediate_attend_check
):
# 锁定期还没结束,检查是否是同一个预约(允许5秒误差)
expected_focus_until = ft + max(0.0, poll_before)
if abs(focus_until - expected_focus_until) > 5.0:
# 不是同一个预约,锁定期还没结束,不允许回退
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束且不是当前预约,跳过回退",
focus_until=int(focus_until),
expected_focus_until=int(expected_focus_until),
target_future_ts=int(ft),
lock_period_remain_seconds=int(focus_until - now_ts),
)
except Exception:
pass
return False
# 是同一个预约,即使锁定期还没结束,如果时间窗口到了,也允许回退
# 但这里通常已经在目标直播间了,需要检查是否已经在目标位置
# 获取当前实际的 room_pos(可能已经被更新)
try:
current_room_pos_check = int(
getattr(analyser, "room_pos", room_pos) or room_pos
)
except Exception:
current_room_pos_check = int(room_pos)
# 计算位置差
try:
target_pos_check = int(target.get("pos_seen") or 0)
except Exception:
target_pos_check = 0
pos_diff_check = current_room_pos_check - target_pos_check
# 如果已经在目标位置(pos_diff == 0),说明已经在目标直播间,不需要再次回退
# 但是需要检查时间窗口是否到达,如果到达了,应该返回 True 表示需要参与
# 或者如果是队列满立即参与模式,直接返回 True
if pos_diff_check == 0:
# 检查是否是队列满立即参与模式
is_queue_full_immediate_attend_pos = False
try:
queue_full_waiting_pos = bool(
getattr(analyser, "queue_full_waiting_at_earliest", False) or False
)
if queue_full_waiting_pos:
is_queue_full_immediate_attend_pos = True
except Exception:
pass
# 检查时间窗口是否到达,或者是队列满立即参与模式
if is_queue_full_immediate_attend_pos or (
now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before)
):
# 时间窗口已到达或队列满立即参与模式,虽然已在目标位置,但需要参与,返回 True
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束但是同一个预约,且已在目标位置,时间窗口已到达或队列满立即参与模式,需要参与",
focus_until=int(focus_until),
target_future_ts=int(ft),
current_room_pos=current_room_pos_check,
target_pos=target_pos_check,
now_ts=int(now_ts),
time_window_start=int(ft - dynamic_ahead),
time_window_end=int(ft + max(0.0, poll_before)),
is_queue_full_immediate_attend=is_queue_full_immediate_attend_pos,
)
except Exception:
pass
# 更新锁定期和待处理标志(如果不是队列满立即参与模式,才设置锁定期)
if not is_queue_full_immediate_attend_pos:
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:
write_state_callback()
except Exception:
pass
return True
else:
# 时间窗口未到达,跳过
# 注意:如果已经在目标位置但时间窗口未到,不应该设置 reservation_after_action_pending
# 因为这会导致反复等待,应该清除这个标志,让主循环正常处理
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束但是同一个预约,且已在目标位置,但时间窗口未到达,跳过回退并清除待处理标志",
focus_until=int(focus_until),
target_future_ts=int(ft),
current_room_pos=current_room_pos_check,
target_pos=target_pos_check,
now_ts=int(now_ts),
time_window_start=int(ft - dynamic_ahead),
time_window_end=int(ft + max(0.0, poll_before)),
)
except Exception:
pass
# 清除待处理标志,避免反复等待
if reservation_after_action_pending_ref:
reservation_after_action_pending_ref[0] = False
return False
# 如果不在目标位置,继续检查时间窗口
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束但是同一个预约,继续检查时间窗口",
focus_until=int(focus_until),
target_future_ts=int(ft),
current_room_pos=current_room_pos_check,
target_pos=target_pos_check,
pos_diff=pos_diff_check,
)
except Exception:
pass
lock_check_result = handle_lock_period_same_reservation_check(
analyser,
target,
ft,
now_ts,
focus_until,
room_pos,
dynamic_ahead,
poll_before,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
write_state_callback,
)
if lock_check_result is True:
return True
if lock_check_result is False:
return False
# 否则继续后续检查
# 检查是否是队列满后立即参与的情况(使用标志判断,而不是锁定期)
is_queue_full_immediate_attend = False
try:
# 检查队列满等待标志
queue_full_waiting = bool(
getattr(analyser, "queue_full_waiting_at_earliest", False) or False
)
if queue_full_waiting:
is_queue_full_immediate_attend = True
try:
analyser._log_kv(
"预约",
"[预约] 检测到队列满后立即参与模式(通过标志判断),跳过时间窗口检查,直接参与",
queue_full_waiting=queue_full_waiting,
target_future_ts=int(ft),
)
except Exception:
pass
except Exception:
pass
is_queue_full_immediate_attend = is_queue_full_immediate_attend_mode(analyser, ft)
if not is_queue_full_immediate_attend and now_ts < ft - dynamic_ahead:
# 还没到窗口(非队列满立即参与模式)
try:
from datetime import datetime
from .attend_window_helpers import log_time_window_not_yet
time_window_start_ts = ft - dynamic_ahead
time_window_start_str = (
datetime.fromtimestamp(time_window_start_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
if time_window_start_ts > 0
else "无效"
)
analyser._log_kv(
"预约",
"[预约] 时间窗口未到,跳过回退",
now_ts=int(now_ts),
now_str=datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S"),
time_window_start=int(time_window_start_ts),
time_window_start_str=time_window_start_str,
remain_seconds=int((ft - dynamic_ahead) - now_ts),
target_future_ts=int(ft),
dynamic_ahead=dynamic_ahead,
)
except Exception:
pass
log_time_window_not_yet(analyser, now_ts, ft, dynamic_ahead)
return False
if now_ts > ft + max(0.0, poll_before):
# 已明显错过开奖时间,交给统一清理逻辑
try:
analyser._log_kv(
"预约",
"[预约] 已明显错过开奖时间,清理过期预约",
future_ts=int(ft),
now_ts=int(now_ts),
poll_before=poll_before,
missed_seconds=int(now_ts - (ft + max(0.0, poll_before))),
)
except Exception:
pass
from .attend_window_helpers import log_missed_window
log_missed_window(analyser, now_ts, ft, poll_before)
cleanup_expired_reservations(analyser, reservations, write_state_callback)
return False
# 进入预约参与窗口:执行回退动作
try:
analyser._log_kv(
"预约",
"[预约] 进入预约参与窗口,准备回退到目标直播间",
future_ts=int(ft),
now_ts=int(now_ts),
room_pos=int(room_pos),
queue_len=len(reservations),
dynamic_ahead=int(dynamic_ahead),
est_back_times=int(est_back_times),
remain_seconds_to_open=int(ft - now_ts),
time_window_start=int(ft - dynamic_ahead),
time_window_end=int(ft + max(0.0, poll_before)),
)
except Exception:
pass
# 进入预约参与窗口:执行回退动作(含日志 + seek 回调 + 异常处理)
from .attend_window_helpers import execute_seek_reservation_with_logging
# 获取当前实际的 room_pos(可能已经被更新)
try:
current_room_pos = int(getattr(analyser, "room_pos", room_pos) or room_pos)
except Exception:
current_room_pos = int(room_pos)
# 计算位置差
try:
target_pos = int(target.get("pos_seen") or 0)
except Exception:
target_pos = 0
pos_diff = current_room_pos - target_pos
# 调用上层提供的"按预约信息回退到目标直播间"的回调
try:
analyser._log_kv(
"预约",
"[预约] 准备执行回退到预约直播间",
target_pos_seen=target_pos,
current_room_pos=current_room_pos,
pos_diff=pos_diff,
)
except Exception:
pass
# 直接调用回退回调,不需要预先下滑
# 原因:
# 1. 回退前已经进行了阶段诊断,处理了弹窗和福袋详情页等异常状态
# 2. 如果已经在直播间,不需要下滑
# 3. 预先下滑会导致 room_pos 减1,影响后续的回退计算,导致少回退一个直播间
ok = False
try:
ok = bool(seek_reservation_room_callback(target))
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
item=target,
reservations=reservations,
current_room_pos=current_room_pos,
target_pos=target_pos,
pos_diff=pos_diff,
),
level="ERROR",
stage="执行回退操作",
)
else:
try:
analyser._log_kv(
"预约",
"[预约] 执行回退时发生异常",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
ok = False
ok, current_room_pos, target_pos, pos_diff = execute_seek_reservation_with_logging(
analyser,
target,
reservations,
room_pos,
ft,
now_ts,
dynamic_ahead,
est_back_times,
poll_before,
seek_reservation_room_callback,
)
if ok:
from douyin.reservation.reservation_logic.attend_window_verify import (
handle_back_verify,
)
_verify_result = handle_back_verify(
analyser=analyser,
target=target,
reservations=reservations,
room_pos=room_pos,
ft=ft,
poll_before=poll_before,
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
reservation_after_action_pending_ref=reservation_after_action_pending_ref,
seek_reservation_room_callback=seek_reservation_room_callback,
write_state_callback=write_state_callback,
)
if _verify_result is not None:
return _verify_result
from .attend_window_helpers import process_seek_success
# 如果回退或校验失败,直接返回 False
if not ok:
try:
analyser._log_kv(
"预约",
"[预约] 回退或校验失败,保留队列以便后续重试或清理",
future_ts=int(ft),
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts),
target_pos=int(target.get("pos_seen", 0)),
current_room_pos=int(room_pos),
)
except Exception:
pass
try:
write_state_callback()
except Exception:
pass
return False
# 进入锁定期:在开奖附近一段时间内不再切换直播间
focus_until_new = ft + max(0.0, poll_before)
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = focus_until_new
else:
reservation_focus_until_ts_ref.append(focus_until_new)
if reservation_after_action_pending_ref:
reservation_after_action_pending_ref[0] = True
else:
reservation_after_action_pending_ref.append(True)
try:
from datetime import datetime
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft > 0
else "无效"
)
# 运行日志
analyser._log_kv(
"预约",
f"[预约] 已回退到目标直播间,等待详情识别与参与 - 直播间:'{target_room_title[:30] if target_room_title else ''}', 开奖时间:{ft_str}, 价值:{target_value}元",
future_ts=int(ft),
future_str=ft_str,
focus_until=int(focus_until_new),
lock_period_seconds=int(focus_until_new - _now_ts()),
remain_seconds_to_open=int(ft - _now_ts()),
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
target_content=target_content,
target_value_yuan=target_value,
)
# 行为日志
analyser._log_kv(
"行为",
"回退到预约直播间成功",
action="回退到预约直播间",
result="成功",
detail={
"目标直播间": (
target_room_title
if target_room_title
else target_room_title_raw
),
"目标直播间原始": target_room_title_raw,
"福袋内容": target_content,
"福袋价值": target_value,
"预计开奖时间": ft_str,
"预计开奖时间戳": int(ft),
"剩余秒数": int(ft - _now_ts()) if ft > _now_ts() else 0,
},
)
except Exception:
pass
# 不在这里弹出队列,等待真正"参与完毕"后由上层统一处理
try:
write_state_callback()
except Exception:
pass
# 添加函数完成日志
try:
from datetime import datetime
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 返回结果",
result="已触发回退",
future_ts=int(ft),
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
return True
if process_seek_success(
analyser,
target,
reservations,
ft,
now_ts,
room_pos,
poll_before,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
seek_reservation_room_callback,
write_state_callback,
start_time,
):
return True
return False
# 回退失败:记录日志,等待后续重试或清理
try:
analyser._log_kv(
"预约",
"[预约] 回退到预约直播间失败,保留队列以便后续重试或清理",
future_ts=int(ft),
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts),
target_pos=int(target.get("pos_seen", 0)),
current_room_pos=int(room_pos),
)
except Exception:
pass
from .attend_window_helpers import log_seek_failure_and_finish
try:
write_state_callback()
except Exception:
pass
# 添加函数完成日志
try:
from datetime import datetime
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 返回结果",
result="未触发回退",
future_ts=int(ft) if ft > 0 else 0,
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
log_seek_failure_and_finish(
analyser, target, ft, now_ts, room_pos, start_time, write_state_callback
)
return False
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
@@ -0,0 +1,420 @@
"""attend_window 中"回退校验失败 + 映射表二次回退"块的 helper
从 process_reservation_attend_window 中提取的最大独立块(约 375 行深嵌套)。
当 verify_ok=False 时执行映射表查找 → 二次回退尝试。
"""
from __future__ import annotations
from typing import Any, Callable, List, Optional
from ._common import (
ReservationItem,
_RESERVATION_ERROR_UTILS_AVAILABLE,
format_reservation_context,
log_reservation_error,
safe_write_state,
)
def handle_verify_failure_retry_via_mapping(
analyser: Any,
target: ReservationItem,
reservations: List[ReservationItem],
verify_detail: Any,
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],
) -> bool:
"""处理"回退校验失败 → 通过映射表二次回退"的逻辑。
流程:
1. 写"回退校验失败"日志(log_reservation_error 或 _log_kv)
2. 通过映射表查找目标和当前直播间位置
3. 计算映射差值,决定是否重试 seek
4. 如果重试成功 → 设置锁定期 + 待处理标志,返回 True
5. 如果重试失败 → 清理锁定相关标志,返回 False
返回:
True:第二次回退成功(调用方应直接 return True)
False:第二次回退失败或被跳过(调用方应直接 return False)
"""
if not verify_ok:
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 = 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 = None
mapped_current_pos = 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
# 尝试使用回退回调根据映射表差值重新回退
ok2 = False
should_retry_seek = True
mapped_pos_diff = 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
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
# 返回 True 表示回退成功
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
+99 -655
View File
@@ -128,230 +128,59 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
if pixel_threshold > 1.0:
pixel_threshold = 1.0
# ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)==========
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
# 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测
pixel_state = {}
pixel_details = {}
pixel_detection_start = time.time()
try:
result = analyser._read_pixel_stage_state(return_details=True)
if isinstance(result, tuple):
pixel_state, pixel_details = result
else:
pixel_state = result
pixel_details = {}
# 步骤0第一步:并行像素检测 + 详情日志记录
from douyin.stage.douyin_stage_step0 import run_parallel_pixel_detection
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
# 从并行检测结果中获取直播间图标检测结果
# 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间
live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False))
# 获取检测分数(白色像素比例)
pixel_confidence = 0.0
if "has_live_room_pixel" in pixel_details:
pixel_confidence = float(
pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0
)
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
if live_room_pixel_detected:
in_live_room = True
detection_method = "像素检测(多边形区域白色像素)"
live_room_score = pixel_confidence # 白色像素比例即为置信度
_log(
"步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
else:
# 像素检测未通过(直播间图标未命中)
in_live_room = False
detection_method = "像素检测未命中"
_log(
"步骤0[检测直播间]-像素检测未命中",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
# 简单策略:若检测到抽奖结果弹窗,也可视为在直播间(减少漏报)
try:
if pixel_state.get("has_lucky_draw_result", False):
# 如果并行检测里抽奖弹窗命中,则视为在直播间
in_live_room = True
detection_method = "抽奖结果弹窗(像素检测)"
# 尽量使用该项的置信度作为分数(回退为0.0)
try:
live_room_score = float(
pixel_details.get("has_lucky_draw_result", {}).get(
"confidence", 0.0
)
or 0.0
)
except Exception:
live_room_score = 0.0
_log(
"步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)",
抽奖弹窗置信度=round(live_room_score, 4),
)
except Exception:
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
pass
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
_log(
"步骤0[检测直播间]-最终结果:在直播间",
检测方法=detection_method,
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
# 记录每个检测步骤的详细信息
for key, detail in pixel_details.items():
step_name_map = {
"has_coupon_bg": "优惠券背景",
"has_redpacket_bg": "购物红包背景",
"has_lucky_draw_result": "抽奖结果弹窗",
"has_attend_button_red": "参与按钮红色区域",
"has_fansclub_join_red": "粉丝团加入红色区域",
"has_fudai_detail": "福袋详情页",
"has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)",
}
step_name = step_name_map.get(key, key)
detected = detail.get("detected", False)
method = detail.get("method", "unknown")
log_fields = {
"步骤": step_name,
"检测结果": "命中" if detected else "未命中",
"检测方法": method,
}
# 添加耗时信息
if "elapsed_ms" in detail:
log_fields["耗时(ms)"] = detail["elapsed_ms"]
# 添加分数信息
if "template_score" in detail and detail["template_score"] is not None:
log_fields["分数"] = round(detail["template_score"], 4)
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
# 对于像素检测,添加置信度信息
if "confidence" in detail and detail["confidence"] is not None:
if "分数" not in log_fields:
log_fields["分数"] = round(detail["confidence"], 4)
log_fields["置信度"] = round(detail["confidence"], 4)
# 如果是三部分识别,显示平均分和区域结果
if "avg_score" in detail and detail["avg_score"] is not None:
log_fields["平均分"] = round(detail["avg_score"], 4)
if "detected_parts" in detail and detail["detected_parts"]:
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
if "best_region" in detail and detail["best_region"]:
log_fields["最佳区域"] = detail["best_region"]
if "region_results" in detail and detail["region_results"]:
region_scores = detail["region_results"]
if isinstance(region_scores, dict):
log_fields["区域分数"] = (
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
)
# 对于像素检测,red_ratio也作为分数显示
if "red_ratio" in detail and detail["red_ratio"] is not None:
log_fields["红色比例"] = round(detail["red_ratio"], 4)
# 如果还没有分数,将red_ratio作为分数显示
if "分数" not in log_fields:
log_fields["分数"] = round(detail["red_ratio"], 4)
# 显示阈值(无论是否为None都显示,方便调试)
if "effective_threshold" in detail:
threshold_val = detail["effective_threshold"]
if threshold_val is not None:
log_fields["阈值"] = round(threshold_val, 4)
else:
log_fields["阈值"] = "未设置"
# 对于福袋详情页,额外显示配置的阈值(用于调试)
if key == "has_fudai_detail":
# 显示任务数量信息(无论是否为None都显示,便于调试)
if "task_count" in detail:
task_count_val = detail["task_count"]
log_fields["任务数量"] = task_count_val
# 如果任务数量存在但检测结果为False,记录警告
if (
task_count_val is not None
and task_count_val > 0
and not detected
):
try:
_log( # type: ignore[misc]
"警告:检测到任务数量但 has_fudai_detail 为 False",
任务数量=task_count_val,
detected=detected,
)
except Exception:
pass
else:
log_fields["任务数量"] = "未获取"
try:
configured_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
log_fields["配置阈值"] = round(configured_threshold, 4)
except Exception:
pass
if "reason" in detail:
log_fields["原因"] = detail["reason"]
if "error" in detail:
log_fields["错误"] = detail["error"]
_log(f"并行检测-{step_name}", **log_fields)
_log(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed,
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
pixel_state, pixel_details, in_live_room, live_room_score, detection_method = (
run_parallel_pixel_detection(
analyser,
in_live_room,
live_room_score,
detection_method,
pixel_threshold,
step_start,
_log,
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log(
"并行检测异常",
耗时毫秒=pixel_detection_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
pixel_state = {}
pixel_details = {}
# 步骤0结束计时
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复查
from douyin.stage.douyin_stage_helpers import (
verify_redpacket_outside_live_room,
)
redpacket_result = verify_redpacket_outside_live_room(
analyser,
pixel_state,
pixel_details,
enable_ocr_mode1,
max_step_time,
diag_start,
_log,
_log_summary,
preprocess_for_ocr,
)
if redpacket_result is not None:
return redpacket_result
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏)
from douyin.stage.douyin_stage_step3 import detect_tab_pages_via_ocr
return detect_tab_pages_via_ocr(
analyser,
enable_ocr_mode1,
max_step_time,
diag_start,
max_diag_time,
_log,
_log_summary,
_log_separator,
preprocess_for_ocr,
)
# ========== 在直播间:继续执行像素检测结果处理 ==========
_log_separator("在直播间,继续执行像素检测结果处理")
@@ -361,444 +190,60 @@ 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
# 优先级1+1.5:抽奖结果弹窗 + 购物红包弹窗 OCR 检测
from douyin.stage.douyin_stage_priority import detect_lottery_or_redpacket_popup
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)
# 优先级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,
说明="像素检测到购物红包背景",
)
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)
# ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)==========
step1_fudai_start = time.time()
# 从并行检测结果中获取福袋详情页检测结果(任务数量检测)
# 注意:即使 has_fudai_detail 为 False,pixel_details 中可能仍然有任务数量信息
detail_detected = bool(pixel_state.get("has_fudai_detail", False))
detail_task_count = None
# 尝试从 pixel_details 中获取任务数量(无论 has_fudai_detail 是否为 True)
if "has_fudai_detail" in pixel_details:
detail_task_count = pixel_details["has_fudai_detail"].get("task_count")
# 保存任务数量到 analyser 对象,供后续读取详情时使用
# 特殊处理:如果是点击验证触发的原因,总是保存检测结果(包括0和None)
if trigger_reason == "find_and_open_fudai_detail_click_verification":
try:
analyser._fudai_detail_task_count_from_stage = detail_task_count
try:
_log( # type: ignore[misc]
"阶段检测:设置任务数量到 analyser(点击验证)",
任务数量=detail_task_count,
触发原因=trigger_reason,
)
except Exception:
pass
# 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图
if detail_task_count is not None and detail_task_count > 0:
analyser._screenshot_ready_for_ocr = True
try:
_log( # type: ignore[misc]
"标记截图可复用(任务数量>0)",
任务数量=detail_task_count,
screenshot_ready=True,
)
except Exception:
pass
except Exception:
pass
elif detail_task_count is not None and detail_task_count > 0:
# 其他情况下,只有检测到有效的任务数量才保存
try:
analyser._fudai_detail_task_count_from_stage = detail_task_count
try:
_log( # type: ignore[misc]
"阶段检测:设置任务数量到 analyser",
任务数量=detail_task_count,
触发原因=trigger_reason,
)
except Exception:
pass
# 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图
if detail_task_count > 0:
analyser._screenshot_ready_for_ocr = True
try:
_log( # type: ignore[misc]
"标记截图可复用(任务数量>0)",
任务数量=detail_task_count,
screenshot_ready=True,
)
except Exception:
pass
except Exception:
pass
pass
try:
_log( # type: ignore[misc]
"保存任务数量到 analyser 对象",
任务数量=detail_task_count,
has_fudai_detail=detail_detected,
)
except Exception:
pass
# 如果任务数量为 None,记录警告日志
if detail_task_count is None:
try:
_log( # type: ignore[misc]
"警告:任务数量为 None,无法保存到 analyser 对象",
任务数量=None,
has_fudai_detail=detail_detected,
)
except Exception:
pass
else:
# pixel_details 中没有 has_fudai_detail 信息,记录警告
try:
_log( # type: ignore[misc]
"警告:pixel_details 中没有 has_fudai_detail 信息",
has_fudai_detail=detail_detected,
)
except Exception:
pass
# 如果并行检测到福袋详情页,直接返回
if detail_detected:
total_elapsed = (time.time() - diag_start) * 1000
_log_summary(
"阶段诊断完成(任务数量检测)",
阶段="FUDai_DETAIL",
原因="并行检测任务数量检测确认",
任务数量=detail_task_count,
总耗时毫秒=total_elapsed,
)
_log_separator("最终结果:FUDai_DETAIL(福袋详情页)")
return "FUDai_DETAIL", f"任务数量检测确认(任务数量={detail_task_count})"
# 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页)
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
# 暂时禁用:将默认值改为 False
enable_invite_redpacket_ocr = bool(
getattr(analyser, "enable_invite_redpacket_ocr", False)
lottery_or_redpacket_result = detect_lottery_or_redpacket_popup(
analyser,
pixel_state,
max_step_time,
diag_start,
max_diag_time,
_log,
_log_summary,
_log_separator,
preprocess_for_ocr,
)
template_match_score_threshold = float(
getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4
if lottery_or_redpacket_result is not None:
return lottery_or_redpacket_result
# 步骤1+1.5:福袋详情页(像素检测)+ 邀你抢红包(OCR 检测)
from douyin.stage.douyin_stage_step1 import detect_fudai_detail_or_invite_redpacket
fudai_detail_result = detect_fudai_detail_or_invite_redpacket(
analyser,
pixel_state,
pixel_details,
trigger_reason,
max_step_time,
diag_start,
max_diag_time,
_log,
_log_summary,
_log_separator,
preprocess_for_ocr,
)
# 获取模板匹配分数(如果存在),用于判断是否跳过OCR
template_match_score = float(
getattr(analyser, "_last_template_match_score", 0.0) or 0.0
if fudai_detail_result is not None:
return fudai_detail_result
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
from douyin.stage.douyin_stage_helpers import verify_popup_via_ocr
popup_result = verify_popup_via_ocr(
analyser,
pixel_state,
enable_ocr_mode1,
max_step_time,
diag_start,
max_diag_time,
_log,
_log_summary,
preprocess_for_ocr,
)
should_skip_redpacket_ocr = (
not detail_detected
and template_match_score > 0
and template_match_score < template_match_score_threshold
)
if should_skip_redpacket_ocr:
_log(
"步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)",
模板匹配分数=template_match_score,
阈值=template_match_score_threshold,
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间",
)
# 步骤1结束计时(像素检测福袋详情页)
step1_fudai_elapsed = (time.time() - step1_fudai_start) * 1000
_log("步骤1[像素检测福袋详情页]-完成", 总耗时毫秒=step1_fudai_elapsed)
if (
not detail_detected
and enable_invite_redpacket_ocr
and not should_skip_redpacket_ocr
):
step_ocr_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
ocr_max_step_time = float(
getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0
)
if remaining_time_before > ocr_max_step_time:
try:
_log(
"步骤1.5[OCR检测邀你抢红包]-开始",
剩余时间秒=remaining_time_before,
说明="在指定区域检测邀你抢红包文字",
)
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
cut_start = time.time()
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
# 保存完整截图并标注OCR区域
try:
from douyin.handlers import douyin_screenshot_manager
from douyin.core import path_config
import os
from PIL import Image
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
_raw = Image.open(pic_path)
try:
_raw.load()
pic_rgb = _raw.convert("RGB")
finally:
_raw.close()
width, height = pic_rgb.size
rx = int(
getattr(analyser, "resolution_ratio_x", 1080) or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400) or 2400
)
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
x1 = int(x1_base * width / rx)
y1 = int((y1_base + y_pianyi) * height / ry)
x2 = int(x2_base * width / rx)
y2 = int((y2_base + y_pianyi) * height / ry)
x1 = max(0, min(x1, width - 1))
y1 = max(0, min(y1, height - 1))
x2 = max(0, min(x2, width - 1))
y2 = max(0, min(y2, height - 1))
if x1 < x2 and y1 < y2:
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="阶段诊断邀你抢红包区域",
step="before_ocr",
coords=(x1, y1, x2, y2),
extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi,
},
)
if debug_path:
try:
_log(
"OCR识别前保存完整截图(阶段诊断邀你抢红包区域)",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
analyser.cut_pic(
*STAGE_RED_PACKET_OCR, "", "阶段诊断邀你抢红包区域", y_pianyi
)
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
ocr_start = time.time()
name_red0 = preprocess_for_ocr(
analyser, "阶段诊断邀你抢红包区域"
)
ocr_text = str(
analyser.operation.analyse_pic_word(name_red0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(ocr_text),
文本预览=ocr_text[:50] if ocr_text else "",
)
# 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(
getattr(analyser, "enable_ocr_mode1", True)
)
if enable_ocr_mode1 and (
not ocr_text
or not any(
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
)
):
if (
time.time() - step_ocr_redpacket_start
< ocr_max_step_time
):
name_red1 = preprocess_for_ocr(
analyser, "阶段诊断邀你抢红包区域"
)
ocr_text = str(
analyser.operation.analyse_pic_word(name_red1, 1)
or ""
)
_log(
"步骤1.5[OCR检测邀你抢红包]-OCR模式1",
文本长度=len(ocr_text),
文本预览=ocr_text[:50] if ocr_text else "",
)
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
redpacket_keywords = (
"邀你抢红包",
"邀你抢手气红包",
"邀你抢",
"抢红包",
"抢手气",
)
if ocr_text and any(
kw in ocr_text for kw in redpacket_keywords
):
redpacket_elapsed = (
time.time() - step_ocr_redpacket_start
) * 1000
total_elapsed = (time.time() - diag_start) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-命中",
耗时毫秒=redpacket_elapsed,
总耗时毫秒=total_elapsed,
OCR文本=ocr_text[:50],
)
_log_summary(
"阶段诊断完成(OCR检测邀你抢红包)",
阶段="FUDai_DETAIL",
原因="检测到邀你抢红包文字",
OCR文本=ocr_text[:50],
总耗时毫秒=total_elapsed,
)
return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)"
else:
redpacket_elapsed = (
time.time() - step_ocr_redpacket_start
) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-未命中",
耗时毫秒=redpacket_elapsed,
OCR文本=ocr_text[:50] if ocr_text else "",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log(
"步骤1.5[OCR检测邀你抢红包]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# 步骤1.5结束计时(OCR检测邀你抢红包)
step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
_log("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed)
# 所有像素检测完成,未命中任何特定阶段:检查是否有可疑弹窗背景需要 OCR 确认
from douyin.stage.douyin_stage_handler_pkg.popup_verification import (
verify_popup_via_ocr,
)
_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 popup_result is not None:
return popup_result
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
if in_live_room:
@@ -826,4 +271,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
+383
View File
@@ -0,0 +1,383 @@
"""阶段诊断辅助:步骤3 OCR弹窗确认 + 步骤2.5 购物红包OCR复查
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取的
两个相对独立的 OCR 复查块:
- verify_popup_via_ocr:步骤3,所有像素检测都未命中特定阶段、但像素检测到弹窗
背景特征(优惠券/购物红包)时,OCR 二次确认是否为弹窗。
- verify_redpacket_outside_live_room:步骤2.5,不在直播间但检测到购物红包背景
时,OCR 复查(支持模式0/模式1,置信度阈值)。
"""
from __future__ import annotations
import time
from douyin.fudai.core.coords import (
SHOPPING_REDPACKET_AREA,
COUPON_PARTICIPATE_BUTTON_ALT,
)
def verify_redpacket_outside_live_room(
analyser,
pixel_state: dict,
pixel_details: dict,
enable_ocr_mode1: bool,
max_step_time: float,
diag_start: float,
log_fn,
log_summary_fn,
preprocess_for_ocr,
):
"""步骤2.5:不在直播间,但像素检测到购物红包背景时的 OCR 复查。
Args:
analyser: fudai_analyse 实例
pixel_state: 像素检测结果字典
pixel_details: 像素检测详细信息
enable_ocr_mode1: 是否启用 OCR 模式1(关键词未命中时再跑模式1)
max_step_time: 单步最大耗时(秒)
diag_start: 阶段诊断起始时间戳
log_fn: 详细日志函数(_log)
log_summary_fn: 概要日志函数(_log_summary)
preprocess_for_ocr: OCR 预处理函数
Returns:
- (stage, reason) 二元组:检测到购物红包弹窗时
- None:未检测到(调用方继续后续逻辑)
"""
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_fn(
"步骤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
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_fn("步骤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_fn(
"步骤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_fn(
"步骤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_fn(
"步骤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_fn(
"步骤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_fn(
"阶段诊断完成(购物红包弹窗-非直播间复查)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(不在直播间)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
else:
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
log_fn("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
return None
def verify_popup_via_ocr(
analyser,
pixel_state: dict,
enable_ocr_mode1: bool,
max_step_time: float,
diag_start: float,
max_diag_time: float,
log_fn,
log_summary_fn,
preprocess_for_ocr,
):
"""步骤3:OCR确认弹窗。
Args:
analyser: fudai_analyse 实例
pixel_state: 像素检测结果字典
enable_ocr_mode1: 是否启用 OCR 模式1(并行执行模式0+模式1)
max_step_time: 单步最大耗时(秒)
diag_start: 阶段诊断起始时间戳
max_diag_time: 阶段诊断最大耗时(秒)
log_fn: 详细日志函数(_log)
log_summary_fn: 概要日志函数(_log_summary)
preprocess_for_ocr: OCR 预处理函数
Returns:
- (stage, 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
step_ocr_verify_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
log_fn(
"步骤3[OCR确认弹窗]-开始",
剩余时间秒=remaining_time_before,
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
)
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
if pixel_state.get("has_coupon_bg", False):
coupon_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
log_fn("步骤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 "")
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_fn(
"步骤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_fn(
"步骤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_fn(
"步骤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_fn(
"阶段诊断完成(优惠券弹窗-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_fn("步骤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_fn(
"步骤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_fn(
"步骤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_fn(
"阶段诊断完成(购物红包弹窗-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_fn(
"步骤3[OCR确认弹窗]-未匹配到弹窗",
耗时毫秒=ocr_verify_elapsed,
说明="OCR确认后未匹配,判定为直播间背景颜色",
)
# 步骤3结束计时(OCR确认弹窗)
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
log_fn("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
return None
+137
View File
@@ -0,0 +1,137 @@
"""阶段诊断辅助:步骤 1(抽奖结果弹窗)+ 步骤 1.5(购物红包弹窗)
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取的
两个相邻的 priority 检测块。
"""
from __future__ import annotations
import time
from douyin.fudai.core.coords import (
SHOPPING_REDPACKET_AREA,
)
def detect_lottery_or_redpacket_popup(
analyser,
pixel_state: dict,
max_step_time: float,
diag_start: float,
max_diag_time: float,
log_fn,
log_summary_fn,
log_separator_fn,
preprocess_for_ocr,
):
"""步骤 1(抽奖结果弹窗 OCR 确认)+ 步骤 1.5(购物红包弹窗 OCR 检测)。
返回:
(stage, reason) 二元组:检测到弹窗时
None:未检测到,调用方继续后续流程
"""
if pixel_state.get("has_lucky_draw_result", False):
step1_start = time.time()
log_separator_fn("步骤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_fn(
"阶段诊断完成(抽奖结果弹窗)",
阶段="FUDai_RESULT",
原因="像素检测+按钮OCR确认",
总耗时毫秒=total_elapsed,
)
log_separator_fn("最终结果:FUDai_RESULT(抽奖结果弹窗)")
return "FUDai_RESULT", "像素检测+按钮OCR确认"
else:
log_fn("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测")
except Exception as e:
log_fn(
"步骤1[检测抽奖结果弹窗]-简化OCR异常",
异常类型=type(e).__name__,
异常信息=str(e),
)
# 步骤1结束计时
step1_elapsed = (time.time() - step1_start) * 1000
log_fn("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed)
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
if pixel_state.get("has_redpacket_bg", False):
log_separator_fn("步骤1.5:检测购物红包弹窗")
step_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
log_fn(
"步骤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_fn("步骤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_fn(
"步骤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_fn(
"步骤1.5[检测购物红包弹窗]-OCR未识别到关键词",
说明="OCR未匹配,不判定为购物红包弹窗",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
log_fn(
"步骤1.5[检测购物红包弹窗]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
log_fn(
"步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗",
说明="需要OCR确认才能判定",
)
if redpacket_detected:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
log_summary_fn(
"阶段诊断完成(购物红包弹窗)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="检测到购物红包弹窗",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
# 步骤1.5结束计时
step15_elapsed = (time.time() - step_redpacket_start) * 1000
log_fn("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed)
return None
+231
View File
@@ -0,0 +1,231 @@
"""阶段诊断辅助:步骤 0 第一步(并行像素检测 + 详情日志记录)
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取。
基于一张截图并行采集所有像素特征(直播间图标、福袋详情页、抽奖结果、
优惠券背景等),然后逐项记录详情日志。
"""
from __future__ import annotations
import time
from typing import Tuple
def run_parallel_pixel_detection(
analyser,
in_live_room: bool,
live_room_score: float,
detection_method: str,
pixel_threshold: float,
step_start: float,
log_fn,
) -> Tuple[dict, dict, bool, float, str]:
"""步骤 0 第一步:并行像素检测 + 详情日志记录。
返回 (pixel_state, pixel_details, in_live_room, live_room_score, detection_method) 五元组。
"""
# ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)==========
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
# 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测
pixel_state = {}
pixel_details = {}
pixel_detection_start = time.time()
try:
result = analyser._read_pixel_stage_state(return_details=True)
if isinstance(result, tuple):
pixel_state, pixel_details = result
else:
pixel_state = result
pixel_details = {}
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
# 从并行检测结果中获取直播间图标检测结果
# 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间
live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False))
# 获取检测分数(白色像素比例)
pixel_confidence = 0.0
if "has_live_room_pixel" in pixel_details:
pixel_confidence = float(
pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0
)
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
if live_room_pixel_detected:
in_live_room = True
detection_method = "像素检测(多边形区域白色像素)"
live_room_score = pixel_confidence # 白色像素比例即为置信度
log_fn(
"步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
else:
# 像素检测未通过(直播间图标未命中)
in_live_room = False
detection_method = "像素检测未命中"
log_fn(
"步骤0[检测直播间]-像素检测未命中",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
# 简单策略:若检测到抽奖结果弹窗,也可视为在直播间(减少漏报)
try:
if pixel_state.get("has_lucky_draw_result", False):
# 如果并行检测里抽奖弹窗命中,则视为在直播间
in_live_room = True
detection_method = "抽奖结果弹窗(像素检测)"
# 尽量使用该项的置信度作为分数(回退为0.0)
try:
live_room_score = float(
pixel_details.get("has_lucky_draw_result", {}).get(
"confidence", 0.0
)
or 0.0
)
except Exception:
live_room_score = 0.0
log_fn(
"步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)",
抽奖弹窗置信度=round(live_room_score, 4),
)
except Exception:
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
pass
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
log_fn(
"步骤0[检测直播间]-最终结果:在直播间",
检测方法=detection_method,
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
# 记录每个检测步骤的详细信息
for key, detail in pixel_details.items():
step_name_map = {
"has_coupon_bg": "优惠券背景",
"has_redpacket_bg": "购物红包背景",
"has_lucky_draw_result": "抽奖结果弹窗",
"has_attend_button_red": "参与按钮红色区域",
"has_fansclub_join_red": "粉丝团加入红色区域",
"has_fudai_detail": "福袋详情页",
"has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)",
}
step_name = step_name_map.get(key, key)
detected = detail.get("detected", False)
method = detail.get("method", "unknown")
log_fields = {
"步骤": step_name,
"检测结果": "命中" if detected else "未命中",
"检测方法": method,
}
# 添加耗时信息
if "elapsed_ms" in detail:
log_fields["耗时(ms)"] = detail["elapsed_ms"]
# 添加分数信息
if "template_score" in detail and detail["template_score"] is not None:
log_fields["分数"] = round(detail["template_score"], 4)
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
# 对于像素检测,添加置信度信息
if "confidence" in detail and detail["confidence"] is not None:
if "分数" not in log_fields:
log_fields["分数"] = round(detail["confidence"], 4)
log_fields["置信度"] = round(detail["confidence"], 4)
# 如果是三部分识别,显示平均分和区域结果
if "avg_score" in detail and detail["avg_score"] is not None:
log_fields["平均分"] = round(detail["avg_score"], 4)
if "detected_parts" in detail and detail["detected_parts"]:
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
if "best_region" in detail and detail["best_region"]:
log_fields["最佳区域"] = detail["best_region"]
if "region_results" in detail and detail["region_results"]:
region_scores = detail["region_results"]
if isinstance(region_scores, dict):
log_fields["区域分数"] = (
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
)
# 对于像素检测,red_ratio也作为分数显示
if "red_ratio" in detail and detail["red_ratio"] is not None:
log_fields["红色比例"] = round(detail["red_ratio"], 4)
# 如果还没有分数,将red_ratio作为分数显示
if "分数" not in log_fields:
log_fields["分数"] = round(detail["red_ratio"], 4)
# 显示阈值(无论是否为None都显示,方便调试)
if "effective_threshold" in detail:
threshold_val = detail["effective_threshold"]
if threshold_val is not None:
log_fields["阈值"] = round(threshold_val, 4)
else:
log_fields["阈值"] = "未设置"
# 对于福袋详情页,额外显示配置的阈值(用于调试)
if key == "has_fudai_detail":
# 显示任务数量信息(无论是否为None都显示,便于调试)
if "task_count" in detail:
task_count_val = detail["task_count"]
log_fields["任务数量"] = task_count_val
# 如果任务数量存在但检测结果为False,记录警告
if (
task_count_val is not None
and task_count_val > 0
and not detected
):
try:
log_fn( # 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_fn(f"并行检测-{step_name}", **log_fields)
log_fn(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed,
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
log_fn(
"并行检测异常",
耗时毫秒=pixel_detection_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
pixel_state = {}
pixel_details = {}
# 步骤0结束计时
step0_elapsed = (time.time() - step_start) * 1000
log_fn("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed)
return pixel_state, pixel_details, in_live_room, live_room_score, detection_method
+347
View File
@@ -0,0 +1,347 @@
"""阶段诊断辅助:步骤 1(像素检测福袋详情页)+ 步骤 1.5(OCR 检测邀你抢红包)
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取。
"""
from __future__ import annotations
import time
from douyin.fudai.core.coords import (
STAGE_RED_PACKET_OCR,
)
def detect_fudai_detail_or_invite_redpacket(
analyser,
pixel_state: dict,
pixel_details: dict,
trigger_reason: str,
max_step_time: float,
diag_start: float,
max_diag_time: float,
log_fn,
log_summary_fn,
log_separator_fn,
preprocess_for_ocr,
):
"""步骤 1:从并行检测结果获取福袋详情页(任务数量检测)+ 步骤 1.5:OCR 检测邀你抢红包文字。
返回:
(stage, reason) 二元组:检测到福袋详情页时
None:未检测到,调用方继续后续流程
"""
# ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)==========
step1_fudai_start = time.time()
# 从并行检测结果中获取福袋详情页检测结果(任务数量检测)
# 注意:即使 has_fudai_detail 为 False,pixel_details 中可能仍然有任务数量信息
detail_detected = bool(pixel_state.get("has_fudai_detail", False))
detail_task_count = None
# 尝试从 pixel_details 中获取任务数量(无论 has_fudai_detail 是否为 True)
if "has_fudai_detail" in pixel_details:
detail_task_count = pixel_details["has_fudai_detail"].get("task_count")
# 保存任务数量到 analyser 对象,供后续读取详情时使用
# 特殊处理:如果是点击验证触发的原因,总是保存检测结果(包括0和None)
if trigger_reason == "find_and_open_fudai_detail_click_verification":
try:
analyser._fudai_detail_task_count_from_stage = detail_task_count
try:
log_fn( # type: ignore[misc]
"阶段检测:设置任务数量到 analyser(点击验证)",
任务数量=detail_task_count,
触发原因=trigger_reason,
)
except Exception:
pass
# 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图
if detail_task_count is not None and detail_task_count > 0:
analyser._screenshot_ready_for_ocr = True
try:
log_fn( # type: ignore[misc]
"标记截图可复用(任务数量>0)",
任务数量=detail_task_count,
screenshot_ready=True,
)
except Exception:
pass
except Exception:
pass
elif detail_task_count is not None and detail_task_count > 0:
# 其他情况下,只有检测到有效的任务数量才保存
try:
analyser._fudai_detail_task_count_from_stage = detail_task_count
try:
log_fn( # type: ignore[misc]
"阶段检测:设置任务数量到 analyser",
任务数量=detail_task_count,
触发原因=trigger_reason,
)
except Exception:
pass
# 如果任务数量 > 0,标记截图可以复用,避免OCR时重复截图
if detail_task_count > 0:
analyser._screenshot_ready_for_ocr = True
try:
log_fn( # type: ignore[misc]
"标记截图可复用(任务数量>0)",
任务数量=detail_task_count,
screenshot_ready=True,
)
except Exception:
pass
except Exception:
pass
pass
try:
log_fn( # type: ignore[misc]
"保存任务数量到 analyser 对象",
任务数量=detail_task_count,
has_fudai_detail=detail_detected,
)
except Exception:
pass
# 如果任务数量为 None,记录警告日志
if detail_task_count is None:
try:
log_fn( # type: ignore[misc]
"警告:任务数量为 None,无法保存到 analyser 对象",
任务数量=None,
has_fudai_detail=detail_detected,
)
except Exception:
pass
else:
# pixel_details 中没有 has_fudai_detail 信息,记录警告
try:
log_fn( # type: ignore[misc]
"警告:pixel_details 中没有 has_fudai_detail 信息",
has_fudai_detail=detail_detected,
)
except Exception:
pass
# 如果并行检测到福袋详情页,直接返回
if detail_detected:
total_elapsed = (time.time() - diag_start) * 1000
log_summary_fn(
"阶段诊断完成(任务数量检测)",
阶段="FUDai_DETAIL",
原因="并行检测任务数量检测确认",
任务数量=detail_task_count,
总耗时毫秒=total_elapsed,
)
log_separator_fn("最终结果:FUDai_DETAIL(福袋详情页)")
return "FUDai_DETAIL", f"任务数量检测确认(任务数量={detail_task_count})"
# 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页)
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
# 暂时禁用:将默认值改为 False
enable_invite_redpacket_ocr = bool(
getattr(analyser, "enable_invite_redpacket_ocr", False)
)
template_match_score_threshold = float(
getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4
)
# 获取模板匹配分数(如果存在),用于判断是否跳过OCR
template_match_score = float(
getattr(analyser, "_last_template_match_score", 0.0) or 0.0
)
should_skip_redpacket_ocr = (
not detail_detected
and template_match_score > 0
and template_match_score < template_match_score_threshold
)
if should_skip_redpacket_ocr:
log_fn(
"步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)",
模板匹配分数=template_match_score,
阈值=template_match_score_threshold,
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间",
)
# 步骤1结束计时(像素检测福袋详情页)
step1_fudai_elapsed = (time.time() - step1_fudai_start) * 1000
log_fn("步骤1[像素检测福袋详情页]-完成", 总耗时毫秒=step1_fudai_elapsed)
if (
not detail_detected
and enable_invite_redpacket_ocr
and not should_skip_redpacket_ocr
):
step_ocr_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
ocr_max_step_time = float(
getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0
)
if remaining_time_before > ocr_max_step_time:
try:
log_fn(
"步骤1.5[OCR检测邀你抢红包]-开始",
剩余时间秒=remaining_time_before,
说明="在指定区域检测邀你抢红包文字",
)
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
cut_start = time.time()
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
# 保存完整截图并标注OCR区域
try:
from douyin.handlers import douyin_screenshot_manager
from douyin.core import path_config
import os
from PIL import Image
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
pic = Image.open(pic_path)
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
)
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
x1 = int(x1_base * width / rx)
y1 = int((y1_base + y_pianyi) * height / ry)
x2 = int(x2_base * width / rx)
y2 = int((y2_base + y_pianyi) * height / ry)
x1 = max(0, min(x1, width - 1))
y1 = max(0, min(y1, height - 1))
x2 = max(0, min(x2, width - 1))
y2 = max(0, min(y2, height - 1))
if x1 < x2 and y1 < y2:
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="ocr",
picname="阶段诊断邀你抢红包区域",
step="before_ocr",
coords=(x1, y1, x2, y2),
extra_info={
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
"y_offset": y_pianyi,
},
)
if debug_path:
try:
log_fn(
"OCR识别前保存完整截图(阶段诊断邀你抢红包区域)",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
analyser.cut_pic(
*STAGE_RED_PACKET_OCR, "", "阶段诊断邀你抢红包区域", y_pianyi
)
cut_elapsed = (time.time() - cut_start) * 1000
log_fn("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
ocr_start = time.time()
name_red0 = preprocess_for_ocr(
analyser, "阶段诊断邀你抢红包区域"
)
ocr_text = str(
analyser.operation.analyse_pic_word(name_red0, 0) or ""
)
ocr_elapsed = (time.time() - ocr_start) * 1000
log_fn(
"步骤1.5[OCR检测邀你抢红包]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(ocr_text),
文本预览=ocr_text[:50] if ocr_text else "",
)
# 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(
getattr(analyser, "enable_ocr_mode1", False)
)
if enable_ocr_mode1 and (
not ocr_text
or not any(
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
)
):
if (
time.time() - step_ocr_redpacket_start
< ocr_max_step_time
):
name_red1 = preprocess_for_ocr(
analyser, "阶段诊断邀你抢红包区域"
)
ocr_text = str(
analyser.operation.analyse_pic_word(name_red1, 1)
or ""
)
log_fn(
"步骤1.5[OCR检测邀你抢红包]-OCR模式1",
文本长度=len(ocr_text),
文本预览=ocr_text[:50] if ocr_text else "",
)
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
redpacket_keywords = (
"邀你抢红包",
"邀你抢手气红包",
"邀你抢",
"抢红包",
"抢手气",
)
if ocr_text and any(
kw in ocr_text for kw in redpacket_keywords
):
redpacket_elapsed = (
time.time() - step_ocr_redpacket_start
) * 1000
total_elapsed = (time.time() - diag_start) * 1000
log_fn(
"步骤1.5[OCR检测邀你抢红包]-命中",
耗时毫秒=redpacket_elapsed,
总耗时毫秒=total_elapsed,
OCR文本=ocr_text[:50],
)
log_summary_fn(
"阶段诊断完成(OCR检测邀你抢红包)",
阶段="FUDai_DETAIL",
原因="检测到邀你抢红包文字",
OCR文本=ocr_text[:50],
总耗时毫秒=total_elapsed,
)
return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)"
else:
redpacket_elapsed = (
time.time() - step_ocr_redpacket_start
) * 1000
log_fn(
"步骤1.5[OCR检测邀你抢红包]-未命中",
耗时毫秒=redpacket_elapsed,
OCR文本=ocr_text[:50] if ocr_text else "",
)
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
log_fn(
"步骤1.5[OCR检测邀你抢红包]-异常",
耗时毫秒=redpacket_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
# 步骤1.5结束计时(OCR检测邀你抢红包)
step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
log_fn("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed)
return None
+314
View File
@@ -0,0 +1,314 @@
"""阶段诊断辅助:步骤3 OCR 推荐页/关注列表/直播列表检测
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取的
"步骤3:OCR 检测推荐页/关注列表/直播列表"独立块。
"""
from __future__ import annotations
import time
from douyin.fudai.core.coords import (
RECOMMEND_TAB,
FOLLOW_TAB,
LIVE_LIST_TAB,
)
def detect_tab_pages_via_ocr(
analyser,
enable_ocr_mode1: bool,
max_step_time: float,
diag_start: float,
max_diag_time: float,
log_fn,
log_summary_fn,
log_separator_fn,
preprocess_for_ocr,
):
"""步骤3:OCR 检测推荐页/关注列表/直播列表标签栏。
返回 (stage, reason) 二元组:
- "RECOMMEND_PAGE" / "FOLLOW_LIST" / "LIVE_LIST" / "IN_LIVE_ROOM"
无论命中哪个分支都返回,调用方应直接 return 该结果。
"""
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
log_fn(
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
)
t_recommend = ""
t_follow = ""
t_list = ""
try:
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
log_fn("步骤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_fn("步骤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_fn(
"步骤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_fn(
"步骤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_fn(
"步骤3[OCR推荐页标签栏]-命中推荐",
耗时毫秒=elapsed_recommend,
总耗时毫秒=total_elapsed,
识别文本=seen_text,
)
log_summary_fn(
"阶段诊断完成",
阶段="RECOMMEND_PAGE",
原因=f"标题='{t_recommend}'",
总耗时毫秒=total_elapsed,
)
log_separator_fn("最终结果:RECOMMEND_PAGE(推荐页)")
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果识别到"关注"但没有"推荐",可能是关注列表
if "关注" in t_recommend and "推荐" not in t_recommend:
log_fn(
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
精确区域="(658,147)-(765,194)",
)
step_start_follow = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
log_fn("步骤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_fn(
"步骤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_fn(
"步骤3[OCR关注列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
except Exception as e:
import traceback
log_fn(
"步骤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_fn(
"步骤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_fn(
"阶段诊断完成",
阶段="FOLLOW_LIST",
原因=f"标题='{t_follow}'",
总耗时毫秒=total_elapsed,
)
log_separator_fn("最终结果:FOLLOW_LIST(关注列表)")
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
# 如果识别到"正在直播"标签,判定为直播列表
if "正在直播" in t_recommend or (
"直播" in t_recommend
and "推荐" not in t_recommend
and "关注" not in t_recommend
):
log_fn(
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
精确区域="(650,145)-(800,195)",
)
step_start_list = time.time()
try:
ocr_start = time.time() # 初始化ocr_start
if time.time() - step_start < max_step_time:
cut_start = time.time()
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
log_fn("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
# else分支不需要,因为ocr_start已经在上面初始化了
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
log_fn(
"步骤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_fn(
"步骤3[OCR直播列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
except Exception as e:
import traceback
log_fn(
"步骤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_fn(
"步骤3[OCR直播列表]-命中",
耗时毫秒=elapsed_list,
总耗时毫秒=total_elapsed,
识别文本=list_text,
)
log_summary_fn(
"阶段诊断完成",
阶段="LIVE_LIST",
原因=f"标题='{t_list}'",
总耗时毫秒=total_elapsed,
)
log_separator_fn("最终结果:LIVE_LIST(直播列表)")
return "LIVE_LIST", "标题='{}'".format(t_list)
# 记录诊断时看到的"关注页标题"
try:
analyser._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
analyser._last_follow_list_title_text = ""
elapsed_total = (time.time() - step_start) * 1000
if elapsed_total > max_step_time * 1000:
log_fn(
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
耗时毫秒=elapsed_total,
阈值毫秒=max_step_time * 1000,
)
else:
log_fn(
"步骤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_fn(
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
耗时毫秒=elapsed_total,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
# 步骤3结束计时
step3_elapsed = (time.time() - step_start) * 1000
log_fn("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
log_summary_fn(
"阶段诊断完成",
阶段="IN_LIVE_ROOM",
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
总耗时毫秒=total_elapsed,
)
log_separator_fn("最终结果:IN_LIVE_ROOM(默认直播间)")
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
+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}")
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff. Show more