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
23 changed files with 9977 additions and 8894 deletions

No files matched your search

+129 -3655
View File
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
@@ -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
@@ -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
@@ -0,0 +1,156 @@
"""find_fudai 辅助:numpy 加速水平带扫描
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
使用 numpy 批量处理,从最优位置向左右两侧交替搜索福袋图标的特征颜色。
"""
from __future__ import annotations
import time
from typing import Any, Tuple
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, Any]:
"""numpy 加速扫描水平带,查找福袋图标的特征颜色。
返回更新后的 (detected, detected_x)。
"""
try:
import numpy as _np
# 计算检测区域,考虑分辨率缩放和偏移
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
y0 = 354 * ry // 2400 + y_pianyi_val
x1 = max(0, 157 * rx // 1080)
x2 = min(width, 410 * rx // 1080)
y_top = max(0, y0 - 3)
y_bottom = min(height, y0 + 4)
# 边界检查
if x1 < x2 and y_top < y_bottom:
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
# 双截图记录:保存实时操作截图(像素检测区域)
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
)
except Exception:
pass
arr = _np.array(roi)
if arr.size > 0:
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))
# 从最优位置开始,向左右两侧交替搜索
found_col = None
search_range = max(optimal_col, roi_width - optimal_col)
# 先检查最优位置本身
if valid_cols[optimal_col]:
found_col = optimal_col
else:
# 向左右两侧交替搜索
for offset in range(1, search_range + 1):
# 先检查右侧
right_col = optimal_col + offset
if right_col < roi_width and valid_cols[right_col]:
found_col = right_col
break
# 再检查左侧
left_col = optimal_col - offset
if left_col >= 0 and valid_cols[left_col]:
found_col = left_col
break
# 如果没找到,回退到原来的方法(从左到右)
if found_col is None:
found_col = int(_np.argmax(valid_cols))
col_idx = found_col
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
detected_x = int((x1 + col_idx) * 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
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
except (ImportError, ValueError, IndexError, AttributeError):
# numpy不可用或计算错误,回退到逐像素检测
detected = False
return detected, detected_x
@@ -0,0 +1,207 @@
"""find_fudai 辅助:逐像素扫描兜底
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
当 numpy 加速扫描未命中或不可用时,回退到原始逐像素检查。
"""
from __future__ import annotations
import time
from typing import Any, Tuple
def pixel_scan_fallback(
analyser: Any,
detected: bool,
detected_x,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
) -> Tuple[bool, Any]:
"""numpy 未命中或不可用时的原始逐像素检查兜底。
返回更新后的 (detected, detected_x)。
"""
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
# 获取最优搜索起始位置(使用历史记录或默认值)
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
# 确保最优位置在搜索范围内
optimal_x_scaled = max(
scan_x_start, min(optimal_x_scaled, scan_x_end - 1)
)
# 确保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
# 优化:从最优位置开始向左右两侧搜索
found_x = None
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
# 先检查最优位置本身
try:
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
# 如果最优位置没找到,向左右两侧交替搜索
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"
@@ -0,0 +1,257 @@
"""find_fudai 辅助:模板匹配兜底(OpenCV)
从 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, Tuple
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, Any]:
"""像素检测未命中时的 OpenCV 模板匹配兜底。
返回更新后的 (detected, detected_x)。
"""
# 像素检测未命中时,使用模板匹配作为兜底
if not detected or detected_x is None:
try:
import cv2
import numpy as np
# 获取模板路径
try:
from douyin.core import path_config
template_path = path_config.get_assets_dir() + "/fudai.png"
except Exception:
# 回退到旧路径(向后兼容)
base_dir = os.path.dirname(__file__)
template_path = os.path.join(base_dir, "assets", "fudai.png")
if os.path.exists(template_path):
# 获取匹配阈值
try:
template_threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
except Exception:
template_threshold = 0.7
# 读取模板
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is not None:
# 将PIL图片转换为OpenCV格式
pic_rgb = pic_new.convert("RGB")
screenshot_bgr = cv2.cvtColor(
np.array(pic_rgb), cv2.COLOR_RGB2BGR
)
# 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
x1 = max(0, 156 * rx // 1080)
x2 = min(width, 269 * rx // 1080)
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
if x1 < x2 and y_top < y_bottom:
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
if search_roi.size > 0:
th, tw = template.shape[:2]
rh, rw = search_roi.shape[:2]
# 保存搜索区域截图到 last_match.png
try:
base_dir = os.path.dirname(__file__)
pic_base = os.path.join(base_dir, "pic")
match_dir = os.path.join(pic_base, "template_match")
os.makedirs(match_dir, exist_ok=True)
last_match_path = os.path.join(
match_dir, "last_match.png"
)
# 保存截图并检查是否成功
save_success = cv2.imwrite(
last_match_path, search_roi
)
if save_success:
try:
analyser._log_kv(
"[找福袋图标] 已保存搜索区域截图",
loop=loop,
文件路径=last_match_path,
搜索区域尺寸=f"{rw}x{rh}",
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图失败",
loop=loop,
文件路径=last_match_path,
)
except Exception:
pass
except Exception as save_err:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图异常",
loop=loop,
错误类型=type(save_err).__name__,
错误信息=str(save_err),
)
except Exception:
pass
# 如果模板太大,缩小模板
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template = cv2.resize(
template,
(
max(1, int(tw * scale)),
max(1, int(th * scale)),
),
)
th, tw = template.shape[:2]
# 执行模板匹配
if th <= rh and tw <= rw:
res = cv2.matchTemplate(
search_roi, template, cv2.TM_CCOEFF_NORMED
)
_min_val, max_val, _min_loc, max_loc = (
cv2.minMaxLoc(res)
)
# 双截图记录:保存实时操作截图(搜索区域)
try:
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,
错误类型=type(e).__name__,
错误信息=str(e),
)
except Exception:
pass
return detected, detected_x
File diff suppressed because it is too large. Load diff
+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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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
File diff suppressed because it is too large. Load diff
+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", "不在直播间且未识别到特定页面,默认判定为在直播间"