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
CodexandClaude Opus 4.5 66eb05e6b1 补 reservation_logic.cleanup_validate 子模块单元测试(+10 用例)
- validate_back_to_reservation / cleanup_expired_reservations 函数签名验证
- reservation_logic 全部 6 个子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-22 01:22:56 +08:00
CodexandClaude Opus 4.5 5a40b49727 补 douyin_yanghao_pkg 剩余子模块单元测试(+7 用例)
- _scaled_click / _do_comment 函数签名验证
- douyin_yanghao_pkg 全部 3 个子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:48:38 +08:00
CodexandClaude Opus 4.5 266c7f2932 补 underlying_operations_pkg 剩余子模块单元测试(+14 用例)
- analyse_pic_digits / _swipe_with_sendevent_improved 函数签名验证
- underlying_operations_pkg 全部 10 个子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:45:46 +08:00
CodexandClaude Opus 4.5 59ac6a3abc 补 flow_control_pkg + orchestrator_pkg 子模块单元测试(+12 用例)
- find_and_open_fudai_detail 函数签名验证
- read_fudai_detail_once / read_fudai_detail_with_retries 函数签名验证
- flow_control_pkg / orchestrator_pkg 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:42:58 +08:00
CodexandClaude Opus 4.5 df628c11dd 补 douyin_fudai_finder_pkg 子模块单元测试(+15 用例)
- FudaiClickExecutor / FudaiDetailVerifier / FudaiImageAcquirer 类存在性验证
- check_have_fudai_with_ready_screenshot_optimized 函数签名验证
- douyin_fudai_finder_pkg 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:38:43 +08:00
CodexandClaude Opus 4.5 6996c7813e 补 screenshot_manager 子模块单元测试(+17 用例)
- _sanitize_filename_part 纯函数测试(无效字符/中文/路径)
- save_files / save_image 函数签名验证
- screenshot_manager 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:28:26 +08:00
CodexandClaude Opus 4.5 0efcfff545 补 reservation/core + fudai_modules 模块单元测试(+21 用例)
- format_reservation_context / validate_reservation_item 纯函数测试
- fudai_modules Mixin 类存在性验证
- reservation/core 包导入测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:24:15 +08:00
CodexandClaude Opus 4.5 b0eccc5171 补 bin 模块单元测试(+19 用例)
- format_size / get_log_base_names 纯函数测试
- parse_args 命令行参数解析测试
- manage_logs / run_cli 函数签名验证
- bin 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:21:03 +08:00
CodexandClaude Opus 4.5 e8bf904fc6 补 douyin/stage 模块单元测试(+23 用例)
- diagnose_stage_from_current_screen 函数签名验证
- StageHandler 类方法检查
- stage_handler_pkg shim 与子模块导出一致性验证
- stage 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:17:54 +08:00
CodexandClaude Opus 4.5 8d98143df1 补 douyin/core 模块单元测试(+24 用例)
- io_utils 纯函数测试(_verify_png_integrity/_ensure_parent_dir/_safe_replace_file)
- path_config 路径配置函数测试
- version 版本信息格式验证
- flow_control shim 与子模块导出一致性验证
- core 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:15:34 +08:00
CodexandClaude Opus 4.5 b5a15ecea4 补 douyin/other 模块单元测试(+28 用例)
- _normalize_room_title 纯函数测试(空格/数字/中文)
- high_value_room / popups / lottery 函数签名验证
- yanghao shim 与子模块导出一致性验证
- other 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:12:54 +08:00
CodexandClaude Opus 4.5 73008a9763 补 douyin/reservation 模块单元测试(+23 用例)
- _compact_text 纯函数测试(空格/中文/边界值)
- match_reservation / validate_back_to_reservation 函数签名验证
- reservation_handler shim 与子模块导出一致性验证
- reservation 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:09:35 +08:00
CodexandClaude Opus 4.5 5309aa0198 补 douyin/fudai 模块单元测试(+20 用例)
- is_abnormal_time_value 纯函数测试(边界值/异常值)
- validate_fudai_detail 函数签名验证
- fudai_detail shim 与子模块导出一致性验证
- fudai/core 子模块存在性测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:07:15 +08:00
CodexandClaude Opus 4.5 85d7bb2525 补 douyin/detection/pixel 模块单元测试(+14 用例)
- pixel/popups 弹窗检测函数签名验证
- pixel/buttons 按钮检测函数签名验证
- pixel/stage 阶段检测函数签名验证
- shim 与子模块导出一致性验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:03:35 +08:00
CodexandClaude Opus 4.5 3269d3adf6 补 gui/components 模块单元测试(+22 用例)
- log_color_config 纯函数测试(get_operation_type/get_color_config)
- mapping_utils 纯函数测试(_format_timestamp)
- gui/components 子模块存在性验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 22:00:02 +08:00
CodexandClaude Opus 4.5 7ef5bc3e07 补 douyin/logging 模块单元测试(+30 用例)
- log_formatter 纯函数测试(format_debug_log/action_log/error_log 等)
- PerformanceTracker 类测试
- logging 子模块存在性验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 21:56:43 +08:00
CodexandClaude Opus 4.5 2c8879be7a 补 douyin/fudai/core 模块单元测试(+14 用例)
- validate_coords 纯函数测试(边界/修正/无效坐标)
- safe_image_load 函数测试
- fudai/core 子模块存在性验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 21:53:47 +08:00
CodexandClaude Opus 4.5 6ecedbbde1 补 douyin/handlers 模块单元测试(+13 用例)
- _adb_path 纯函数测试(环境变量、引号处理、operation 对象)
- SwipeHandler / PopupHandler / ScreenshotHandler 类存在性验证
- swipe_ops 函数签名检查

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 21:50:02 +08:00
CodexandClaude Opus 4.5 cdf8be0ded 补 operations 模块单元测试(+18 用例)
- OCR 缓存机制测试(cache_get/put/clear/stats)
- _img_fingerprint 哈希函数测试
- screenshot_operations / screenshot_service 类存在性验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 21:42:39 +08:00
CodexandClaude Opus 4.5 a6dee879e7 补 tools/dev/bump_version.py 单元测试(+10 用例)
- parse_semver 纯函数测试(含边界/异常)
- compute_next 版本号递增测试
- 集成测试:连续 bump 验证

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 21:37:19 +08:00
CodexandClaude Opus 4.5 9f7e8da57a 补 reservation_handler_pkg / stage_handler_pkg 单元测试(+12 用例)
- 验证 shim 与 pkg 导出一致性
- Handler 类方法签名检查
- 子模块导入测试

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 21:25:50 +08:00
CodexandClaude Opus 4.7 6bdf7b2527 补 5 个剩余子包的综合测试(test_remaining_pkgs.py +20 用例)
覆盖 5 个之前没专门测试的拆分子包,每个写"API 兼容 + 不抛异常"级别的测试
(业务函数依赖大量 analyser 状态 + 真实截图,深度业务测试留给端到端):

- detection_pkg
  + _ensure_detection_cache 创建 _detection_cache 与 _detection_cache_ttl
  + _ensure_detection_cache 多次调用幂等(不覆盖既有 cache)
  + 4 个对外 API callable
- fudai_detail_orchestrator_pkg
  + read_fudai_detail_once / _with_retries 可调用
  + 兼容 shim 与子包指向同一函数对象
- logging_wrapper_pkg.misc
  + log_step_time / log_error_with_context / log_performance_step /
    log_debug_info 不抛异常
  + get_performance_stats 返回 dict
- flow_control_pkg
  + 4 个对外 API callable
  + 兼容 shim 与子包指向同一函数对象
- detect_by_template (module-level)
  + 签名 (analyser, rx, pic, region) 正确
  + FudaiDetector.detect_by_template 类方法仍可调用(forwarding)
- underlying_operations_pkg 第二轮新增
  + save_reward_pic / set_clipboard_text / _swipe_with_sendevent_improved /
    select_device / analyse_pic_digits 可调用
  + set_clipboard_text 空文本短路返回 False(不调用 ADB)

回归:
- 全套 627 → 647(+20 用例)
- 全部 647 passed in 19s
- compileall exit 0

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 21:04:14 +08:00
CodexandClaude Opus 4.7 af8145b8a8 补 fudai_filter_pkg / logging_pkg 单元测试 + 修 monitor 缺 datetime import
新增测试:
- test_fudai_filter_pkg (24)
  覆盖 helpers / should_skip / join_decision 三个子模块
  含 _is_short_countdown_text / is_watch_task_fudai / check_contain
  + should_skip_fudai_by_config 5 个业务场景断言(高价值通过 / 观看任务跳过 /
    低价值跳过 / 黑名单跳过 / 单间模式必参)
- test_logging_pkg (22)
  覆盖 _common 全局状态 + handlers 类构造 + cleanup 纯函数边界 + monitor
  类构造 + config 全部对外 API(get_logger 缓存 / get_caller_info /
  format_exception_info / LogContext / log_function_call 装饰器)

修复 1 个真实回归 bug:
- douyin/logging/douyin_logging_pkg/monitor.py 缺 from datetime import datetime
  (原文件用的是 from datetime import datetime, timedelta;拆分时只写了
  import 模块导致 datetime.now() 抛 NameError)
  修复后 LogRotationMonitor 可正常构造

回归:
- 全套 581 → 627 (+46 用例)
- 全部 627 passed in 22s
- compileall exit 0

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 21:01:15 +08:00
CodexandClaude Opus 4.7 e417acfb7c 为 10 个已拆出的子包补单元测试(+226 用例)
新增 tests/ 下 10 个测试文件,把已拆出的子包从"被外部测试间接覆盖"提升到
"独立可测":

- test_web_gui_pkg (52)
  覆盖 logger / ansi / adb_compat / nested / stats_helpers
  含 _wg_log/_LOGGER 日志、ANSI 清理、点号路径、_parse_countdown_seconds 等
- test_underlying_operations_pkg (35)
  覆盖 adb_helpers / bounds / countdown / ocr_content / pic_path
  含 _adb_path 环境变量覆盖、check_countdown 多种格式、OCR 字符纠错
- test_reservation_logic_helpers (21)
  覆盖 helpers.py 5 个纯函数(_now_ts / _normalize_room_title /
  _calculate_string_similarity / _extract_content_core /
  _sort_reservations_inplace 排序稳定性)
- test_screenshot_manager_pkg (47)
  覆盖 paths.get_category_for_picname(5 类关键词分类)+
  get_latest_attempt_path / get_last_success_path(按 operation_type 路径推断)
  + 异步计数器
- test_gui_core_pkg (13)
  覆盖 RunParams dataclass 28 字段构造 + adb 函数 + read_config / write_config
  roundtrip
- test_fudai_core_pkg (17)
  覆盖 _FudaiOcrExecutorState 单例 + _get_fudai_ocr_executor 缓存复用 + 11
  个 thin_wrappers 与原实现等价行为
- test_handler_shells (8)
  覆盖 ReservationHandler / StageHandler / LoggingWrapper 三个薄壳类的
  staticmethod forwarding 完整性
- test_yanghao_pkg (14)
  覆盖 _yanghao_log(_log_kv 优先 + logger fallback + broken analyser
  兜底 + 未知 level 不抛)+ yanghao_get_recommend_seconds 默认值
- test_pixel_common (6)
  覆盖 _safe_open_screenshot_rgb 用 tmp_path 构造合法/损坏/截断/RGBA PNG
- test_fudai_finder_pkg (13)
  覆盖 5 个类(FudaiImageAcquirer / FudaiDetector / FudaiClickExecutor /
  FudaiDetailVerifier / FudaiFinder)实例化与组合关系,verify
  detect_by_template 类方法签名仍兼容(拆出后)

回归:
- 全套测试 355 → 581(+226 用例)
- 全部 581 passed / 1 skipped in 27s
- 新拆出的 12 个子包现在都有专门的单元测试覆盖

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:54:35 +08:00
CodexandClaude Opus 4.7 2d928c3856 FudaiDetector.detect_by_template 拆出(957→655,瘦身 302 行)
把 douyin/fudai/douyin_fudai_finder_pkg/detector.py 的 FudaiDetector.detect_by_template
(306 行 / 4 个 self.X)搬到独立子模块 detect_by_template.py(321 行)。

策略:
- self.analyser → analyser(参数)
- self.rx → rx(参数)
- 类方法保留为 1 行 forwarding:
    def detect_by_template(self, pic, region):
        return _impl(self.analyser, self.rx, pic, region)
- detector.py 内顶部 import detect_by_template 模块的实现

回归:
- 2 个文件 compileall 通过
- pytest 355 passed / 1 skipped
- FudaiFinder() 实例化正常,FudaiDetector.detect_by_template 类方法仍可访问
- module-level detect_by_template 可独立调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:31:27 +08:00
CodexandClaude Opus 4.7 57d99f3459 拆分 douyin_fudai_core (2205 → 2124 + 3 个子模块)
把 douyin/fudai/douyin_fudai_core.py 中工具/兼容部分搬到
douyin/fudai/douyin_fudai_core_pkg/ 子包:

- ocr_executor (46)    _FudaiOcrExecutorState 类 + _fudai_ocr_executor_state
                       全局实例 + _get_fudai_ocr_executor 池复用函数
- thin_wrappers (65)   11 个 [兼容] 薄壳 forwarding 函数
                       (attend_choujiang / check_lucky_draw_result /
                        is_watch_task_fudai / should_skip_fudai_by_config /
                        basic_join_decision 等)

巨型 get_fudai_contain (2062 行) 留在原文件。原文件从子包 import 后
re-export,外部全部不需修改:
- should_skip_fudai_by_config 24 处外部引用
- attend_choujiang 15 处 / is_watch_task_fudai 13 处 / basic_join_decision 13 处
- 其他 1-10 处

回归:
- 4 个新/改文件 compileall 通过
- pytest 355 passed / 1 skipped(其中 2 个新 _is_short_countdown_text 测试也通过)
- attend_choujiang shim ⇄ pkg 同一对象
- should_skip_fudai_by_config(高价值) 返回 (False, 'ok')
- _fudai_ocr_executor_state.workers = 0 全局实例正常

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:25:34 +08:00
CodexandClaude Opus 4.7 a337b4b93d underlying_operations 第三轮拆分(2434 → 2351,再瘦身 83 行)
新增 2 个子模块:

- device_select (新, 73)  select_device 设备选择交互(无 self.X)
- ocr_digits (新, 49)     analyse_pic_digits 数字 OCR 识别
                         (保留 analyser 参数以调 analyser.analyse_pic_word)

策略:
- select_device 的 self.X 全是 _adb_path / _adb_args,已经是 module-level,
  搬出后改用 from .adb_helpers import _adb_path, _adb_args 即可。
- analyse_pic_digits 用 self.analyse_pic_word(递归调用类内大方法)。
  搬到 module-level 后第一参数从 self 改名 analyser,类内 forwarding
  传 self 即可,外部 op.analyse_pic_digits(picname) 完全兼容。

回归:
- 4 个新/改文件 compileall 通过
- pytest 353 passed / 1 skipped
- underlying_operations.select_device / analyse_pic_digits 类方法和 module-level
  函数都可访问

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:12:40 +08:00
CodexandClaude Opus 4.7 57eacb3219 underlying_operations 第二轮拆分(2582 → 2434,再瘦身 148 行)
新增 3 个子模块 + 1 个函数搬到已有子模块:

- adb_helpers (38)         新增 _adb_args(构造 adb -s 命令行)
- reward_pic (新, 73)      save_reward_pic(中奖截图保存)
- swipe_sendevent (新, 47) _swipe_with_sendevent_improved(sendevent 滑动)
- clipboard (新, 75)       set_clipboard_text(设备剪贴板设置)

策略:4 个方法的 self.X 引用都是 self._adb_path / self._adb_args 这种
"无状态工具方法",可以替换为 module-level 函数调用。类内方法保留为
1 行 forwarding 调用 _impl_X。

外部调用全部不需修改:
- save_reward_pic 4 处外部 self.save_reward_pic 仍工作
- _adb_args / _swipe_with_sendevent_improved / set_clipboard_text 0 外部引用

回归:
- 5 个新/改文件 compileall 通过
- pytest 353 passed / 1 skipped
- 类的 _adb_args / save_reward_pic / set_clipboard_text /
  _swipe_with_sendevent_improved 4 个 forwarding 全部正确

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:07:23 +08:00
CodexandClaude Opus 4.7 254820e6dc 拆分 underlying_operations (3021 → 5 子模块 + 2582 行原文件)
把 douyin/core/underlying_operations.py 中 6 个零 self 引用的方法搬到
douyin/core/underlying_operations_pkg/ 子包,类内方法变成 1 行 forwarding。
原文件保留 underlying_operations 巨型类(>50 个实例方法用 self)。

新建子包:
- adb_helpers (34)   _adb_path / _pick_adbkeyboard_ime
- pic_path (65)      _find_pic_path 按名称查找图片路径
- ocr_content (228)  extract_ocr_content OCR 文本拼接 + 置信度
- countdown (179)    check_countdown 倒计时文本解析(含 OCR 字符纠错)
- bounds (17)        _parse_bounds 解析 UI dump 的 [x1,y1][x2,y2]

策略:6 个方法的 self 引用全为 0,纯算法逻辑直接搬到 module-level;
类内对应方法保留装饰器和签名,body 改为 1 行 forwarding 调用:
  @staticmethod
  def _adb_path() -> str:
      return _impl_adb_path()

外部调用全部不需修改:
- ``self._find_pic_path(...)``         实例方法 forwarding 仍工作
- ``cls._adb_path()``                  staticmethod forwarding 仍工作
- ``ReservationHandler._parse_bounds(...)`` 外部 5 处引用零修改

修复发现:
- countdown.py 原本 ``import datetime``(应为 ``from datetime import datetime,
  timedelta``),导致 datetime.now()/timedelta() 触发 NameError 后被外层
  except 吞掉返回 False。修正后 check_countdown('5:30') 正确返回 (330, <ts>)
- 子模块内部用 _uo_log,加本地实现避免对原文件的循环依赖

回归:
- 6 个新文件 + 改写后 underlying_operations.py compileall 通过
- pytest 353 passed / 1 skipped
- check_countdown / extract_ocr_content / _parse_bounds /
  _pick_adbkeyboard_ime / _find_pic_path / _adb_path 6 个 forwarding 全部正确

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 19:54:22 +08:00
CodexandClaude Opus 4.7 246c80498e 拆分 douyin_yanghao (922 → 4 子模块 + 788 行原文件保留 yanghao_idle)
把 douyin/other/douyin_yanghao.py 中 6 个独立小函数拆出到
douyin/other/douyin_yanghao_pkg/ 子包,巨型函数 yanghao_idle (756 行)
留在原文件,从子包 import 拿 _yanghao_log/_scaled_click/_do_comment 用。

新建子包:
- logger (40)         _yanghao_log + module logger
- click_helpers (75)  _scaled_click / _do_comment
- entrypoints (82)    yanghao_recommend_flow / yanghao_wait /
                      yanghao_get_recommend_seconds
                      (yanghao_recommend_flow 通过 lazy import 调用 yanghao_idle)

外部 import 路径不变:
``from douyin.other.douyin_yanghao import yanghao_recommend_flow / yanghao_wait /
yanghao_get_recommend_seconds`` 等仍可用(原文件 from yanghao_pkg import * re-export)。
- _scaled_click 4 处外部引用 / _yanghao_log 1 处 / 其他 0 处

回归:
- 4 个新文件 + 改写后 douyin_yanghao.py compileall 通过
- pytest 353 passed / 1 skipped
- _yanghao_log() / yanghao_get_recommend_seconds() 调用结果正常

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 19:08:49 +08:00
CodexandClaude Opus 4.7 badf64998d 拆分 douyin_flow_control (706 → 4 个子模块 + 23 行 shim)
把 douyin/core/douyin_flow_control.py 4 个独立顶层函数拆成
douyin/core/douyin_flow_control_pkg/ 子包:

- stage_handler (34)  handle_stage_after_diagnosis 阶段后状态记录
- find_open (537)     find_and_open_fudai_detail 找福袋并打开详情(最大头)
- filter (85)         filter_fudai_detail 配置筛选决策
- no_fudai (94)       handle_no_fudai_situation 无福袋时的简单流程

原文件改为 23 行 re-export shim,4 个公共符号全部保留。
- find_and_open_fudai_detail 4 处外部引用,其他 0 处
全部不需修改。

回归:
- 5 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一函数对象

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 19:03:43 +08:00
CodexandClaude Opus 4.7 a6bbdcc400 拆分 web_gui (2251 → 5 子模块 + 2148 行原文件保留 ProcRunner/Handler/main)
把 gui/web_gui.py 中 11 个独立 helper 拆出到 gui/web_gui_pkg/ 子包,
ProcRunner 巨型类(1514 行 / 25 实例方法 / 390 处 self)+ Handler 类
(588 行)+ main 留在原文件。

新建子包:
- logger (29)         _wg_log + module logger
- ansi (17)           strip_ansi_escape_codes + _ANSI_ESCAPE_RE
- adb_compat (44)     5 个 thin wrapper(forward 到 gui.gui_core_pkg)
- nested (18)         get_nested_value(点号路径配置读取)
- stats_helpers (71)  _parse_countdown_seconds / _bucket / _inc_map(ProcRunner 3 个 @staticmethod)

策略:8 个顶层 helper 直接搬子包;ProcRunner 内 3 个 @staticmethod 也搬,
类内改成 1 行 @staticmethod forwarding 保持 ProcRunner._parse_countdown_seconds
等调用兼容。原文件 import gui.web_gui_pkg 暴露 11 个公共符号。

外部 import 路径全部不变:
- find_adb_executable / read_config / list_adb_devices 等共 70+ 处外部引用
  全部不需修改(CONFIG_PATH 17 处 / read_config 17 处 / find_adb_executable
  18 处 / list_adb_devices 21 处 / write_config 10 处 / 其他 1-7 处)

回归:
- 6 个新文件 + 改写后 web_gui.py compileall 通过
- pytest 353 passed / 1 skipped
- _wg_log / strip_ansi_escape_codes / get_nested_value 调用结果正确
- ProcRunner._parse_countdown_seconds('1:30') = 90 (薄壳 forwarding OK)
- ProcRunner._bucket(15, [0,10,50,100]) = '10-50'
- ProcRunner._inc_map(m, 'k', 5) -> {'k': 5}
- ProcRunner() 实例化 OK

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:57:52 +08:00
CodexandClaude Opus 4.7 ef6ca4a650 拆分 gui_core (1594 → 4 子模块 + 1207 行原文件保留 Runner)
把 gui/gui_core.py 中 12 个独立顶层函数 + RunParams dataclass 拆出到
gui/gui_core_pkg/ 子包;Runner 巨型类(1164 行 / 13 实例方法 / 用 self
状态)原文件保留,仅做 import re-export。

新建子包:
- adb (79)         find_adb_executable / list_adb_devices / resolve_adb_device
- wifi_adb (323)   7 个 WiFi-ADB 函数
- config (46)      CONFIG_PATH / read_config / write_config
- run_params (45)  RunParams dataclass

策略:Runner 类内部用了 find_adb_executable 等顶层函数,所以原文件
``gui/gui_core.py`` 通过 ``from gui.gui_core_pkg import *`` re-export
14 个公共符号供 Runner 内部和外部代码继续使用。

外部 import 路径全部不变:
``from gui.gui_core import find_adb_executable / RunParams / Runner`` 等
所有 14 个公共符号都保留。
- find_adb_executable 20 处外部引用 / read_config 17 处 / list_adb_devices
  16 处 / 其他 1-7 处,全部不需修改

回归:
- 5 个新文件 + 改写后 gui_core.py compileall 通过
- pytest 353 passed / 1 skipped
- find_adb_executable() 调用正常返回 adb.EXE 绝对路径
- read_config() 读到 126 个 config keys
- RunParams.is_dataclass = True,28 个字段
- Runner 类正确暴露

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:49:05 +08:00
CodexandClaude Opus 4.7 c442335b34 拆分 douyin_stage_handler (1009 → 5 个子模块 + 26 行 shim)
把 douyin/stage/douyin_stage_handler.py 的 StageHandler 类(4 个
@staticmethod)拆成 douyin/stage/douyin_stage_handler_pkg/ 子包:

- diagnose (37)        diagnose_stage_from_current_screen 阶段诊断分发
- check_live (774)     check_in_live_room_by_icon 直播间图标检测(最大头)
- handle_detail (20)   handle_in_fudai_detail 福袋详情页处理
- handle_room (195)    handle_live_room_has_or_not_fudai 直播间福袋检测分发
- handler (32)         StageHandler 类(薄壳,每个方法 1 行 forwarding)

策略:4 个方法都是 @staticmethod 第一参数 analyser,搬到 module-level 后
类方法变成 1 行 forwarding。类内部 0 互调,外部 3 处 StageHandler.method
(douyin_fudai.py / fudai_stage_detection.py)保持不变。

外部 import 路径不变:
``from douyin.stage.douyin_stage_handler import StageHandler`` 仍可用。

回归:
- 6 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- StageHandler.diagnose / module-level diagnose 都正确指向 wrapper / 实现

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:36:41 +08:00
CodexandClaude Opus 4.7 4ab1b88fa0 拆分 douyin_logging_wrapper (1080 → 6 个子模块 + 59 行 shim)
把 douyin/logging/douyin_logging_wrapper.py 的 LoggingWrapper 类(8 个
@staticmethod)按职责拆成 douyin/logging/douyin_logging_wrapper_pkg/ 子包:

- _common (76)     共享:colorama / 占位类 / 模块实例
- enhanced (380)   enhanced_log_kv 主入口
- simple (216)     _enhanced_log_kv_simple 简化版
- detailed (356)   _enhanced_log_kv_detailed 详细版(最大头)
- misc (151)       5 个小型辅助方法(log_step_time / log_error_with_context /
                   log_performance_step / log_debug_info / get_performance_stats)
- wrapper (55)     LoggingWrapper 类(薄壳,每个方法 1 行 forwarding)

策略:8 个方法全是 @staticmethod 第一参数 analyser,搬到 module-level 后
类方法变成 1 行 forwarding。类内部互调(enhanced_log_kv → simple/detailed,
log_error_with_context → enhanced_log_kv)改为直接 import module-level 函数。

外部 import 路径不变:
``from douyin.logging.douyin_logging_wrapper import LoggingWrapper`` 仍可用
(原文件改成 59 行 re-export shim,含 18 个共享符号 / 4 个占位类)。

回归:
- 7 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- LoggingWrapper.get_performance_stats / module-level 函数 / Fore/Style 占位
  全部能正常调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:32:03 +08:00
CodexandClaude Opus 4.7 85bd488f66 拆分 douyin_reservation_handler (1314 → 6 个子模块 + 29 行 shim)
把 douyin/reservation/douyin_reservation_handler.py 按职责拆成
douyin/reservation/douyin_reservation_handler_pkg/ 子包:

- find_room (169)       find_room_pos_by_title 按标题查找直播间位置
- record_title (333)    record_room_title_and_pos 记录直播间标题与位置
- seek_room (319)       seek_reservation_room 回退到目标预约直播间
- direct_attend (441)   handle_reservation_direct_attend 预约直接参与
- dump_state (180)      _dump_room_pos_map_to_state 序列化映射到 state 文件
- handler (43)          ReservationHandler 类(薄壳,每个 staticmethod 1 行 forwarding)

策略亮点:原 ReservationHandler 4 个方法都是 @staticmethod 且第一个参数为
analyser,搬出来成 module-level 函数后,类方法变成 1 行 forwarding。
公共 API 100% 保留:ReservationHandler.method(analyser, ...) 完全不需要改。

外部 import 路径不变:
``from douyin.reservation.douyin_reservation_handler import ReservationHandler``
仍可用(原文件改成 29 行 re-export shim)。
- ReservationHandler 5 处外部引用
- find_room_pos_by_title 2 处外部引用
- handle_reservation_direct_attend / _dump_room_pos_map_to_state 各 1 处
全部不需修改。

回归:
- 7 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- ReservationHandler.find_room_pos_by_title / module-level 函数 / 顶层
  _dump_room_pos_map_to_state 都能正常调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:21:40 +08:00
CodexandClaude Opus 4.7 7715b93eca fix(manage_logs): 修复 douyin_logging 拆分后的 import 回归
douyin/logging/douyin_logging.py 在 e35e8a8 commit 拆分为子包后,
原文件改成 re-export shim,不再"恰好"暴露 module-level 的 path_config
和全局变量 _log_monitor。

bin/manage_logs.py 之前依赖这两个间接 import:
  from douyin.logging.douyin_logging import path_config        # 副作用
  from douyin.logging.douyin_logging import _log_monitor       # 全局变量

修复:
- path_config 改为直接从源头导入:from douyin.core import path_config
- _log_monitor 改为从子包内部状态读取:
  from douyin.logging.douyin_logging_pkg import _common as _logging_state
  _log_monitor = _logging_state._log_monitor

回归:
- bin/manage_logs.py --help / monitor / stats 三个子命令全部正常
- pytest 353 passed / 1 skipped 不变

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:48:17 +08:00
CodexandClaude Opus 4.7 2523668b4c 拆分 douyin_fudai_finder (1816 → 6 个子模块 + 29 行 shim)
把 douyin/fudai/douyin_fudai_finder.py 按 5 个类 + 1 顶层函数拆成
douyin/fudai/douyin_fudai_finder_pkg/ 子包:

- image_acquirer (91)    FudaiImageAcquirer 截图获取与预处理
- detector (957)         FudaiDetector 多算法识别(最大头)
- click_executor (220)   FudaiClickExecutor 点击执行
- detail_verifier (237)  FudaiDetailVerifier 详情页打开验证
- finder (392)           FudaiFinder 4 个组件的组合入口
- optimized_entry (59)   check_have_fudai_with_ready_screenshot_optimized 顶层入口

原文件改为 29 行 re-export shim,6 个公共符号全部保留。
- check_have_fudai_with_ready_screenshot_optimized 2 处外部引用
- 其他类全部为 internal class composition,0 处外部引用

回归:
- 7 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一类对象
- FudaiFinder 实例化后内部组件正确(acquirer / detector / executor / verifier)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:34:19 +08:00
CodexandClaude Opus 4.7 e7faceeb5f 拆分 fudai_detail_orchestrator (1043 → 2 个子模块 + 17 行 shim)
把 douyin/fudai/core/fudai_detail_orchestrator.py 按 2 个独立顶层函数拆成
douyin/fudai/core/fudai_detail_orchestrator_pkg/ 子包:

- read_once (546)         read_fudai_detail_once 单次福袋详情识别
- read_with_retries (513) read_fudai_detail_with_retries 带重试版本

原文件改为 17 行 re-export shim,2 个公共符号全部保留。
- read_fudai_detail_once 5 处外部引用
- read_fudai_detail_with_retries 5 处外部引用
全部不需修改。

子包名 _pkg 后缀避免与同目录 shim 文件 fudai_detail_orchestrator.py 冲突。

回归:
- 3 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一函数对象

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:23:02 +08:00
CodexandClaude Opus 4.7 9d1b0c1e36 拆分 douyin_logging (1412 → 5 个子模块 + 46 行 shim)
把 douyin/logging/douyin_logging.py 按职责拆成
douyin/logging/douyin_logging_pkg/ 子包:

- _common (21)     共享全局状态:_logging_configured / _logger_cache / _log_monitor
- handlers (206)   自定义 handler:RotatingDatedFileHandler / DatedFileHandler
- cleanup (282)    日志压缩与清理:compress_log_file / cleanup_old_logs / _load_*_policy
- monitor (337)    轮转监控:LogRotationMonitor / start/stop_log_monitor / get_log_stats
- config (652)     主配置入口:get_logger / configure_logging / log_function_call /
                   LogContext / get_caller_info / format_exception_info

原文件改为 46 行 re-export shim,15 个公共符号全部保留。
全局变量统一搬到 _common,子模块通过 ``from . import _common as _state``
访问 _state.X 形式(global 不能跨模块)。

子包名 douyin_logging_pkg 是为了避免与同目录下的 shim 文件
douyin_logging.py 冲突(同名包 vs 模块在 Python 中不能并存)。

回归:
- 6 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(含 unified_logger MDC 13 个用例)
- 旧 import 路径与新子包路径返回同一函数对象
- get_logger 缓存机制(第二次调用返回同一对象)正常工作

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:13:34 +08:00
CodexandClaude Opus 4.7 74209035f7 拆分 douyin_reservation_logic (2702 → 7 个子模块 + 53 行 shim)
把 douyin/reservation/douyin_reservation_logic.py 按职责拆成
douyin/reservation/reservation_logic/ 子包:

- _common (57)             共享错误处理工具占位 + ReservationItem 类型
- helpers (130)            内部工具:标题归一化 / 相似度 / 排序 / 时间戳
- add (447)                add_reservation_core_logic 主入口(添加新预约)
- cleanup_validate (136)   validate_back_to_reservation / cleanup_expired_reservations
- queue_full (305)         handle_queue_full_wait_at_earliest 队列满时等待策略
- attend_window (1437)     process_reservation_attend_window 进入预约窗口(最大头)
- record (328)             record_high_value_reservation 高价值预约登记入口

原文件改为 53 行 re-export shim,17 个公共符号全部保留。
- process_reservation_attend_window 7 处外部引用
- handle_queue_full_wait_at_earliest 5 处外部引用
- _now_ts 5 处 / cleanup_expired_reservations 4 处 / _sort_reservations_inplace 4 处
- 其他 5 处以下
全部不需修改。

回归:
- 8 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一函数对象
- _now_ts / _normalize_room_title / _calculate_string_similarity 等纯函数
  调用结果与拆分前一致

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:03:55 +08:00
CodexandClaude Opus 4.7 787c4e8eec 拆分 douyin_detection (1756 → 3 个子模块 + 22 行 shim)
把 douyin/detection/douyin_detection.py 按职责拆成
douyin/detection/detection_pkg/ 子包:

- _common (14)    _ensure_detection_cache 共享缓存初始化
- detail (323)    check_detail_height + check_in_fudai_detail(详情页相关)
- finder (1438)   check_have_fudai_with_ready_screenshot(找福袋图标主入口,最大头)

原文件改为 22 行 re-export shim,4 个公共符号全部保留。
- check_in_fudai_detail 5 处外部引用
- check_have_fudai_with_ready_screenshot 3 处外部引用
- check_detail_height 2 处外部引用
全部不需修改。

子包名 detection_pkg 是为了避免与同目录下的 shim 文件 douyin_detection.py
潜在的命名混淆。

回归:
- 4 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一函数对象

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 16:55:24 +08:00
CodexandClaude Opus 4.7 19e347e6c1 拆分 fudai_filter (1090 → 3 个子模块 + 24 行 shim)
把 douyin/fudai/core/fudai_filter.py 按职责拆成
douyin/fudai/core/fudai_filter_pkg/ 子包:

- helpers (126)        小工具:_is_short_countdown_text / check_contain / is_watch_task_fudai
- should_skip (483)    should_skip_fudai_by_config 配置筛选总决策
- join_decision (524)  basic_join_decision 最终参与决策

原文件改为 24 行 re-export shim,5 个公共符号全部保留。
- check_contain 16 处外部引用
- should_skip_fudai_by_config 14 处外部引用
- is_watch_task_fudai 10 处外部引用
- basic_join_decision 7 处外部引用
- _is_short_countdown_text 5 处外部引用
全部不需修改。

子包名 fudai_filter_pkg 是为了避免与同目录下的 shim 文件 fudai_filter.py
循环 import(同名包 vs 模块在 Python 中不能并存)。

回归:
- 4 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(test_filter_logging 29 用例全过)
- 旧 import 路径与新子包路径返回同一函数对象

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 16:47:45 +08:00
CodexandClaude Opus 4.7 c0b8ff3ba6 拆分 douyin_pixel (1172 → 4 个子模块 + 33 行 shim)
把 douyin/detection/douyin_pixel.py 按职责拆成
douyin/detection/pixel/ 子包:

- _common (32)     _safe_open_screenshot_rgb
- popups (444)     优惠券 / 红包 / 抽奖结果弹窗检测
- buttons (340)    参与按钮 / 粉丝团加入红色区域检测
- stage (436)      直播间图标 / 福袋详情 / 综合阶段状态读取

原文件改为 33 行 re-export shim,9 个公共符号全部保留。
detect_fudai_detail_page 等 6 处外部引用、detect_attend_button_red_area
等 2 处外部引用全部不需修改。

回归:
- 5 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- 旧 import 路径与新子包路径返回同一函数对象

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 16:37:06 +08:00
CodexandClaude Opus 4.7 bf7f30996e 拆分 douyin_screenshot_manager (1705 → 6 个子模块 + 79 行 shim)
把巨型文件 douyin/handlers/douyin_screenshot_manager.py 按职责拆成
douyin/handlers/screenshot_manager/ 子包:

- _common (79)     共享 logger / 全局状态 / 异步计数器
- paths (205)      OCR 目录、调试存档目录、各类路径
- save_files (173) save_latest_attempt / save_last_success / save_*_from_file / cleanup_ocr_dir
- async_save (360) _debug_save_loop + 工作线程启停(global 状态走 _common._state.X)
- cleanup (293)    debug_captures 目录清理与轮转
- save_image (731) save_debug_image 主入口(最大头)

原文件改为 79 行 re-export shim,30 个公共符号全部保留。
外部 29 处 save_debug_image / 6 处 save_latest_attempt / 等
import 路径不变,零调用方修改。

回归:
- 子包 7 文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(与拆分前完全一致)
- 旧 import 路径与新子包路径返回同一函数对象
- AST 验证 30 个期望符号全部正确暴露

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 16:25:59 +08:00
CodexandClaude Opus 4.7 a6ce16f9c4 docs/README: 版本日志段引向 CHANGELOG.md + git tags + 发布流程
- 把 V3.0.0–V3.3.3 的散落条目统一到 CHANGELOG.md,README 只保留最近 3 个版本作为快照
- 加发布流程段:bump_version.py 用法 + test_version_consistency.py 守门
- 顶部链向 CHANGELOG.md 与 git tags 页面

回归:36 个路径引用全部存在;353 个测试通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:28:21 +08:00
CodexandClaude Opus 4.7 e35e8a85bd 建立版本管理体系:CHANGELOG + bump 脚本 + pyproject 元数据 + 一致性测试
新增:
- CHANGELOG.md:Keep a Changelog 1.1.0 格式,回填 V3.0.0–V3.3.3 历史
- tools/dev/bump_version.py:一键 bump major/minor/patch,
  同步 version.py / pyproject.toml / CHANGELOG.md,并创建 git tag。
  支持 --dry-run / --no-tag。
- tests/test_version_consistency.py:9 个用例确保
  version.py、pyproject.toml、CHANGELOG.md 三处版本号一致

修改:
- pyproject.toml 加 [project] 元数据,version=3.3.3(PEP 440 形式,
  与 douyin/core/version.py 同步;后者带 V 前缀,是单一事实来源)

后续会给 V3.0.0 → V3.3.3 补打 git tag。

回归:353 个 pytest 用例通过;bump_version dry-run 三种模式(patch/minor/major/set)
全部输出正确。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:17:56 +08:00
CodexandClaude Opus 4.7 778c021272 tests: 新增 param_usage_tracker 单元测试 (13 用例)
douyin/utils/param_usage_tracker:
  - track_param:写一条 / extra 字段合并 / 多次 append / unrepresentable 值兜底
  - track_call 装饰器:参数记录 / include_args=False / 保留 __name__ /
    异常正常传播 / kwargs 记录
  - read_entries:文件不存在 / 读回写入内容 / limit 限制 / 跳过坏行

用 monkeypatch 把 _get_log_path 重定向到 tmp_path,避免污染 state/。

回归:tests/ 344 passed / 1 skipped。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:11:54 +08:00
CodexandClaude Opus 4.7 ca4941b66d tests: 新增 ActionLogger + track_action 装饰器测试 (10 用例)
douyin/logging/action_logger:
  - ActionLogger 5 个 log_* 方法:log_step / log_operation / log_decision /
    log_state_change / log_ocr,覆盖带/不带 elapsed、含 kwargs 等场景
  - log_operation 大量 kwargs 不应导致格式化失败
  - track_action 装饰器:透传返回值、默认用函数名、异常正常传播、kwargs 透传

回归:tests/ 331 passed / 1 skipped。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:02:08 +08:00
CodexandClaude Opus 4.7 7d31075ce3 tests: 新增 PerformanceTracker 单元测试 (13 用例)
douyin/logging/performance_tracker.PerformanceTracker 6 个方法:
  - start_timer/end_timer:基本时长测量、未知 id 返回 0、二次 end 幂等
  - get_elapsed:进行中 / 未知 / end 后的行为
  - track_function:装饰器透传值 + 记录时长 + 异常路径仍记录
  - track_step:自定义 name 记录
  - get_statistics:空 / 多次平均

回归:tests/ 321 passed / 1 skipped。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:56:56 +08:00
CodexandClaude Opus 4.7 dba43e18f9 tests: 新增 check_contain + log_formatter 测试 (41 用例)
- test_check_contain.py:fudai_filter.check_contain 黑名单关键词检查
  * 空黑名单 / 命中 / 未命中 / None / 空字符串
  * 命中后短路(不继续遍历)
  * 黑名单空字符串关键词不误匹配
  * 缺 contains_not_want 属性 / broken _log_kv 兜底

- test_log_formatter.py:9 个格式化纯函数
  * format_action_log / format_debug_log / format_error_log(前缀 + tag + 字段)
  * format_parameters / format_variables / format_call_stack
  * format_exception(含 traceback)
  * add_colors(默认绿 / red / 未知颜色兜底)
  * add_separators(带/不带 label)
  * beautify_log_output / colorize_log_line(不抛 + 一致性)

回归:tests/ 308 passed / 1 skipped。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:45:49 +08:00
CodexandClaude Opus 4.7 a39da30d16 docs/README: 把 pic/ 与 douyin/core/state/ 的 markdown 链接改为内联代码
这些目录是 .gitignored 的运行时生成目录,仓库里不存在实体,
作为 markdown 链接会渲染成断链;改为内联代码 \`pic/\` /
\`douyin/core/state/reservations.json\` 表达"运行时路径"语义。

修复 3 处:调试技巧段、故障排查段、FAQ 高价值预约段。

回归:267 个 pytest 用例通过;README 33 个路径引用全部存在。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:35:46 +08:00
CodexandClaude Opus 4.7 601e701823 docs/README: 把 pic/ logs/ state/ 等运行时目录的 markdown 链接改为内联代码
这些目录在 .gitignore 里(运行时生成),通过 markdown 链接 [pic/](pic/) 跳转
没意义;改为 \`pic/\`、\`logs/\`、\`state/\` 内联代码标记,更准确。
顺手把 douyin/core/state/reservations.json 的链接也改为内联代码(同样在 .gitignore)。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:29:18 +08:00
CodexandClaude Opus 4.7 f6c9bb938c tests: 新增 reservation_error_utils 单元测试 (23 用例)
覆盖 douyin/reservation/core/reservation_error_utils 4 个工具函数:
  - format_reservation_context:空输入 / item / queue / 长字符串截断 /
    长队列截 5 项 / kwargs 合并 / 异常输入兜底
  - validate_reservation_item:合法项 / 缺字段 / 非字典 / 0/负值 /
    格式错误
  - safe_write_state:成功 / PermissionError / OSError / ValueError 路径
  - log_reservation_error:走 _log_kv / 无 analyser / broken analyser

回归:tests/ 267 passed / 1 skipped。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:25:35 +08:00
CodexandClaude Opus 4.7 872722522c docs/README: 系统性重构 + 修正 AI_PROJECT_SUMMARY 链接
- 系统性重写 README(1700+ 行 → 700 行):
  - 顶部加目录索引,主体改为表格 + 简明列表
  - 重新组织"快速开始"为三种启动方式(GUI / CLI / Web GUI),命令示例
    全部用 bin/<entry>.py 形式
  - 「核心功能」改为 11 项一行表格,配合超链接
  - 「技术架构」段简化为核心栈 + 检测层次表 + 架构图,删除冗长描述
  - 详细配置说明改为多个分组表格,命中率高
  - 引用 docs/ 子文档统一加 markdown 链接,便于跳转

- 修正过期链接:[docs/AI_PROJECT_SUMMARY.md] → [docs/archive/AI_PROJECT_SUMMARY.md]
  (main 上 PR #5 把它归档了,README 重写时引到了旧路径)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:25:12 +08:00
CodexandClaude Opus 4.7 87d0fe2db8 tests: 把 GUI ⇄ WebUI 配置同步检查纳入 pytest
包装 tools/diagnostics/check_web_gui_config_sync.py 为单元测试:
- test_gui_webui_keys_synced:用 check_sync() 检测 GUI 与 WebUI 配置 key 漂移;
  失败时打印 "缺哪些 key" + "怎么修复"
- test_manifest_shape:build_manifest() 应产出预期形状 + 共享 key 数量级合理

每次有人改 webui/index.html 或 gui/gui_app.py,pytest 都能立即发现 key 漂移,
避免之前那种"GUI 改了 WebUI 没改"的常见缺陷。

回归:tests/ 244 passed / 1 skipped。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:15:14 +08:00
CodexandClaude Opus 4.7 ecffba94b4 P3 §7: 引入 pytest 基础设施 + 9 个核心模块冒烟/单元测试
§7-1 pytest 基础设施
  - pyproject.toml 加 [tool.pytest.ini_options]
    (testpaths / python_files / strict markers / smoke + slow marker 注册)
  - tests/conftest.py 自动把项目根加到 sys.path

§7-2 核心模块测试(242 passed, 1 skipped)
  - test_filter_logging.py(重写为 pytest):should_skip_fudai_by_config
    + is_watch_task_fudai + _is_short_countdown_text 共 29 用例
  - test_time_utils.py:parse_mm_ss + extract_2digits 共 22 用例
  - test_douyin_text_utils.py:4 个 OCR 解析函数 25 用例
  - test_douyin_utils.py:extract_prize_value_yuan + normalize_countdown_text 21 用例
  - test_path_config.py:10 个路径函数结构断言 + 路径间互不重复 20 用例
  - test_logger_helpers.py:8 个 print→logger helper 的统一接口测试 20 用例
  - test_unified_logger_mdc.py:MDC 7 个方法 + 线程隔离 13 用例
  - test_io_utils.py:_verify_png_integrity / _safe_replace_file /
    _ensure_parent_dir 11 用例
  - test_imports.py:78 个核心模块的 import 冒烟 + 关键类/函数导出验证

修订老测试
  - test_ocr_comparison.py:用 pytest.importorskip 跳过缺失的 psutil/easyocr/paddleocr,
    并整体标 @pytest.mark.slow(需要 'pytest -m slow' 才会跑)
  - test_webgui.py:原会真的启 HTTP 服务卡死,改为 import 冒烟 + helper 调用测试

README
  - 重写 "## ✅ 测试" 段,给出实际可用的 pytest 命令、测试约定、marker 说明

回归:tests/ 142 项测试 PASS / 1 SKIP / 0 FAIL;全部纯函数 + 不依赖 ADB / OCR / 设备。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:09:02 +08:00
CodexandClaude Opus 4.7 818c3139b1 docs: 收尾 DEBUG_IMAGE_SYSTEM + ocr_engine_decision 路径
- DEBUG_IMAGE_SYSTEM.md: 'path_config.py' → 'douyin/core/path_config.py'
- ocr_engine_decision.md: 'Underlying_Operations.py' → 'douyin/core/underlying_operations.py'

至此活文档(除 docs/完整技术文档.md 头部对照表里的旧→新示例外)已无
裸路径残留。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:38:47 +08:00
CodexandClaude Opus 4.7 941bbc2475 docs: 命令行示例与核显说明改新路径
- docs/完整技术文档.md:7 处 'python run_cli.py …' 命令统一改为
  'python bin/run_cli.py …',与重构后入口位置对齐(头部小贴士那
  一行的示例字符串保留作为对照说明)
- docs/核显GPU加速说明.md:'修改 Underlying_Operations.py' 改为
  'douyin/core/underlying_operations.py'

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:35:19 +08:00
CodexandClaude Opus 4.7 c802f62796 docs/完整技术文档: 批量替换叙述性旧路径为新路径
把全文(除头部"路径迁移说明"对照表外)所有反引号包裹的旧路径标识符
更新为重构后位置:

- \`Underlying_Operations.py\` → \`douyin/core/underlying_operations.py\` (23 处)
- \`path_config.py\` → \`douyin/core/path_config.py\` (7 处)
- \`run_cli.py\` → \`bin/run_cli.py\` (15 处)
- \`unified_logger.py\` → \`douyin/logging/unified_logger.py\` (1 处)
- \`Underlying_Operations.<method>()\` → \`underlying_operations.<method>()\` (6 处)

头部 "⚠️ 路径迁移说明" 对照表内的旧路径作为示例保留。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:32:35 +08:00
CodexandClaude Opus 4.7 b6d2836e84 docs/完整技术文档: 可执行 import 示例改为新路径
8 处 from Underlying_Operations / from path_config / python -c "..."
示例改为 douyin.core.underlying_operations / douyin.core.path_config,
确保读者复制粘贴能跑通。

文档头部"路径迁移说明"表里左侧"旧"列保留旧路径作为对照;正文叙述性
提及(如 "见 Underlying_Operations.get_screenshot() 实现")暂保留,
读者依靠头部表对照即可。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:30:14 +08:00
CodexandClaude Opus 4.7 af4fc9168b docs/完整技术文档: fudai_detail_modules → douyin/fudai/core/fudai_detail_orchestrator
main PR b137aea 把 fudai_detail_modules/ 6 个模块合并到 douyin/fudai/core/,
其中 fudai_detail_reader.py 因与 core/ 已有同名文件冲突,重命名为
fudai_detail_orchestrator.py。

修订文档里 5 处旧引用:
- L155、L236:变更记录里的 fudai_detail_reader.py 改为新位置 + 标注旧路径
- L209:python -c 示例 import 改为新模块路径
- L256:py_compile 示例改为新文件路径
- L523:get_fudai_contain 调用位置改为新位置(顺手把"具体行号"改为
  "以代码当前状态为准",因为行号会随重构持续变化,硬编码价值低)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:26:24 +08:00
CodexandClaude Opus 4.7 a84ec29145 docs/DEBUG_IMAGE_SYSTEM: Underlying_Operations.py → douyin/core/underlying_operations.py
文件已迁移到 douyin/core/,文档里两处"实现位置"的路径修正为新位置。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:21:36 +08:00
CodexandClaude Opus 4.7 16d9bde4a0 docs/README: 修正版本徽章链接 version.py → douyin/core/version.py
文件已迁移到 douyin/core/version.py,徽章链接 (version.py) 是断链。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:18:58 +08:00
CodexandClaude Opus 4.7 e5c5ce06ee docs/README: 更新"添加新功能"指引段
- 把"在项目根目录创建 douyin_xxx.py" 改为按职责放到对应子包
  (douyin/core / douyin/fudai/core / douyin/detection 等)
- 把 douyin_fudai.py 标题改为 douyin/core/douyin_fudai.py
- 把 gui_app.py 标题改为 gui/gui_app.py
- 集成 GUI 后建议跑 tools/diagnostics/check_web_gui_config_sync.py 校验

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:17:10 +08:00
CodexandClaude Opus 4.7 20aefbb3a1 docs/README: 更新架构设计 ASCII 图反映重构后路径
- 用户界面层从 "gui_app.py / web_gui.py / run_cli.py" 改为
  "bin/run_cli.py / bin/gui_app.py / bin/webgui_launcher.py"
- 底层操作层从 "operations/ device/screenshot/ocr" 改为
  "douyin/core/underlying_operations.py + operations/ (向后兼容包装)"
  (删除已删的 device_operations.py 提及)
- 路径配置从 "path_config.py" 改为 "douyin/core/path_config.py"

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:15:14 +08:00
CodexandClaude Opus 4.7 ae3f276f56 docs/README: 更新模块说明段反映重构后路径
修订"代码结构 > 核心模块说明"段中的过期内容:

- douyin/logging/:把已删的 douyin_logger.py 替换为现存的 unified_logger.py /
  internal_loggers.py / action_logger.py / log_formatter.py / performance_tracker.py
- path_config.py:标题改为 douyin/core/path_config.py,补 get_high_value_rooms_path
- operations/:删掉已不存在的 device_operations.py,明确这是向后兼容包装层
- Underlying_Operations.py:标题改为 douyin/core/underlying_operations.py
- gui_app.py / web_gui.py:标题改为 gui/<file>.py(实现) + bin/<file>.py(启动器)
- run_cli.py:标题改为 bin/run_cli.py
- 补 bin/manage_logs.py 子段
- tools/:示例改成现实存在的 tools/diagnostics/ tools/coords/ 路径
- version.py:标题改为 douyin/core/version.py

douyin/other/:补登 douyin_high_value_room / douyin_live_room / douyin_lottery 三个模块

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:13:07 +08:00
CodexandClaude Opus 4.7 a46901ef5d docs: 修正"根目录有 launcher 转发"的错误说明 + 入口命令改为 bin/
实际情况:根目录已不再保留 run_cli.py / gui_app.py / webgui_launcher.py /
manage_logs.py 的 launcher 转发,这些入口脚本统一在 bin/ 下,必须以
'python bin/run_cli.py ...' 形式调用。

之前的提交里我把"路径迁移说明"写成"入口仍可从仓库根直接运行"是错的,
本提交修正:

- README.md
  - 项目架构段末尾的"历史小贴士"改为完整的迁移表,明确入口在 bin/ 下
  - 5 处 'python run_cli.py' / 'python gui_app.py' / 'python webgui_launcher.py'
    全部改为 'python bin/...' 形式(分别在快速开始、命令行用法、Web GUI 启动、
    Issue 模板、测试模式段)

- docs/完整技术文档.md
  - 头部"路径迁移说明"末尾的"仍可从仓库根直接运行"改为"必须用 bin/ 前缀"

文档里其他正文中的 'python run_cli.py …' 命令属于历史正文,迁移说明已在文档头部
统一指引读者改读为 bin/ 前缀,不再逐句修订(避免改动 7000+ 行文档主体)。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:10:07 +08:00
CodexandClaude Opus 4.7 9e189c711c docs/README: 重写"项目架构"段反映 2026-05 重构后实际结构
老版目录树包含大量过期路径:
  - 根目录 path_config.py / Underlying_Operations.py / run_cli.py(已迁到 douyin/core/ 与 bin/)
  - fudai_detail_modules/ 顶级目录(已被 main 上的 PR 整体删除)
  - operations/ 列出的 device_operations.py / image_operations.py 已删除
  - 缺失 bin/、缺 io_utils.py、缺 douyin/core/path_config.py 与 underlying_operations.py、缺 webui/、缺 fudai_modules 子模块清单

重写为反映现实结构 + 末尾加历史小贴士,让读者遇到旧路径时能查到对应位置。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:05:32 +08:00
CodexandClaude Opus 4.7 c5c8def884 underlying_operations: 52 处 print → _uo_log
- 新增模块级 _uo_log(msg, level):与项目其他 print→logger 改造一致的模式,
  优先走 logging(带 [OCR]/[截图]/[Underlying]/[警告]/[错误] 前缀),失败兜底 stdout
- 替换的内容包括:
  - OCR 引擎初始化 / 延迟初始化(PaddleOCR / EasyOCR 切换)
  - exec-out 截图 / 文件替换 / 回退方案的失败日志
  - 滑动操作失败 / ADB 输入注入异常
  - 中奖截图保存 / OCR 调试输出
  - paste_text_at / click 等底层操作的调试输出
- 保留为 stdout:
  - 设备选择交互(L220-247,含 input() 提示,需要用户在 stdout 看到)
  - _uo_log helper 自身的最终兜底(L73)

回归:146 .py 全量编译通过;underlying_operations 类与 _LOGGER 加载正确;
test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:54:27 +08:00
Codex 80b35bcb6c 精修 WebUI v34:换主色 — Cyber Lime → Amber × Royal Indigo
- 用户反馈不要绿色配色;切换为琥珀橙 + 靛蓝
- primary 浅 #65a30d → #f59e0b (amber-500),深 #a3e635 → #fbbf24 (amber-400)
- on-primary 全部用深字(#1a0f00)保证 amber 上可读
- warning 与 amber 撞色:改 #ea580c (orange-600) / 深色 #fb923c (orange-400) 拉开
- 浅色底从冷青米 #f7f8f3 改暖米 #fbf7ec;深色加微暖 #0c0a07 / #16140e
- mesh blob / shadow-glow / focus-ring / overview-primary-bg / log-bg 全部同步暖系
- 65 个 token + inline 装饰色(rgba 与 hex)批量换色,0 残留绿色
- favicon SVG 同步:amber 渐变 + 深字播放三角 + indigo 装饰圆点

cache-bust v33 → v34
2026-05-21 12:53:05 +08:00
CodexandClaude Opus 4.7 cc1d4f0897 P3: 删除 3 个永远 FAIL 的字符串匹配测试
这三个脚本都是 grep 源码字符串模式做"验证",匹配的代码模式在历次重构里
早已改名/拆分/删除,导致它们长期失败、永远不会再 PASS:

- tests/test_delays.py
  匹配的注释 "# 点击前延迟1秒" 已不存在于 douyin_yanghao.py

- tests/validation/validate_fudai_mapping_recording.py
  匹配的字符串如 "basic_join_decision:设置福袋信息并记录映射表"、
  "_record_room_title_and_pos" 已不存在

- tests/validation/validate_reservation_lock_protection.py
  匹配的 "参与成功,处理锁定期并移除预约"、"protection_seconds=10" 已不存在

继续保留只会误导新人;该补的是基于行为/接口的真单元测试(pytest 引入再说),
而不是字符串模式断言。tests/validation/ 目录因此变空,一并删除。

剩余 tests/test_filter_logging.py(业务函数测试)继续保留,仍 PASS。

回归:149 -> 146 .py,全量 compileall 通过;test_filter_logging /
check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:43:52 +08:00
Codex 5efa0ebc8b 精修 WebUI v33:字体切换 — IBM Plex Sans + IBM Plex Mono
- body font 从 Manrope 改 IBM Plex Sans (Google Fonts)
- mono 从 JetBrains Mono 改 IBM Plex Mono(21 处全替换)
- HTML preload 同步加载 IBM Plex Sans 400/500/600/700 + Plex Mono 400/500/600/700 + Plex Serif (备选)
- 工程感更强、字形更有性格,配 lime × indigo 色系更贴

cache-bust v32 → v33
2026-05-21 12:43:05 +08:00
Codex 0e74bfba77 精修 WebUI v32:换配色 + 全局放大字号
配色反转:粉/青 → Cyber Lime × Royal Indigo
- primary:#ec4899 (粉) → #65a30d (lime-700),深色 #f472b6 → #a3e635
- secondary:#06b6d4 (青) → #4f46e5 (indigo-600),深色 #22d3ee → #818cf8
- on-primary:#ffffff → #0a1502 / #06120a (lime 上需深字保证可读性)
- 浅色 base 改暖青米白 #f7f8f3,深色改深炭蓝 #0a0c10 / #12161e (整体更冷静)
- mesh blob / shadow-glow / focus-ring / status ring 等所有彩色装饰同步换色
- favicon SVG 也同步:lime 渐变 + indigo 圆点

字号 / 控件全局放大
- token: text-xs 11→12, sm 12→13, base 13→15, md 14→16, lg 16→18, xl 22→24, 2xl 32→36
- leading-snug 1.35→1.4, leading-normal 1.5→1.55
- control-height 34→38px, rail-width 216→232px
- 硬编码 font-size 全部 +2px(脚本批量映射 9→11..16→18,反向顺序避免链式覆盖)
- min-height 30/32/34/36 → 32/34/36/38

cache-bust v31 → v32
2026-05-21 12:39:42 +08:00
CodexandClaude Opus 4.7 c92af75d02 docs/完整技术文档: 头部加路径迁移说明
文档主体(7363 行)撰写于项目大重构之前,正文中仍存在大量旧路径
(Underlying_Operations.py / path_config.py 在根目录,run_cli.py / gui_app.py
不在 bin/ 等)。全面改写风险高,改为在文档头部加一段醒目的"路径迁移说明",
列出新旧路径映射,让读者遇到旧路径时能查得到对应位置。

收益:
  - 不破坏现有内部链接 / 锚点
  - 读者一眼就能找到新旧路径对照
  - 入口脚本(bin/)仍有根目录 launcher,文档里 python run_cli.py 命令仍可用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:18:58 +08:00
CodexandClaude Opus 4.7 6ac99530d6 docs/README: 补登 ocr_engine_decision.md
main PR #6 新增了 docs/ocr_engine_decision.md(OCR 引擎选型决策记录),
但 docs/README.md 索引未同步。补到「系统说明(活文档)」分组。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:15:51 +08:00
CodexandClaude Opus 4.7 0c62696118 P3: 清理过期 TODO + 修正过期路径注释
- operations/__init__.py:
  - 模块描述里 "Underlying_Operations.py 模块化" 改为
    "douyin/core/underlying_operations.py 模块化拆分"(原文件已迁移)
  - 删除 "TODO: 逐步迁移后改为从子模块导入"——
    导入是有意保留的向后兼容层,不是待办

- douyin/reservation/core/__init__.py:
  - 删除 "临时导入" "TODO: 迁移完成后改为从子模块导入"
  - 这个 re-export 层也是有意保留的向后兼容设计

回归:140 .py 编译通过;operations + reservation.core 模块加载 OK;
test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:13:31 +08:00
Codex 9c3cf86f41 精修 WebUI v31:运行状态指示 / tab burst / 截图入场 / 数字千分隔符
logHeader 状态 pill
- logTitle ::before 圆点改 6px 渐变(粉→青)+ 6px primary halo
- ::after 加状态 chip:默认 "PAUSED" muted;body.is-running 时切 "● LIVE"(success 色 + glow border)

侧边导航 burst 反馈
- tab 切换时 sideNav 加 isBurst 类 380ms,触发 ::before 横/纵向 scaleY 1.3 / scaleX 1.6 的脉冲 + 光晕加强(10→18px)
- 同 tab 二次点击不触发;prefers-reduced-motion 下不动

截图入场动画
- preview img 从 opacity 0 + scale(0.985) → opacity 1 + scale(1),280ms 缓出
- 删除一处旧的重复规则

数字千分隔符
- 新增 fmtNum() 工具函数(toLocaleString en-US 千分隔,PID/Trace 不走)
- statLogLen / 9 个福袋统计 / 跳过 / 切换直播间 / 粉丝团等字段全部 fmt 化
- 大数字现在显示 "12,345" 风格,配合 JetBrains Mono tabular-nums 更易读

cache-bust v30 → v31
2026-05-21 12:11:09 +08:00
CodexandClaude Opus 4.7 0d01dabb69 P2 §5.3: 23 处 importlib.import_module → 静态 from import
把剩余 5 个文件里所有动态导入 douyin_screenshot_manager 的 importlib 调用
替换为顶部静态 from import 模式:

  - douyin/detection/douyin_pixel.py        7 处
  - douyin/detection/douyin_detection.py    8 处
  - douyin/fudai/douyin_fudai_finder.py     4 处
  - douyin/fudai/core/fudai_attend.py       2 处
  - gui/gui_app.py                          2 处

douyin_screenshot_manager 只引用 douyin.core.path_config,与上述 5 个文件
无循环依赖。bin/run_cli.py 的剩余 1 处 importlib 是有意为之
(绕过 package __init__ 遮蔽),保留。

收益:
  - 可读性 + IDE 跳转/类型提示
  - 每次调用省去 ~100µs 的 import_module 开销(detection 模块在热路径上调用密集)
  - 死代码减少 ~92 行(5 个文件合计 -115 / +23)

回归:140 .py 编译通过;importlib 残留只剩 bin/run_cli 故意 1 处;
5 个模块导入 + fudai_analyse + should_skip_fudai_by_config 业务链路正常;
test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:06:23 +08:00
Codex 7001919642 精修 WebUI v30:进程心跳 / 滚动条 / 骨架 / 取景器 hover / SVG glow
全局 running 信号
- body.is-running 在视口顶部 fixed 2px 粉→青→粉横向 sweep glow line
- 2.8s 横向滚动 + 4px primary drop-shadow,进程"心跳"信号

滚动条
- 全局 webkit-scrollbar-thumb 改 180deg 粉→青渐变(55% mix)
- hover 升级为纯色 primary→secondary 渐变

骨架屏
- shimmer 渐变改为粉/青双色横扫(35% / 65% 节点 22% mix)
- 节奏 1.6s → 1.8s 更柔和

截图区取景器
- previewBracket hover 时 18→22px + drop-shadow 6→10px primary 75%
- 尺寸 + glow 同步过渡

Timeline 折线
- SVG defs 加 feGaussianBlur (1.6) + feMerge glow filter
- 折线 stroke-width 1.5→1.8 并应用 filter,霓虹光晕
- 与 chart hover 渐变协同

cache-bust v29 → v30
2026-05-21 12:03:44 +08:00
Codex 95255a4498 精修 WebUI v29:tooltip / 小按钮 hover / toggle / chevron / 深色复查
Tooltip
- 字体改 JetBrains Mono 10px 0.04em + text-strong;padding 加大;border 改 primary 35% mix
- box-shadow 三层:1px primary 描边 + 14px primary 40% halo + blur 10px
- 箭头方块同步换 primary 描边 + 90% mix 背景

小图标按钮统一 hover glow
- copyBtn / toastClose / shortcutsClose hover 改 primary 染色 + primary-soft 60% 背景 + 10px primary 45% halo
- 比之前的 muted 灰更有反馈感

Toggle switch
- checked 状态从单色 primary 改 90deg 粉→青渐变 + 12px primary 55% halo
- 圆球 thumb checked 时加 8px primary 40% glow
- focus-visible 在 focus-ring 之外再叠 12px primary halo

details/summary chevron
- 从 currentColor mask 改 linear-gradient (粉→青) mask + drop-shadow 4px primary 50%
- open 时旋转 90° + halo 升至 6px 70%
- 尺寸 10px → 14px

深色主题对比度复查
- mesh blob 不透明度全部 -2%(0.16/0.14/0.12 → 0.14/0.12/0.10),避免大背景过亮干扰阅读
- grain noise opacity:浅色 0.4→0.28,深色 0.6→0.35,保留质感但降低噪点强度

cache-bust v28 → v29
2026-05-21 12:03:44 +08:00
Codex 540ee24861 精修 WebUI v28:主容器 / panel / stat 卡 / 浮动按钮整体升级
主 Header
- 加 4% primary 顶部渐变 + radius-lg 顶部 hairline 改 65/65% 粉→青双色
- isScrolled 时边框改 primary-border + 24px primary halo box-shadow
- ::after 加 1px sweep glow line(200% 横向,6s 循环),仅 isScrolled 时 0.45 不透明显示
- secondaryActions 分隔线改渐变(透明→粉→透明),margin 增大

panel 容器
- 加 radial 双角光晕(左上粉 6% + 右下青 5%)+ surface
- 顶部 hairline 60% 双色渐变
- padding 18→22/24px 给装饰呼吸空间
- hover 时 border 30% primary mix(subtle)

工作区标题
- Eyebrow 字体改 JetBrains Mono 10px 0.18em + 6px 渐变圆点 + glow
- workspaceTitle 字号从 text-xl(22) 升至 26px + 700 weight + -0.02em 字距

stat 卡片
- 普通 stat:position relative + ::after 顶部 hairline (hover 时显示) + ::before 左侧 2px accent (跟 stateOk/Warn/Error 自动着色)
- hover 改 primary-soft 30% mix + 18px halo + 1px primary 描边
- statHero:加 8% primary radial + primary 22% border + 12% inner ring + 35% halo;::before accent 强制 primary→secondary 渐变
- statValue 字距 -0.015 → -0.025

浮动按钮
- scrollTopBtn 36→38px;border 用 primary 30% mix;背景加 radial 16% primary 圆光
- box-shadow 16px primary 30% halo;hover 时升至 24px 50% halo + 颜色全染 primary

cache-bust v27 → v28
2026-05-21 12:03:44 +08:00
Codex b161a2c4a6 精修 WebUI v27:表单焦点光晕 + 图表渐变 + 浮层质感
表单 / 输入控件
- input/select/textarea caret-color 改 primary 粉
- focus-visible 三层光环:1px primary + 4px 22% halo + 14px 40% glow + 背景渐变到 primary-soft
- hover 改 primary-border(之前是 hover-border 灰)
- IP / port / path / number / yanghao_ 系列字段自动用 JetBrains Mono + ss01 + tnum

配置搜索框
- 同款三层 focus 光环;focus-within 时 search icon 染 primary
- kbd 徽章从 muted 改 primary 描边 + primary-soft 6% 背景 + primary-accent-text 粉字
- clear 按钮 hover 背景改 primary-soft

工作区头部
- 左侧 accent 改 3px primary→secondary 渐变 + 12px primary glow
- 加 ::after 顶部 hairline (粉→青渐变)

图表
- chartBlock 加 radial pink 角光 + 顶部 hairline + hover 1px primary 描边 + 22px halo
- chartTitle 字体改 JetBrains Mono 11px 0.1em uppercase + 6px 渐变圆点 (粉→青) + glow
- barTrack 加 inset 1px 阴影;barFill 改 cyan→pink 横向渐变 + 8px halo + ::after 跑光 shimmer 2.4s
- barValue 改 JetBrains Mono + ss01 + tnum

Toast
- 左侧 accent 条改成上下渐变(不再单色)
- icon 包圆形 chip:22×22 圆 + 12% 同色 mix 背景 + 60% 同色 10px halo

帮助层 (shortcutsCard)
- 顶部加 hairline 粉→青渐变(70% 不透明)

cache-bust v26 → v27
2026-05-21 12:03:44 +08:00
Codex ac55428640 精修 WebUI v26:HUD 细节 — 把 chrome 全部往"控制台"推
侧边导航
- sideNav 加渐变粉头部 + counter-reset 通道编号;浮动指示条改 3px 粉→青渐变 + 10px glow
- tabBtn 左侧加 [01]–[11] mono 计数器(::before 用 counter() 生成);hover 时编号变粉
- tabBtn 右侧加可见性切换的 cyan dot(hover 0.7 / active 1)
- active:左渐变背景 + 1px primary 描边 + 编号高亮 + dot glow
- icon 颜色 hover/active 跟随 primary

章节标题
- sectionTitle 字体改 JetBrains Mono 10px 0.12em;圆点改"§ 01" 编号 chip(mono、leading-zero、primary 描边)
- ::after 加横线延展到右侧,渐变粉→透明
- 配置面板顶层加 counter-reset,每个 panel 内部继承计数

卡片
- cardTitle 加状态 chip(::after):默认 "READY",body.is-running 时切 "● LIVE"(绿色 + glow)
- cardTitle .sectionIcon 升级渐变填充 + primary glow

表格
- tableRow 加左侧 hover 渐变 accent stripe(粉→青)
- hover 背景从 surface-soft 改 primary-soft 30% 混合
- tableHead 改 JetBrains Mono 10px + primary 色 + 1px primary 描边 + 渐变背景
- mono 字段全局加 ss01 + tnum

预约卡
- 头部加 radial gradient 粉光晕(右上角)
- reservationItem hover 时左侧 3px 粉→青渐变 accent + 28px halo + translateY(-1)
- reservationIndex dot 改 radial pink + 8px glow
- reservationValue chip 改 JetBrains Mono 0.12em uppercase 粉色 pill
- isImminent / isDue 状态加 radial 警告/危险光晕底

日志
- log 字体改 JetBrains Mono + ss01;padding 加左侧 18px 留出光标位
- background 加 4px 周期性扫描线(cyan 4% mix)
- ::after 加 6×13 粉色光标 1.2s 闪烁(CRT 风)

Footer HUD
- 加 mono 12px / 0.12em 全大写;border-top 改 primary 22% mix
- 左:连接点 + 文字 + "SYS_OK" chip
- 右:PING <em>—</em>ms(实测 /api/version 响应时间,5s 一次)+ FPS <em>—</em>(每秒 RAF 计数)+ version + build
- em 内文字用 secondary/primary 色,mono 数字突出
- 移动端隐藏 PING/FPS

cache-bust v25 → v26
2026-05-21 12:03:44 +08:00
Codex 6fb7707abb 精修 WebUI v25:基调反转 — Operator's Terminal × Editorial
打破之前 Linear 极简,转向更装饰、更有质感的"控制台"美学。

字体与基调
- 字体栈:Manrope (body) + JetBrains Mono (数字/HUD) + Instrument Serif (备选),全部 Google Fonts
- 主色反转:Linear 紫 (#5e6ad2) → 抖音霓虹粉 (#ec4899) + 青蓝 (#06b6d4) 双 accent
- 浅色 base 改暖米白 (#fafaf7);深色改深蓝黑 (#08080c) 提亮饱和度
- body 加双层装饰:3 个 radial-gradient mesh blob + SVG turbulence grain noise (overlay 混合)

品牌标识
- brandMark 升级:6 段 conic-gradient (粉→品红→深粉→青→蓝青→粉);高光 radial drift 9s 缓慢动画;hover scale 1.03
- 内部加 SVG drop-shadow 让 logo 与彩色背景对比

按钮
- btnPrimary:linear-gradient (粉粉粉) + ::before 双层 mask conic 边框 hover 时 1.6s 旋转 + 6→10px 彩色 halo + text-shadow
- btnDanger 同款(红橙红)
- btnSoft hover 时显示粉色微光晕;btnDangerSoft hover 加 4px halo
- 所有按钮 hover translateY(-1px),active 回弹

卡片
- .card 顶部彩色 hairline (粉→青渐变),hover 时 opacity 0.45 → 0.85;hover 时 box-shadow 加 1px primary 描边 + 28px halo
- .overviewCard 同款顶部 hairline + 左侧 3px accent (primary 卡是 primary→secondary 渐变);hover translateY(-1px) + 32px halo

数字 hero
- overviewValue / statValue 改 JetBrains Mono + ss01 字符变体 + tnum + -0.025em 字距;深色主题加 24px primary glow text-shadow

状态点
- statusRunning 改 radial-gradient (mint→success) + 双色环涟漪(success + secondary 错峰 0.9s)+ 8/16px 双层光晕
- statusError 改 radial-gradient (粉→danger) + 12px halo + 1.6s pulse

实时截图区
- 加 4 个角的 viewfinder 取景器 brackets(primary 色 + drop-shadow glow)
- 运行中显示 REC 角标(红圆点 1s 闪烁 + 毛玻璃背景 + JetBrains Mono 字号)
- 空状态加 mesh radial blob (粉/青双色) + 加强扫描线对比
- hover 加 36px primary halo + box-shadow

cache-bust v24 → v25
2026-05-21 12:03:44 +08:00
CodexandClaude Opus 4.7 4f147d214e P2 §5.3: 4 处单点 importlib.import_module → 静态 from import
把单次调用 douyin_screenshot_manager 的 importlib 改为 from-import:
  - douyin/core/douyin_flow_control.py
  - douyin/core/underlying_operations.py
  - douyin/fudai/core/fudai_debug_utils.py
  - douyin/stage/douyin_stage.py

douyin_screenshot_manager 只引用 douyin.core.path_config,与上述 4 个文件
无循环依赖,可以安全静态化。bin/run_cli.py 的 importlib 是有意为之
(绕过 package __init__ 遮蔽),保留。

收益:
  - 可读性 + IDE 跳转/类型提示
  - 每次调用省去 ~100µs 的 import_module 开销

回归:140 .py 编译通过;4 处 importlib 残留全清;
test_filter_logging / check_web_gui_config_sync 通过;
douyin_screenshot_manager 仍可正常加载。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 12:01:16 +08:00
CodexandClaude Opus 4.7 0700a378ec stage + reservation: 孤立 print → logger
- douyin/stage/douyin_stage.py:阶段诊断起始处的 [DEBUG] print 改为
  _LOGGER.debug,原本是诊断日志,走 logging 更合适
- douyin/reservation/douyin_reservation.py:当 _RESERVATION_ERROR_UTILS
  不可用时的 print 兜底改为 _LOGGER.error,避免日志静默丢失
- 两处都新增模块级 logger

回归:140 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 11:52:28 +08:00
CodexandClaude Opus 4.7 d5c9936c88 gui_app + base_interface: 内部错误 print → logger
gui/gui_app.py(8 处 sys.stderr print → _LOGGER):
  - 配置读取失败、日志文件权限/写入错误(warning/error 级)
  - pump_logs 内日志插入失败、循环异常、调度下次更新失败(error/warning 级)
  - 顶部 import logging + 模块级 _LOGGER

douyin/core/fudai_modules/base_interface.py(2 处 print → _LOGGER):
  - BaseFudaiMixin._safe_log 在主类无 _enhanced_log_kv 时的兜底改为 logger.info
  - 顶部 import logging + 模块级 _LOGGER

保留为 stdout 的合理场景:
  - bin/run_cli.py 的 [TEST]/[YANGHAO-ONLY] CLI 输出
  - bin/manage_logs.py 的 CLI 工具输出
  - gui/webgui_launcher.py: GUI 同时把 log 输出到控制台
  - douyin/logging/internal_loggers.py: logger 模块自身的初始化失败兜底
  - douyin/logging/douyin_logging{,_wrapper}.py: 日志系统内部的格式化输出

回归:140 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过;
gui.gui_app/web_gui/gui_core/base_interface 全部可加载,_LOGGER 名称正确。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 11:43:44 +08:00
zzz 7dd1c3ea88 Merge pull request '切换 OCR 默认引擎到 PaddleOCR v4-mobile 并简化预处理' (#6) from claude/compassionate-sammet-469997 into main
Reviewed-on: #6
2026-05-21 11:37:35 +08:00
zzz 10ad6575c7 Merge branch 'main' into claude/compassionate-sammet-469997 2026-05-21 11:36:48 +08:00
CodexandClaude Opus 4.7 9a51b41c3d docs: 归档过期报告 + 整体迁移 docs/optimization → docs/archive/optimization
A. docs/ 根目录下 5 篇过期/迁移类文档归档到 docs/archive/
  - LOGGING_IMPROVEMENTS.md         (日志系统迭代报告,与 archive/日志系统优化说明.md 重复)
  - OCR性能分析报告.md              (历史性能分析)
  - 统一截图和分数记录说明.md        (重构方案,已合并到代码)
  - AI_PROJECT_SUMMARY.md           (提到的 Underlying_Operations.py / path_config.py 路径已与 main 重构后不一致)
  - param_usage.md                  (模块使用说明,零引用,模块本身有 docstring)

B. docs/optimization/ 整目录归档为 docs/archive/optimization/(7 篇)
  - ADB_EXECOUT_OPTIMIZATION / OCR_PERFORMANCE_OPTIMIZATION
  - SCREENSHOT_PERFORMANCE_DIAGNOSIS / SCREENSHOT_VERIFICATION_GUIDE
  - STREAMING_SCREENSHOT_DISABLED / STREAMING_SCREENSHOT_COMPLETELY_DISABLED
  - optimize_file_replace
  全部是优化报告 / 已禁用功能记录,属于历史迭代而非活文档

C. docs/README.md 重写为按主题分组的索引,明确"活文档 vs 归档"边界

保留为活文档:
  - 日志系统规范文档.md(被 3 处引用)
  - 日志轮转功能说明.md(描述当前在用的轮转策略)
  - 截图服务日志说明.md(描述当前服务行为)
  - 完整技术文档.md / 流程图.md / 预约系统详细流程.md / 高价值房间重访功能说明.md

回归:纯文档归档不影响代码;140 .py 全量编译通过;
test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 11:19:28 +08:00
Codex 0131be7869 切换 OCR 默认引擎到 PaddleOCR v4-mobile 并简化预处理
- 默认引擎改为 PaddleOCR PP-OCRv4_mobile(实测 369ms/张,比 EasyOCR 629ms 更快且精度大幅提升,coupon 等关键图错字一片 -> 全对)
- EasyOCR 仅作回退,移除"小图自动放大+锐化+对比度增强"预处理(实测对 Paddle 是负优化,会引入伪影/重复字)
- analyse_pic_word 加 LRU 内容哈希缓存(256 条),重复读图直接命中
- analyse_pic_digits 从 200 行重复实现精简成 30 行委托 + 数字过滤
- 统一两处 OCR 初始化为 _build_paddle / _build_easyocr 工厂,消除重复
- 设置 FLAGS_use_mkldnn=false 绕开 Win + Paddle 3.x 的 oneDNN+PIR 不兼容 bug(实测 FLAGS_enable_pir_in_executor=0 也修不掉,关 oneDNN 是当前唯一可行解)
- 决策依据/速度数据/已知问题归档到 docs/ocr_engine_decision.md
- 业务接口完全向后兼容
2026-05-21 10:50:30 +08:00
CodexandClaude Opus 4.7 7fb0c3849c P0 死代码清理:删 .backup / 空文件 / GUI 占位桩 / 占位目录 / 失效测试
A. 删除 3 个 .backup 文件(约 3.4K 行)
  - douyin/detection/douyin_pixel.py.backup
  - douyin/stage/douyin_stage_handler.py.backup
  - gui/components/log_color_config.py.backup

B. 删除 0 字节文件
  - douyin/other/douyin_stuck_guard.py
  - docs/功能差异对比.md
  - docs/archive/模块化代码对比说明.md

C. 删除 9 个 TODO + pass 占位组件(全仓零外部引用)
  - gui/components/{config_manager,image_viewer,stats_display,
    reservation_display,high_value_rooms_display,ocr_panel,main_window}.py
  - gui/web_components/{proc_runner,http_handler}.py

D. 删除占位目录与失效测试入口
  - douyin/detection/core/  仅 re-export 占位
  - douyin/fudai/finder/    仅 re-export 占位
  - tests/run_test.py       指向已删的 deleted_tests_backup/

附加:tools/diagnostics/check_web_gui_config_sync.py --help 字符串里
      tools/web_gui_config_manifest.json 旧路径修正为 tools/dev/...

回归:154 → 141 个 .py,全量 compileall 通过;AST 扫描 0 处 import 残留;
gui.gui_app/web_gui/gui_core 仍可加载;fudai_analyse / should_skip_fudai_by_config
业务函数链路正常;test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 10:36:59 +08:00
zzz c878491163 Merge pull request 'claude/wonderful-brattain-d1cfe0' (#5) from claude/wonderful-brattain-d1cfe0 into main
Reviewed-on: #5
2026-05-21 10:26:16 +08:00
zzz 6ef04c1f37 Merge branch 'main' into claude/wonderful-brattain-d1cfe0 2026-05-21 10:24:10 +08:00
CodexandClaude Opus 4.7 71f3653354 补回上次合并丢失的关键路径修复 + .gitignore 补强 + 依赖版本对齐
上次冲突解决时跳过了 982f57e (P0 清理) 和 b6ae970 (路径修复) 两个 commit,
本提交补回其中影响运行时正确性和文档一致性的 7 处。

E. 路径错位修复
  - douyin/core/douyin_fudai.py: _reservations_state_path 与 room_pos_map
    状态目录改为优先调用 path_config.get_reservations_path()
  - douyin/core/path_config.py: get_reservations_path 注释明确"实际位置 + 写入方"
  - gui/components/mapping_utils.py: 删除错误兜底 douyin/state/reservations.json
  - gui/components/mapping_table.py: 同步删除 douyin/state/room_pos_map.json 错误兜底
  - gui/web_gui.py: get_reservations() 内的兜底由 douyin/state/ 修正为 douyin/core/state/
  - bin/run_cli.py: 移除对已删空文件 douyin_reservation_ops.py 的 shim 加载
  - douyin/reservation/douyin_reservation_ops.py: 删除 0 字节空文件

F. .gitignore 补强
  - 新增 *.bak_* 拦截带日期后缀的备份命名(修复 *.bak 命中失败的场景)

G. 依赖版本对齐
  - requirements-minimal.txt: paddleocr/paddlepaddle 改为 >=3.0.0,与 requirements.txt 一致
  - README.md: 安装指引中 paddlepaddle==2.5.2 改为 >=3.0.0

回归:全量 .py compileall 通过;7 项断言(path_config 路径、douyin_fudai 切换、
3 处兜底已清、shim 已移除、空文件已删、.gitignore 补强、版本对齐)全部 PASS;
test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 10:18:17 +08:00
zzz 521b7b9e84 Merge branch 'main' into claude/wonderful-brattain-d1cfe0 2026-05-21 10:17:23 +08:00
CodexandClaude Opus 4.5 b96a67b6b8 refactor: web_gui 中 5 个 ADB/config 函数改为薄包装
find_adb_executable / list_adb_devices / resolve_adb_device /
read_config / write_config 在 gui_core.py 中已有完全相同的实现。
web_gui.py 中改为薄包装,所有外部使用保持兼容。

注:get_nested_value 是 web_gui 独有,保留。

文件行数:gui/web_gui.py 原 2253 行减至 2210 行(约减 43 行)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 10:12:38 +08:00
CodexandClaude Opus 4.5 7d63a36125 chore: 删除重复的 log_color_config_fixed.py
log_color_config.py (540行) 与 log_color_config_fixed.py (198行) 的
get_operation_type / get_color_config / apply_operation_color 行为完全一致。
保留前者(更完整),删除后者,简化 actions_log_viewer.py 的双 try import。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 10:12:38 +08:00
zzz 0a0b59c908 Merge pull request 'claude/wonderful-brattain-d1cfe0' (#4) from claude/wonderful-brattain-d1cfe0 into main
Reviewed-on: #4
2026-05-21 09:58:35 +08:00
zzz 2e811e71b3 Merge branch 'main' into claude/wonderful-brattain-d1cfe0 2026-05-21 09:58:24 +08:00
CodexandClaude Opus 4.5 73cfb50a2b chore: 删除 fudai_core 中的未使用 import
去除大规模拆分后剩余的死 import:
- PIL.Image (未引用)
- numpy as np (未引用)
- douyin_reservation_logic (未引用)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:49:38 +08:00
CodexandClaude Opus 4.7 7f33d45df6 fix: tools/diagnostics/check_web_gui_config_sync 路径回归
main 上脚本被迁到 tools/diagnostics/,manifest 被迁到 tools/dev/,
但 ROOT/MANIFEST_PATH 仍按旧位置(tools/ 根、parents[1])计算,
导致脚本运行时报 FileNotFoundError 找不到 gui_app.py。

- ROOT: parents[1] -> parents[2]
- MANIFEST_PATH: tools/web_gui_config_manifest.json -> tools/dev/web_gui_config_manifest.json

回归:脚本输出 [OK] WebUI and gui_app.py config keys are synchronized (125 shared keys)。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:47:53 +08:00
CodexandClaude Opus 4.5 ba4c131b2d refactor: 简化 gui_app.format_gui_log_line 为薄包装
原本 64 行的 fallback 实现实际上是死代码——
gui.components.log_viewer.format_gui_log_line 一直存在,
import 失败几乎不可能发生。

简化为薄包装函数,import 失败时返回原字符串。

文件行数:5857 -> 5804(减 53 行)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:42:27 +08:00
CodexandClaude Opus 4.7 96f8600d42 小批量收尾:删除零引用 scrcpy_screenshot + douyin_fudai/log_viewer print→logger
- 删除 operations/scrcpy_screenshot.py(100 行,仅自身定义自身使用,全仓零外部引用)
- douyin/core/douyin_fudai.py:3 处兜底 print → logging.info/warning(_log_kv 失败时的兜底路径)
- gui/components/log_viewer.py:2 处错误 print → _LOGVIEW_LOGGER.exception(日志线程异常 / 刷新显示异常)

回归:149→148 .py,全量编译通过;test_filter_logging / check_web_gui_config_sync 通过;
fudai_analyse 类正常导出,log_viewer 模块加载 OK。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:40:18 +08:00
CodexandClaude Opus 4.7 938011f672 douyin_screenshot_manager: print → _mgr_log
- 新增模块级 _mgr_log(msg, level):统一走 logging,失败兜底 stdout
- 全部 21 处裸 print 改为 _mgr_log,保留 "[截图管理]" / "[调试图像清理]" 前缀

回归:149 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过;
get_latest_attempt_path / get_last_success_path / ensure_ocr_dir /
shutdown_debug_save_worker 等公共函数仍可加载。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:39:19 +08:00
CodexandClaude Opus 4.7 04035abbc0 douyin_robot: print → _robot_log
- 新增模块级 _robot_log(analyser, msg, level):优先 analyser._log_kv("人机校验" 类目),
  退化到 logging,最后兜底 stdout
- 全部 10 处裸 print → _robot_log
- "无法处理 + 等待30分钟" 类提示标 level=WARNING
- check_robot_pic_distance 中的 print(x, y) 与 print(x1, first_y) 改为 DEBUG 级,
  附带"找到首/末像素"语义说明

回归:149 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过;
3 个公共函数(check_have_robot_analyse / deal_robot_analyse / check_robot_pic_distance)
仍可正常加载。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:38:57 +08:00
CodexandClaude Opus 4.7 a876d9ebb0 gui/web_gui: 内部错误 print → _wg_log,保留启动横幅
- 新增模块级 _wg_log(msg, level):与 yanghao/screenshot 同模式
- 内部错误(日志写权限/失败、静态文件、logs search/get_logs_since)
  6 处 print → _wg_log,分级 WARNING/ERROR
- main() 内的 7 处 print 保留为 stdout:启动端口/URL/中断退出/帮助提示
  属于交互/CLI 输出而非日志事件,走 stdout 更直观

回归:149 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:38:47 +08:00
CodexandClaude Opus 4.7 5a381698d8 operations/{screenshot,ocr}_operations: print → logging
- screenshot_operations.py: 19 处 print → _ops_log(带 [截图]/[截图操作] 前缀)
- ocr_operations.py: 7 处 print → _ocr_log(带 [OCR] 前缀)
- 两处都新增模块级 logger + 兜底 helper,与 douyin_yanghao / screenshot_service
  采用相同模式

回归:149 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过;
ScreenshotOperations、analyse_pic_word 仍可正常加载。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:38:07 +08:00
CodexandClaude Opus 4.7 4557dfb306 operations/screenshot_service: print → logging
- 新增模块级 _svc_log(msg, level):统一走 logging,失败兜底 stdout
- 全部 24 处 print 改为 _svc_log,保留消息中"[截图服务]"前缀以兼容历史搜索
- 默认 level=INFO,告警分级(WARNING/ERROR 等)后续再细化

回归:149 .py 全量编译通过;test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:37:56 +08:00
CodexandClaude Opus 4.7 49704834d8 douyin_yanghao: print → _yanghao_log + 修 3 处 f-string bug
- 新增模块级 _yanghao_log(analyser, msg, level):优先走 analyser._log_kv,
  退化到模块 logger,最后兜底 stdout,避免日志静默丢失
- 全部 58 处裸 print 改为 _yanghao_log 调用
- 修 3 处 f-string 缺前缀 bug({prob} 之前是字面量而非插值):
  L440 跳过点爱心、L466 跳过点收藏、L498 跳过评论的概率显示

回归:全量 149 .py compileall 通过;douyin_yanghao 4 条 helper 路径
(_log_kv / broken _log_kv / 无 _log_kv 兜底 / 4 个 yanghao_* 顶级函数)
全部 PASS;test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:37:46 +08:00
CodexandClaude Opus 4.5 41c3f28eb7 chore: 删除死文件 douyin/fudai/core/fudai_detail_reader.py
该文件只有一个函数 get_fudai_contain(1217 行),但无任何模块
import 它。所有调用方都用的是 douyin_fudai_core.get_fudai_contain。

注:本次 fudai_detail_modules/ 合并时引入的 fudai_detail_orchestrator.py
里的 get_fudai_contain 引用是从 douyin_fudai_core 来的,与本文件无关。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:36:48 +08:00
Codex 16b3bde893 精修 WebUI 第二十一轮:kbd 提示 / 标题反馈 / 趋势箭头
- 关键按钮 kbd 提示:[data-kbd-mod="1"][data-kbd] 自动按平台注入 ⌘ 或 Ctrl 前缀;hover 时不透明度从 0.55 → 1;btnStart 显示 "⌘ ↵",btnSave 显示 "⌘ S";<900px 隐藏
- 页面 title 随运行状态:默认 "抖音挂机控制台",运行中前置 "● ... · 运行中"
- stat 数字趋势箭头:setTextIfExists 检测数值变化方向,向 .statValue 注入 .statTrend ▲/▼ 圆形徽章 (success/danger 色),1100ms 出现 + 淡出再自动移除
- cache-bust v23 → v24
2026-05-21 09:29:38 +08:00
Codex df96f25eba 精修 WebUI 第二十轮:Favicon + 长按连发 + 刷新反馈
- 添加内联 SVG favicon(与 brandMark 同款:紫色渐变圆角方框 + 播放三角 + 圆点),data URL 不增加请求
- number stepper 长按连发:pointerdown 后 500ms 进入 80ms/次的连发;pointerleave/up/cancel/blur 全部取消
- btnRefresh 加 isBusy 状态 + spinner;完成后 toast 反馈"已刷新 · N 台在线"或"无在线设备"或失败提示
- cache-bust v22 → v23
2026-05-21 09:29:38 +08:00
Codex cea5f1df45 精修 WebUI 第十九轮:sticky elevation + toggle switch + 步进按钮
- sectionTitle sticky 真贴顶时(IntersectionObserver + sentinel rootMargin -65px)加 .isStuck 类,浮起 0 6px 12px 阴影
- 关键开关升级为 toggle switch:.check.isToggle 把 input[type=checkbox] 渲染成 32×18 滑块(slider 配 14×14 圆点 + 0.18 阴影);3 个总控开关接入:infinite_loop_enabled / yanghao_enabled / yanghao_enable_actions / yanghao_only
- fmtDuration 改 mono 格式:HH:MM:SS / MM:SS(padStart),适配 tabular-nums
- 自绘 number stepper:所有 .input[type=number] 自动包 .numStepperWrap,hover/focus 时右侧浮现 ▲▼ 微按钮(18×12 双按钮组),调用 stepUp/stepDown + 派发 input/change;inline2 内不加避免连体冲突
- cache-bust v21 → v22
2026-05-21 09:29:38 +08:00
Codex f16eadbd75 精修 WebUI 第十八轮:后端 /api/version + 预约卡 hover accent
- 后端 gui/web_gui.py 新增 GET /api/version:返回 {name, version, build},前端 footer 自动从 cache-bust fallback 切换为真实版本号
- 预约卡 .reservationItem hover 时左侧浮现 2px primary accent 条;isImminent / isDue 状态下不显示(避免与 warning/danger 边框冲突)
- 高价值直播间共用 reservationItem 视觉,自动获得相同 hover accent
- cache-bust v20 → v21
2026-05-21 09:29:38 +08:00
Codex 632951d004 精修 WebUI 第十七轮:sticky 章节 / 语义着色 / 搜索计数 / 空状态升级
- sectionTitle 改 sticky 在长 panel 内吸附顶部,背景渐变 + 6px 模糊;cardTitle/summary 不变
- 福袋统计语义着色:参与成功/中奖 → success;失败 → error;未中奖 → muted;通过 .stateOk/.stateError/.stateWarn/.stateMuted 类切换
- 配置搜索右侧加实时匹配计数徽章("X 项");搜索清空时隐藏
- 空状态占位升级:从单色边框圆点 → 28px 聊天泡 SVG icon (currentColor mask) + 双行布局,更显设计
- cache-bust v19 → v20
2026-05-21 09:29:38 +08:00
Codex 51d8d53a2b 精修 WebUI 第十六轮:滚动顶按钮 / 连体按钮组 / 图表 hover / 徽章
- 滚动 floating 按钮:scrollY > 240 时右下方显示,毛玻璃圆形,平滑滚回顶部;移动端调高避让 toast
- WiFi ADB 操作改 .btnGroup 连体组合:共享圆角、中间无双边、focus z-index 抬起
- timeline 图加 hover 十字线 + tooltip:crosshair 跟随光标 snap 到最近 bin,浮层显示该 bin 的所有系列与时间,无事件显示空状态
- tabBtn[data-badge] 数字徽章:active 时反色 primary;预约数据更新时同步预约 tab 的徽章
- cache-bust v18 → v19
2026-05-21 09:29:38 +08:00
Codex 94e8d37d18 精修 WebUI 第十五轮:设备下拉框状态点
- decorateDeviceSelect: 把 #device select 包裹进 .deviceSelectWrap,在右侧自定义箭头之前插入状态点
- 状态点:选中具体设备或自动模式下有在线设备 → 绿色 ok;无设备 → 灰色 idle;refreshDevices/change 时更新
- cache-bust v17 → v18
2026-05-21 09:29:38 +08:00
Codex 16042d7fd2 精修 WebUI 第十四轮:过渡动画与移动端收敛
- 主题切换平滑:body 加 200ms color/background 过渡;切换时给 :root 临时加 isThemeSwitching,对所有 chrome 表面(header / card / panel / btn 等 18 类)启用 200ms 过渡;260ms 后移除避免长期影响
- 首屏 .app 容器淡入:220ms fadeIn + 微移
- 移动端 (<640) 收敛:subtitle 隐藏(保留 brandMark + title);footer appConnText 隐藏只留状态点
- cache-bust v16 → v17
2026-05-21 09:29:38 +08:00
Codex a40ddc3083 精修 WebUI 第十三轮:动效、语义着色与帮助系统
- panel 切换动画:active 加 fadeIn (220ms) 替换无差别 surfaceIn,tab 切换更有反馈
- statValue 加 stateOk/stateMuted/stateError 语义着色:运行中显示 success 色(hero metric),未运行用 muted
- 预约卡倒计时实时刷新:startReservationsCountdownTick 每秒 tick,更新 .reservationRemain 文字 + isImminent/isDue 类,无需等 stats 轮询
- ? 快捷键弹出帮助 overlay:列出 ⌘K/⌘S/⌘Enter/Esc/?;ESC 或点击遮罩关闭;带毛玻璃 + scale 进出动画;输入框聚焦时不拦截
- cache-bust v15 → v16
2026-05-21 09:29:38 +08:00
Codex 3295cb3d6f 精修 WebUI 第十二轮:质感打磨
- brandMark 改为三档 OKLCH 渐变 + 高光 radial-gradient + hover 微浮起
- tabBtn hover 与 active 用 surface-muted ↔ primary-soft 混合,更稳的层级感
- footer 连接点 ok 状态加涟漪扩散动画(footerRipple)
- logSection: 圆角 v-md / hover border 提亮 / logHeader 渐变背景 / logTitle 加 4px 圆点 / logHeaderActions select 自绘箭头适配紧凑高度
- cache-bust v14 → v15
2026-05-21 09:29:38 +08:00
Codex cdaa9e4c69 精修 WebUI 第十一轮:信息层级与视觉重音
- overview hero metric 字号 20→26px (text-2xl),紧字距,更接近 Vercel/Linear 的指标卡
- overviewLabel 改 10px uppercase,padding 提至 16/18px
- stats 第一行(运行/PID/运行时长)拆为 statsGridHero + .statHero 大卡,与下方密集网格区分主次
- cardTitle 图标改 chip 风:26×26 圆角填充容器,primary-soft 底 + primary-border 描边
- sectionTitle 加左侧 4px primary 圆点 accent;cardTitle/summary 上的 sectionTitle 不显示
- cache-bust v13 → v14
2026-05-21 09:29:38 +08:00
Codex 8b8e3129e5 精修 WebUI 第十轮:交互终章
- header 滚动时加 isScrolled 类:阴影提一档显得"浮起",区分内容区
- 键盘快捷键:⌘S/Ctrl+S 保存配置,⌘Enter/Ctrl+Enter 启动运行;尊重按钮 disabled 状态
- 通用 tooltip 系统:[data-tooltip] + 可选 data-tooltip-pos="bottom",带小箭头与毛玻璃;移动端禁用避免触摸浮悬
- btnTheme / btnShotFullscreen / 复制按钮 全部接入 tooltip
- cache-bust v12 → v13
2026-05-21 09:29:38 +08:00
Codex 0a2d67afb4 精修 WebUI 第九轮:overview 福袋卡迷你 sparkline
- 福袋处理卡片底部加入 22px 高 sparkline,合成 fudai_open_detail + fudai_attend_ok 两条序列为一条折线
- 渐变填充 + 折线双层;用 currentColor 保证主题切换自动跟随;数据少于 2 点时隐藏
- pollStats 触发渲染,与主时间轴同源数据
- cache-bust v11 → v12
2026-05-21 09:29:38 +08:00
Codex d1f153b373 精修 WebUI 第八轮:可复制 + 全屏 + 表格细节
- statValue 一键复制:PID 和 TraceId hover 显示复制按钮,点击调用 navigator.clipboard,带 toast 反馈与 fallback (textarea + execCommand)
- setTextIfExists 改为只更新文本节点,保留子元素(如 .copyBtn 不被覆盖)
- 截图区右上角加全屏按钮(hover 显示):调用 requestFullscreen,失败则新窗口打开;左下角浮层显示截图时间戳,毛玻璃背景
- 表格行:默认 ellipsis 截断,hover 时展开为多行换行
- cache-bust v10 → v11
2026-05-21 09:29:38 +08:00
Codex 857b33f413 精修 WebUI 第七轮:底部状态栏 + 实时反馈
- 底部 appFooter:左侧连接状态点(idle/ok/error 3 态 + tooltip)+ 文字;右侧版本号 + 构建标识;移动端纵向排列
- API 连接状态实时指示:apiGet/apiPost 拦截成功失败,连续 2 次失败才标 error,避免抖动
- 版本号:尝试拉 /api/version;失败时回退到 cache-bust tag
- stat 数字变化时短暂闪 primary 色(statFlash 700ms),通过 setTextIfExists 自动触发
- number input 隐藏原生上下箭头 + tabular-nums 数字
- cache-bust v9 → v10
2026-05-21 09:29:38 +08:00
Codex 07700c24d9 精修 WebUI 第六轮:交互精致度
- 配置搜索加 ⌘K / Ctrl+K 快捷键聚焦 + ESC 清空/失焦;右侧带 kbd 提示徽章(输入或聚焦时自动隐藏;移动端不显示);自动按平台显示 ⌘ 或 Ctrl
- 按钮 .isBusy 状态加旋转 spinner(隐藏图标),禁用 pointer-events
- 即将开奖预约(剩余 ≤60s)加 isImminent 类:warning 边框 + 微脉动 + value pill 反白;已到时间加 isDue(danger 边框 + 反白)
- brand logo 重做:圆角方形容器 + 内嵌播放三角 + 装饰圆点,更具品牌识别度
- 侧边导航 active 指示条改为 sideNav::before 浮动滑块,CSS var 控制 Y/H,切换 tab 时 220ms 滑动;resize/字体加载完成自动重算位置;横向布局自动隐藏
- cache-bust v8 → v9
2026-05-21 09:29:38 +08:00
Codex 96cba09c49 精修 WebUI 第五轮:交互能力与功能性升级
- 新增 Toast 通知系统:右下角浮出(移动端横铺底部),4 类(success/error/warn/info)+ 关闭按钮 + 自动消失 + hover 暂停消失
- 关键操作接入 Toast:保存配置 / 加载配置 / 启动失败 / 设备操作(连接/断开/WiFi 启用)成功失败提示
- 日志关键词分类着色:行级 span,自动识别 ERROR/WARN/SUCCESS/DEBUG/INFO(含中英文与 emoji 标记);DocumentFragment 批量渲染保持性能
- 配置面板加跨标签搜索:workspaceHeader 内嵌搜索框,输入即时按 label/hint/key 过滤所有 row 与 sectionTitle,搜索时自动展开所有 panel;空结果显示空状态;带清空按钮
- 首屏统计骨架屏:未到数据前 statValue 显示 shimmer 占位;pollStats 成功后自动移除
- 移动端复查:inline2 在小屏取消连体边框;workspaceHeader 改纵向布局,搜索框占满宽;secondaryActions 分隔线隐藏;btnTheme 推到右侧
- cache-bust v7 → v8
2026-05-21 09:29:38 +08:00
Codex aa5065590a 精修 WebUI 第四轮:表单细节 + 滚动行为
- inline2 双输入框视觉合并:连体边框、共享圆角、focus 时 z-index 提升
- inline2 内的 span(如 "~")改为正中对齐分隔符
- rowActions 加 border-top + padding-top;primary 按钮自然居前(order: -1)
- html scroll-behavior smooth;prefers-reduced-motion 时回退 auto
- cache-bust v6 → v7
2026-05-21 09:29:38 +08:00
Codex 276235408e 精修 WebUI 第三轮:清理 + a11y + 深色微调
- 清理死变量:surface-elevated、bg-start/mid/end、shadow-hover、shadow-primary*、accent-cyan/emerald、primary-soft-hover*、primary-action-bg
- header 动作组:primary 与 secondary 之间加 1px 分割线;btnTheme 加左 margin
- summary.sectionTitle 加自绘 chevron icon(mask SVG),open 时旋转 90°
- 表单 :focus 改为 :focus-visible(鼠标点击不再触发 ring)
- 按钮加 :focus-visible 双层光环(背景 + primary 描边)
- 深色主题对比度复查:border 26→2a,border-strong 2e→3a,hover-border 40→4a;surface-muted 1a→1c;primary-soft 1a1d33→1c2040;primary-border 2d3257→353c66;warning/danger soft 系列加亮一档;overview-primary-bg 141414→161620;hairline 0.04→0.06
- cache-bust v5 → v6
2026-05-21 09:29:38 +08:00
Codex 299ced21c8 精修 WebUI 第二轮:数据表/表格/图表/预约卡
- workspaceHeader 加左侧 2px primary accent + uppercase eyebrow
- stats 卡片:tabular-nums + uppercase 标签 + 字号统一 text-xl
- table:sticky 表头 uppercase + zebra 奇偶行 + hover 高亮 + mono 列灰度
- timeline 图:4 等分水平网格虚线 + Y 轴 0/mid/max 三档 mono 标签
- 空状态:.hint 单独使用时升级为虚线圆框居中占位 + 圆形 dot
- 预约卡片:reservationIndex 加圆点 + reservationValue 改 uppercase pill;hover 去 transform,纯 box-shadow 反馈
- cache-bust v4 → v5
2026-05-21 09:29:38 +08:00
Codex b7d7f61a27 精修 WebUI:质感细节与组件统一
- 引入设计 token:space-1..8 / radius-sm..xl / text-xs..2xl
- header:替换品牌图标为 SVG(耳机+音符)+ 顶部 hairline;title 用 tabular 字体可读性更好
- 按钮 primary/danger 加 inner highlight + 渐变深浅 + 三态质感(idle/hover/active)
- 侧边导航 tabBtn:active 改为左侧 2px 垂直指示条带 scaleY 动画
- 表单:select 加自绘下拉箭头;focus 双层 ring(border + 半透明)
- check 项勾选后亮 primary-soft 背景
- 状态卡 overviewCard:左侧 2px accent 条 + tabular-nums 数字 + 标签 uppercase
- statusRunning 状态点改为外扩光环动画(更内敛)
- 图表:barFill 加细微渐变;hover 行高亮其他行半透明;tabular-nums
- 全局滚动条:10px 细圆角,仅 thumb 显示
- preview 占位:斜纹背景 + 单方向扫描线动画
- cache-bust v3 → v4
2026-05-21 09:29:37 +08:00
CodexandClaude Opus 4.5 242876f679 refactor: 删除 fudai_core 中重复的 attend_choujiang 实现
attend_choujiang 在 fudai_core.py 中的旧版本只是一个回退实现:
开头就先尝试委派到 fudai_attend.attend_choujiang(更新版本),
1597 行的本地实现实际上是死代码——只在 import 失败时才会执行,
而 fudai_attend.py 一直存在。

简化为薄包装函数,直接调用 fudai_attend 中的实现。

文件行数:3799 -> 2208(减 1591 行,约 42%)
本次会话累计 fudai_core 减少:6393 -> 2208(减 4185 行,65%)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:28:52 +08:00
CodexandClaude Opus 4.5 9edfcc2449 chore: 删除 operations/ 下的废弃存根模块
- device_operations.py:仅是空 stub(__all__ = []),无人使用
- image_operations.py:同上
- screenshot_service_new.py:未被引用的重复实现

operations/__init__.py 不导出这些模块,外部无依赖。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:22:56 +08:00
CodexandClaude Opus 4.5 61ec06092d refactor: 删除 fudai_core 中重复的两个超大函数
douyin_fudai_core.py 中的 should_skip_fudai_by_config (~480 行) 和
basic_join_decision (~1940 行) 与 fudai_filter.py 中的实现高度重复。
保留 fudai_filter.py 中的版本,删除 douyin_fudai_core.py 中的副本。

兼容性:保留薄包装函数,所有现有 import 路径继续工作。

文件行数:6206 -> 3799(减 2407 行,约 39%)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:16:12 +08:00
CodexandClaude Opus 4.5 7d834d316f refactor: 删除 fudai_core 中重复的 check_contain
check_contain 在 fudai_filter.py 中已有完全相同的实现。
通过顶部 import 直接复用,删除 douyin_fudai_core.py 中的副本。

文件行数:6250 -> 6206(减 44 行)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:11:45 +08:00
CodexandClaude Opus 4.5 e38640eb63 refactor: 删除 fudai_core 中重复的 4 个开奖检查函数
check_lucky_draw_result / check_have_reward_notice_confirm /
check_in_order_confirm_page / get_reward 在 fudai_result_checker.py
中已有更新版本(使用 preprocess_for_ocr 等改进)。

douyin_fudai_core.py 中保留薄包装函数作为兼容 re-export,
确保任何旧调用点继续工作。

文件行数:6347 -> 6250(减 97 行)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:08:43 +08:00
CodexandClaude Opus 4.5 0031f17ebc refactor: 抽取 is_watch_task_fudai / _is_short_countdown_text 到 fudai_filter
douyin_fudai_core.py 中存在与 fudai_filter.py 完全重复的
is_watch_task_fudai 实现,_is_short_countdown_text 也属于过滤逻辑。
集中到 fudai_filter.py 后,douyin_fudai_core.py 保留薄包装函数
作为兼容 re-export,确保所有既有调用点继续工作。

文件行数:6393 -> 6347(减 46 行)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:04:40 +08:00
CodexandClaude Opus 4.5 2d6cbecf7e refactor: 抽取 underlying_operations 顶部辅助函数到 io_utils.py
将 4 个模块级辅助函数及相关常量从 underlying_operations.py 抽离到
新建的 douyin/core/io_utils.py:
- _verify_png_integrity
- _safe_replace_file
- _ensure_parent_dir
- _mirror_screenshot_to_external
- _EXTERNAL_DOUYIN_FUDAI_DIR / _EXTERNAL_AXF_SCREENSHOT

underlying_operations.py 仍重新导出这些符号,保持向后兼容,
所有外部 import 无需修改。

文件行数:3508 -> 3342(减 166 行)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 09:01:14 +08:00
CodexandClaude Opus 4.5 bdde741db1 refactor: 删除冗余的 douyin_logger.py
douyin_logger.py 提供的 get_logger 已被 douyin_logging.get_logger 覆盖。
唯一调用处(wrapper 中的回退路径)改为使用 douyin_logging.get_logger。

douyin/logging/ 模块数:9 -> 8

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 08:57:34 +08:00
CodexandClaude Opus 4.5 996990be31 refactor: 合并 action_tracker.py 到 action_logger.py
action_tracker.py 只有 28 行,仅定义 track_action 装饰器,
该装饰器内部依赖 ActionLogger 和 PerformanceTracker,
合并到 action_logger.py 更内聚。

douyin/logging/ 模块数:10 -> 9

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 08:55:40 +08:00
CodexandClaude Opus 4.5 a065c12d0c refactor: 合并 error_logger.py + debug_logger.py 到 internal_loggers.py
这两个模块只被 douyin_logging_wrapper 内部使用,外部完全不引用。
合并为单文件 internal_loggers.py 减少模块数量。

douyin/logging/ 模块数:11 -> 10

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 08:53:48 +08:00
zzz 6e8e5d1102 Merge pull request 'claude/wonderful-brattain-d1cfe0' (#2) from claude/wonderful-brattain-d1cfe0 into main
Reviewed-on: #2
2026-05-21 08:49:06 +08:00
CodexandClaude Opus 4.5 b137aead48 refactor: 合并 fudai_detail_modules/ 到 douyin/fudai/core/
将 fudai_detail_modules/ 6 个模块全部迁移到 douyin/fudai/core/:
- fudai_detail_coupon_detection.py
- fudai_detail_operations.py
- fudai_detail_room_title.py
- fudai_detail_utils.py
- fudai_detail_validator.py
- fudai_detail_reader.py -> fudai_detail_orchestrator.py(避免与 core/ 已有同名文件冲突)

更新所有 import:
- douyin/fudai/douyin_fudai_core.py
- douyin/fudai/douyin_fudai_detail.py

删除 fudai_detail_modules/ 空目录及其 README/__init__。

验证:python -m compileall 全项目通过。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 08:46:11 +08:00
CodexandClaude Opus 4.5 cb4d25abdf refactor: 删除死代码 _parse_mm_ss / _extract_2digits
这两个内嵌函数定义后从未被调用(grep 验证)。
time_utils.py 中已有公共版本可供未来使用。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 00:34:19 +08:00
CodexandClaude Opus 4.5 8fe7ff0585 refactor: 根目录核心模块迁移到 douyin/core/ 和 douyin/logging/
将 4 个根目录核心模块迁移到合理位置:
- path_config.py    -> douyin/core/path_config.py
- version.py        -> douyin/core/version.py
- Underlying_Operations.py -> douyin/core/underlying_operations.py
- unified_logger.py -> douyin/logging/unified_logger.py

配套更新所有 import:
- path_config: 41 处 import 改为 douyin.core.path_config
- version: 4 处改为 douyin.core.version
- unified_logger: 5 处改为 douyin.logging.unified_logger
- Underlying_Operations: 14 处改为 douyin.core.underlying_operations

修复 path_config.PROJECT_ROOT 计算(向上 2 级而非当前目录)。

验证:python -m compileall 全项目通过。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 00:23:14 +08:00
CodexandClaude Opus 4.5 e3e399da70 refactor: 入口脚本迁移到 bin/
将 4 个入口脚本从根目录迁移到 bin/:
- run_cli.py
- gui_app.py
- webgui_launcher.py
- manage_logs.py

配套修改:
- 修复 bin/*.py 内部 ROOT_DIR 计算(parent.parent)
- bin/run_cli.py 在 sys.path 加入项目根,shim 加载逻辑保持不变
- bin/manage_logs.py 在 sys.path 加入项目根
- path_config.get_run_cli_path() 返回 bin/run_cli.py

启动方式变化:
- 原: python run_cli.py / python gui_app.py
- 新: python bin/run_cli.py / python bin/gui_app.py

GUI 内部通过 path_config.get_run_cli_path() 调用,自动适配。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 00:23:14 +08:00
zzz 309b629e7c Merge branch 'main' into claude/wonderful-brattain-d1cfe0 2026-05-20 23:57:39 +08:00
Codex 3ed352ef0e 重构 Web GUI 视觉为深浅双主题大厂风
- 引入 Linear/Vercel 风设计语言:单色 primary、克制阴影、Inter 字体
- 新增深/浅双主题 token 与右上角切换钮,支持系统跟随 + localStorage 记忆
- 字重整体降一档(760→600,720→550,650→500),更轻盈现代
- sectionTitle 改为 11px uppercase 灰色辅助文字 + 细分割线
- 删除 sheen / scan / overviewCard 渐变条等装饰动画与彩色装饰层
- 图表配色单色化:timeline 线统一用 primary + opacity 区分系列
- styles.css/app.js cache-bust 版本升至 theme-v3
2026-05-20 23:09:20 +08:00
zzz 1a0afe86a1 Merge pull request 'claude/wonderful-brattain-d1cfe0' (#1) from claude/wonderful-brattain-d1cfe0 into main
Reviewed-on: #1
2026-05-20 23:07:29 +08:00
297 changed files with 41894 additions and 37702 deletions

No files matched your search

+1
View File
@@ -85,6 +85,7 @@ temp/
config/*.json
!config/README.md
*.bak
*.bak_*
*.backup
*.orig
*.swp
+145
View File
@@ -0,0 +1,145 @@
# Changelog
本项目所有显著变更都会记录在这里。
格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)(带 `V` 前缀,如 `V3.3.3`)。
变更类型:
- `Added` 新增
- `Changed` 调整
- `Deprecated` 即将废弃
- `Removed` 已移除
- `Fixed` 修复
- `Security` 安全相关
## [Unreleased]
### Added
- 引入完整的版本管理体系:
- `CHANGELOG.md`(Keep a Changelog 1.1.0 格式)
- `tools/dev/bump_version.py`(自动 bump major/minor/patch + 同步 `version.py` / `pyproject.toml` / `CHANGELOG.md` + 创建 git tag)
- `[project]` 元数据加入 `pyproject.toml`,与 `douyin/core/version.py` 保持单一事实来源
- 给所有历史版本(V3.0.0 → V3.3.3)补齐 git tag
### Changed
- README「版本更新日志」段简化为指向 `CHANGELOG.md` 与 git tags
## [V3.3.3] — 2025-12-28
### Added
- 30 分钟超时保护机制:长时间无成功参与时自动返回推荐页重启流程
### Fixed
- 模板与截图路径配置统一,使用 `douyin/core/path_config.py`
- 直播间检测模板文件路径错误
- GUI / Web GUI 中行为日志读取路径
### Changed
- 路径配置全量统一化:用 `path_config.py` 集中管理,简化维护
- 行为日志路径统一为 `path_config.get_actions_log_path()`
- 流程图与文档:反映 30 分钟超时检查、阶段诊断步骤、预约回退子流程
## [V3.3.2] — 2025-12-25
### Fixed
- 预约回退功能不生效:
- `needswitch` 配置未从 `config.json` 正确加载
- `self.reservations` 未从状态文件加载
- 预约回退逻辑加详细调试日志
### Changed
- 每次 `run_once_basic` 自动从状态文件加载预约队列,确保始终包含最新数据
## [V3.3.1] — 2025-12-14
### Added
- `live_room_match_threshold`:直播间检测阈值可配置
- `fudai_icon_max_wait_seconds`:福袋图标检测等待时间可配置
### Fixed
- 直播间检测模板文件路径警告
### Changed
- 阶段检测优先使用像素检测
- 合并阶段 1.5 与阶段 3 的 OCR 检测以减少冗余
## [V3.3.0]
### Changed
- 模块化重构:核心代码按职责拆分到 `douyin/` 各子包
- 阶段检测策略调整:像素检测优先
### Added
- GUI 截图 + OCR 联合调试功能
- 桌面 GUI「强制停止」按钮
### Fixed
- 多个已知问题(详情见 commit 历史)
## [V3.2.0]
### Added
- 高价值福袋预约功能(`high_value_fudai_*` 配置族)
- 高价值直播间回访功能(`high_value_room_revisit_*`)
### Changed
- 推荐页养号逻辑优化
## [V3.1.0]
### Added
- 推荐页养号功能:自动点赞 / 收藏 / 评论(按概率)
### Changed
- OCR 识别准确率提升
## [V3.0.0]
### Changed
- **重大更新**:OCR 引擎从 pytesseract 切换到 PaddleOCR
### Added
- 自动分辨率适配
### Fixed
- 大量已知问题
## V2.x
- 多分辨率支持
- 稳定性提升
- 各种 bug 修复
## V1.x
- 基础功能:福袋检测、参与、自动领奖
[Unreleased]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.3...HEAD
[V3.3.3]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.2...v3.3.3
[V3.3.2]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.1...v3.3.2
[V3.3.1]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.0...v3.3.1
[V3.3.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.2.0...v3.3.0
[V3.2.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.1.0...v3.2.0
[V3.1.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.0.0...v3.1.0
[V3.0.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/releases/tag/v3.0.0
+435 -1263
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -9,7 +9,7 @@ import sys
from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parent
ROOT_DIR = Path(__file__).resolve().parent.parent
TARGET = ROOT_DIR / "gui" / "gui_app.py"
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
+5 -4
View File
@@ -27,14 +27,14 @@ import argparse
from datetime import datetime, timedelta
from typing import Dict, Any
# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 添加项目根到 sys.path(从 bin/ 目录运行时需要)
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from douyin.core import path_config
from douyin.logging.douyin_logging import (
cleanup_old_logs,
compress_log_file,
get_log_stats,
path_config
)
@@ -178,7 +178,8 @@ def show_monitor_status() -> None:
"""显示监控器状态"""
print("\n=== 日志监控状态 ===")
from douyin.logging.douyin_logging import _log_monitor
from douyin.logging.douyin_logging_pkg import _common as _logging_state
_log_monitor = _logging_state._log_monitor
if _log_monitor and _log_monitor._running:
print("状态: 运行中")
+5 -5
View File
@@ -47,7 +47,10 @@ except Exception as e:
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
_BASE_DIR = os.path.dirname(__file__)
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 确保项目根在 sys.path 中(脚本从 bin/ 目录启动时)
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
@@ -74,9 +77,6 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
_load_local_shim(
"douyin_reservation_ops", "douyin/reservation/douyin_reservation_ops.py"
)
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
try:
@@ -628,7 +628,7 @@ def main(argv: list[str]) -> int:
if __name__ == "__main__":
try:
from version import print_version_banner
from douyin.core.version import print_version_banner
print_version_banner("run_cli")
except Exception:
@@ -9,7 +9,7 @@ import sys
from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parent
ROOT_DIR = Path(__file__).resolve().parent.parent
TARGET = ROOT_DIR / "gui" / "webgui_launcher.py"
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
+3 -3
View File
@@ -59,8 +59,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
- **OCR后**:保存OCR结果,包含识别文本预览
**实现位置:**
- `Underlying_Operations.py::cut_pic()` - 裁剪图像时保存
- `Underlying_Operations.py::analyse_pic_word()` - OCR识别前后保存
- `douyin/core/underlying_operations.py::cut_pic()` - 裁剪图像时保存
- `douyin/core/underlying_operations.py::analyse_pic_word()` - OCR识别前后保存
**保存信息:**
- 预处理模式(彩色/二值化)
@@ -171,7 +171,7 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
### 目录配置
调试图像目录通过 `path_config.py` 配置:
调试图像目录通过 `douyin/core/path_config.py` 配置:
- `get_pic_dir()`: 返回 pic 目录路径
- `get_debug_captures_dir()`: 返回调试图像存档目录路径
+27 -26
View File
@@ -1,35 +1,36 @@
# 文档目录
本目录包含项目的所有文档文件。
本目录包含项目当前在用的文档。**过期报告 / 历史迭代记录已归档到 `docs/archive/`**。
## 文档列表
## 当前文档(按主题分组)
- **CLEANUP_REPORT.md** - 清理报告
- **CODE_REVIEW_FIXES.md** - 代码审查修复
- **CODE_REVIEW_REPORT.md** - 代码审查报告
### 入门与依赖
- **DEPENDENCY_GUIDE.md** - 依赖安装与版本说明
- **WiFi_ADB_使用指南.md** - WiFi ADB 连接指南
- **scrcpy_手动安装指南.md** - scrcpy 手动安装
- **核显GPU加速说明.md** - 核显 GPU 加速
- **设置定时任务说明.md** - 定时任务设置
- **Git_连接与代理排查.md** - Git 网络连通排查
### 系统说明(活文档)
- **完整技术文档.md** - 完整技术文档
- **DEBUG_IMAGE_SYSTEM.md** - 调试图像系统
- **DEPENDENCY_FIXES_REPORT.md** - 依赖修复报告
- **DEPENDENCY_GUIDE.md** - 依赖指南
- **FIXES_REPORT.md** - 修复报告
- **FUDAI_FINDER_OPTIMIZATION.md** - 福袋查找器优化
- **GUI参数冲突分析.md** - GUI参数冲突分析
- **GUI日志修复总结.md** - GUI日志修复总结
- **LOGGING_IMPROVEMENTS.md** - 日志改进
- **MODULAR_REFACTORING_VERIFICATION.md** - 模块化重构验证
- **OCR性能分析报告.md** - OCR性能分析报告
- **WPS流程图说明.md** - WPS流程图说明
- **功能差异对比.md** - 功能差异对比
- **日志系统优化总结.md** - 日志系统优化总结
- **日志系统优化说明.md** - 日志系统优化说明
- **日志系统规范文档.md** - 日志系统规范文档
- **核显GPU加速说明.md** - 核显GPU加速说明
- **模块化代码对比说明.md** - 模块化代码对比说明
- **流程图.md** - 流程图
- **真机测试报告.md** - 真机测试报告
- **统一截图和分数记录说明.md** - 统一截图和分数记录说明
- **设置定时任务说明.md** - 设置定时任务说明
- **预约系统详细流程.md** - 预约系统详细流程
- **预约系统详细流程.md** - 预约系统流程
- **高价值房间重访功能说明.md** - 高价值房间重访
- **截图服务日志说明.md** - 截图服务日志
- **日志系统规范文档.md** - 日志系统规范
- **日志轮转功能说明.md** - 日志轮转
- **ocr_engine_decision.md** - OCR 引擎选型决策记录
### 流程图
- **流程图.md** - 主流程图
- **WPS流程图说明.md** - WPS 流程图说明
- **WPS详细流程图.txt** / **流程图_WPS文本格式.txt** - WPS 文本格式流程图
### 测试
- **测试验证指南.md** - 测试验证指南
## 归档(`docs/archive/`)
历史报告、过期迭代记录、已合并到代码或被新文档替代的内容已移至 `docs/archive/`。
其中 `docs/archive/optimization/` 子目录包含旧的性能/截图优化报告。
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Whitespace-only changes.
+84
View File
@@ -0,0 +1,84 @@
# OCR 引擎选型决策记录
> 2026-05 决策依据。基于 ~30 张项目截图实测对比,决定换掉 EasyOCR,统一用 **PaddleOCR PP-OCRv4_mobile**。
---
## 结论
| 引擎 | 平均/张 | 关键图精度 | 选用 |
|---|---|---|---|
| **PaddleOCR v4-mobile** | **369ms** | ✅ 12 段全对 | **首选** |
| PaddleOCR v5-mobile | 407ms | ⚠️ 偶尔合并段落 | 略差 |
| RapidOCR-ONNX | 1494ms | ✅ 12 段全对 | 兜底 |
| PaddleOCR v5-server | 2395ms | ⚠️ 多噪声字符 | 不用(重型) |
| EasyOCR | 629ms | ❌ "官方保障"→"膏方保腰" | **回退** |
| PaddleOCR v4-server | 2721ms | ⚠️ 切分错误 | 不用(重型) |
业务图都是裁切后的小区域(300×120 倒计时框、600×260 内容框),mobile 模型完胜 server 模型。
## 关键修复:Win + Paddle 3.x oneDNN+PIR bug
`ConvertPirAttribute2RuntimeAttribute not support pir::ArrayAttribute<pir::DoubleAttribute>` 在 paddle 3.3 + paddleocr 3.5 + Win 必现。
实测结论:
- ❌ `FLAGS_enable_pir_in_executor=0` 修不掉(PIR 已强制默认)
- ❌ paddleocr 3.x 强制要 paddle 3.x,不能降级
- ✅ **`enable_mkldnn=False`** 是当前唯一可行解,代价是 CPU 推理慢 20-30%
代码里在 `operations/ocr_operations.py` 模块顶层设置 `FLAGS_use_mkldnn=false` + `enable_mkldnn=False`。等 paddle 上游补全 `onednn_instruction.cc:118` 的属性转换分支后可以删掉这行。
## 已知次优配置
- PaddleOCR `predict()` 是 3.x 推荐 API,`ocr()` 仍兼容(代码做了运行时检测)
- 自定义"放大+锐化+对比度增强"预处理对 PaddleOCR 是负优化(实测 `coupon_full_title` 输出 `全全场通用` 重复字、`coupon_limit` 多出 `工品` 噪声),已删除。PaddleOCR 内部的 resize/normalize 已经够用
## 速度数据(19 张 + 11 张混合裁切框,CPU 模式)
### 速度横向对比(按场景分组的代表数据)
| 图片类型 | v4-mobile | v5-mobile | EasyOCR |
|---|---|---|---|
| 复杂多文字(coupon.png 整图)| 2293ms | 2148ms | 2168ms |
| 长文字行(banner_long.png)| 898ms | 910ms | 451ms |
| 短文字(coupon_title.png)| 163ms | 162ms | 279ms |
| 数字小框(coupon_30.png)| 18ms | 106ms | 147ms |
| 福袋裁切区域(fudai_*)| ~150-1700ms | ~150-2200ms | ~470-5500ms |
| 空白图标 | ~10-100ms | ~10-150ms | ~30-100ms |
EasyOCR 在彩色背景大图上特别慢(fudai 1280×1280 跑 5 秒+),且关键内容图错字率极高。
### v4-mobile vs v5-mobile 精度差
- coupon.png:v4-mobile `一单回本 | 全场通用` 正确切分,v5-mobile `一单回本全场通用` 合并
- banner_long.png:v4-mobile `上一个 | 下一个` 正确,v5-mobile `E— | 下-` 错误
v4-mobile 综合最优。
## 生效的优化
`operations/ocr_operations.py`:
1. 切到 PaddleOCR v4-mobile 优先(之前 EasyOCR 优先)
2. 加 LRU 结果缓存(256 条),重复图直接命中(业务里 cut_pic 短时间常重读相同区域)
3. 抽出 `PADDLE_KWARGS` / `_build_paddle()` / `_build_easyocr()` 工厂消除重复
`douyin/core/underlying_operations.py`:
1. `__init__` / `_ensure_ocr` 都对齐到 Paddle 优先
2. `analyse_pic_word` 加缓存层(基于 blake2b 内容哈希 + change_color)
3. 删掉小图自动放大+锐化+对比度增强(实测负优化)
4. PaddleOCR 切到 `predict()` 新 API
5. `analyse_pic_digits` 从 200 行精简到 30 行委托 + 数字过滤
业务接口完全向后兼容,调用方零改动。
## 测试用图
`assets/`:项目自带 9 张图
裁切扩展:从 coupon.png/fudai.png 裁出多种难度的小区域(~22 张)测试模型对小裁切框的表现
## 维护提示
- 缓存大小:环境变量 `OCR_CACHE_MAX`(默认 256,设 0 禁用)
- 缓存统计:`from operations.ocr_operations import cache_stats; print(cache_stats())`
- 调试图保存:环境变量 `SAVE_OCR_DEBUG_IMAGES=1`
- 跳过初始化(仅做点击不需要 OCR 的流程):环境变量 `SKIP_OCR_INIT=1`
View File
Whitespace-only changes.
+83 -64
View File
@@ -6,6 +6,25 @@
说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。
> **⚠️ 路径迁移说明(2026-05 之后阅读本文档时请对照)**
>
> 本文档主体撰写于项目大重构之前,正文里仍出现大量旧路径。重构后实际位置如下(旧 → 新):
>
> | 文档里写的(旧) | 当前实际位置(新) |
> |---|---|
> | `Underlying_Operations.py` | `douyin/core/underlying_operations.py` |
> | `path_config.py` | `douyin/core/path_config.py` |
> | `run_cli.py` | `bin/run_cli.py` |
> | `gui_app.py` | `bin/gui_app.py`(launcher)/ `gui/gui_app.py`(实现) |
> | `webgui_launcher.py` | `bin/webgui_launcher.py`(launcher)/ `gui/webgui_launcher.py`(实现) |
> | `manage_logs.py` | `bin/manage_logs.py` |
> | `unified_logger.py` | `douyin/logging/unified_logger.py` |
> | `version.py` | `douyin/core/version.py` |
> | `from Underlying_Operations import …` | `from douyin.core.underlying_operations import …` |
> | `from path_config import …` | `from douyin.core.path_config import …` |
>
> 入口脚本现在统一放在 `bin/` 下,根目录已不再保留 launcher 转发。文档里所有 `python run_cli.py …` 示例命令请改读为 `python bin/run_cli.py …`,其他入口同理。
-- 变更记录
- 2026-01-18: V4.5 — 修复预约更新后的循环问题,添加强制切换标志防止在同一直播间反复检测。
- 2026-01-18: V4.4 — 修复并行OCR重试导致日志/重试噪音,参与失败自动切换直播间;购物红包像素+OCR复查(非直播间也OCR复查);并行OCR完成后写盘映射表以提升回退校验一致性;预约回退纠偏(方向提示)与二次回退改进;GUI映射表自适应列与新增购物红包阈值配置(GUI暴露)。
@@ -133,7 +152,7 @@ PY
- 映射表福袋信息记录修复:
- `douyin/fudai/douyin_fudai_core.py`:修复映射表中福袋信息记录缺失问题,在记录映射表前确保`_current_fudai_content`和`_last_fudai_detail_tuple`属性已被正确设置。
- `fudai_detail_modules/fudai_detail_reader.py`:优化福袋详情识别完成后映射表记录时机,将并行映射表记录从OCR开始前移动到福袋详情识别完成后,确保福袋内容和详情信息完整记录到映射表。
- `douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`,2026-05 合并到 core/):优化福袋详情识别完成后映射表记录时机,将并行映射表记录从OCR开始前移动到福袋详情识别完成后,确保福袋内容和详情信息完整记录到映射表。
- 预约锁定期保护机制:
- `douyin/core/douyin_fudai.py`:修复预约福袋参与成功后锁定期被提前清除的问题,实现依次参与保护机制;参与成功后检查是否还有其他预约,如果有则设置10秒保护期,确保预约福袋依次参与不被其他预约打断;如果没有其他预约则正常清除锁定期。
@@ -187,7 +206,7 @@ else:
# 映射表福袋信息记录验证
python -c "
from fudai_detail_modules import fudai_detail_reader
from douyin.fudai.core import fudai_detail_orchestrator as fudai_detail_reader
import inspect
source = inspect.getsource(fudai_detail_reader.read_fudai_detail_once)
if 'analyser._current_fudai_content = content' in source and 'analyser._last_fudai_detail_tuple = detail_tuple' in source and '在福袋详情识别完成后记录映射表' in source:
@@ -214,10 +233,10 @@ else:
- 任务计数检测优化:
- `douyin/stage/douyin_stage.py`:限制任务计数仅在触发原因 "find_and_open_fudai_detail_click_verification" 时设置,避免重复诊断。
- `douyin/fudai/douyin_fudai_core.py`:删除备用阶段检测逻辑,默认任务计数为 0,增加警告日志。
- `fudai_detail_modules/fudai_detail_reader.py`:默认任务计数为 0,增强警告日志输出。
- `douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`):默认任务计数为 0,增强警告日志输出。
- 日志时间戳统一:
- `douyin/logging/douyin_logging.py`:新增 MillisecondFormatter 类。
- `unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。
- `douyin/logging/unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。
- `douyin/logging/action_logger.py`:更新为使用 MillisecondFormatter。
- 截图复用优化:
- 确保在福袋详情页关闭前复用截图,避免不必要的重复截图。
@@ -234,10 +253,10 @@ else:
# 语法检查
python -m py_compile douyin/stage/douyin_stage.py
python -m py_compile douyin/fudai/douyin_fudai_core.py
python -m py_compile fudai_detail_modules/fudai_detail_reader.py
python -m py_compile douyin/fudai/core/fudai_detail_orchestrator.py
# 运行短会话验证
python run_cli.py --wait-minutes 0 --device-id <ADB_ID>
python bin/run_cli.py --wait-minutes 0 --device-id <ADB_ID>
# 检查日志格式
Get-Content logs/actions.log -Tail 10 | Select-String "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}"
@@ -260,13 +279,13 @@ pip install -r requirements-minimal.txt
3. 运行主流程(单设备示例):
```powershell
python run_cli.py --device-id <ADB_ID> --needswitch
python bin/run_cli.py --device-id <ADB_ID> --needswitch
```
4. 调试单次循环:
```powershell
python run_cli.py --device-id <ADB_ID> --wait-minutes 0
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 0
```
说明:如需快速禁用 OCR 启动耗时,可设置环境变量 `SKIP_OCR_INIT=1`。
@@ -288,13 +307,13 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 0
1. 代码内默认值(常量/类属性)
2. `config/config.json`(通过 `path_config.get_config_path()` 获取)
3. 环境变量(例如 `SKIP_OCR_INIT`, `DISABLE_SCREENSHOT_MIRROR`)
4. 命令行参数(`run_cli.py` 解析,优先级最高,运行时覆盖实例属性)
4. 命令行参数(`bin/run_cli.py` 解析,优先级最高,运行时覆盖实例属性)
示例:通过命令行临时指定设备优先于 `config/config.json` 中的默认设备。
实现建议与样例:
- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `run_cli.py` 中用命令行覆盖字段。
- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `bin/run_cli.py` 中用命令行覆盖字段。
- 推荐在 `config/config.json` 中采用明确分组,例如:
```json
@@ -305,7 +324,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 0
}
```
- 命令行覆盖示例(`run_cli.py` 中解析后合并):
- 命令行覆盖示例(`bin/run_cli.py` 中解析后合并):
```python
# pseudo
@@ -318,7 +337,7 @@ if args.device_id:
- 使用代码内默认值并在日志中写 warning;
- 在关键字段(如 `device`、`ocr_engine`)缺失时中断并提示用户。
关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`path_config.py`,`run_cli.py`。
关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`douyin/core/path_config.py`,`bin/run_cli.py`。
## 截图 / OCR / 日志 / 状态(实现细节与故障采样)
@@ -326,12 +345,12 @@ if args.device_id:
- 优先方式:`adb exec-out screencap -p`(单次 adb 调用,速度最快)。
- 回退方式:`adb shell screencap -p /sdcard/screen.png` + `adb pull`(兼容性但更慢)。
- 写入策略:先写入临时文件(例如 `screenshot.png.tmp`),再通过原子替换或安全复制覆盖 `pic/screenshot.png`,以避免并发读取到半写入文件。见 `Underlying_Operations.get_screenshot()` 的实现。
- 写入策略:先写入临时文件(例如 `screenshot.png.tmp`),再通过原子替换或安全复制覆盖 `pic/screenshot.png`,以避免并发读取到半写入文件。见 `underlying_operations.get_screenshot()` 的实现。
- Windows 文件锁与镜像:`_safe_replace_file()` 包含多重回退(`os.replace` → `shutil.copy2` → 分块复制),并可通过环境变量 `DISABLE_SCREENSHOT_MIRROR=1` 禁用将截图镜像到外部目录(`EXTERNAL_DOUYIN_FUDAI_DIR`)。
2) OCR(策略与初始化)
- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `Underlying_Operations.analyse_pic_word()`。
- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `underlying_operations.analyse_pic_word()`。
- 延迟初始化:支持 `SKIP_OCR_INIT=1`(跳过启动时初始化),首次调用时会在 `_ensure_ocr()` 进行按需初始化。
- 回退与容错:若 OCR 未能初始化或识别失败,函数返回空字符串,上层代码需对空结果做容错与重试。建议生产环境安装 `easyocr` 并允许启动时初始化以减少首次延迟。
@@ -362,7 +381,7 @@ Remove-Item pic\screenshot.png.tmp -Force -ErrorAction SilentlyContinue
- OCR 未初始化或识别异常:
```python
from Underlying_Operations import underlying_operations
from douyin.core.underlying_operations import underlying_operations
op = underlying_operations()
op._ensure_ocr()
print(op.analyse_pic_word('pic/screenshot.png'))
@@ -382,7 +401,7 @@ print(op.analyse_pic_word('pic/screenshot.png'))
1) 在短时间窗口运行主流程以生成调试图片和日志(注意 `debug_captures.enabled`):
```powershell
python run_cli.py --device-id <ADB_ID> --wait-minutes 1
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 1
```
2) 基于日志时间戳筛选 `pic/` 下的候选图片(示例:按文件修改时间):
@@ -419,14 +438,14 @@ powershell -Command "Get-Content tools/coords_report.csv -TotalCount 200 | Out-F
python -m py_compile $(git ls-files "**/*.py")
```
- 关键文件存在性检查:确保 `run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py` 存在并可被导入。
- 关键文件存在性检查:确保 `bin/run_cli.py`、`douyin/core/underlying_operations.py`、`config/config.json`、`douyin/core/path_config.py` 存在并可被导入。
示例 CI 脚本片段:
```bash
python -m py_compile $(git ls-files "**/*.py") || exit 1
python - <<'PY'
from path_config import get_reservations_path
from douyin.core.path_config import get_reservations_path
import os
print('reservations path', get_reservations_path())
assert os.path.isdir(os.path.dirname(get_reservations_path()))
@@ -440,14 +459,14 @@ PY
- 项目意图(一句话):自动化在抖音直播中查找并参与“福袋”活动的流程化机器人,包含截图、像素/模板检测、OCR、决策与预约管理。
- 关键入口(按优先级):
- `run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
- `bin/run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
- `douyin/core/douyin_fudai.py::fudai_choujiang()`:主循环调度;查看运行状态与错误堆栈。
- `Underlying_Operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
- `douyin/core/underlying_operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
- 可调用的“程序式”API(Python)示例:
```python
from Underlying_Operations import underlying_operations
from douyin.core.underlying_operations import underlying_operations
op = underlying_operations()
# 获取当前截图路径
img = op.get_screenshot('<ADB_ID>')
@@ -456,7 +475,7 @@ text = op.analyse_pic_word(img)
```
- 关键文件与含义速查表(便于 LLM 快速定位实现细节):
- `path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
- `douyin/core/path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
- `douyin/logging/douyin_logging_wrapper.py`:业务日志封装——搜索 `traceId` 与 `stage`。
- 可观测数据(建议供 AI 检索):
@@ -486,22 +505,22 @@ text = op.analyse_pic_word(img)
6) 参考实现与文件链接
- 截图与裁剪:`Underlying_Operations.get_screenshot()`、`Underlying_Operations.cut_pic()`。
- OCR:`Underlying_Operations.analyse_pic_word()`、`Underlying_Operations.analyse_pic_digits()`。
- 截图与裁剪:`underlying_operations.get_screenshot()`、`underlying_operations.cut_pic()`。
- OCR:`underlying_operations.analyse_pic_word()`、`underlying_operations.analyse_pic_digits()`。
- 日志:`douyin/logging/douyin_logging.py`、`douyin/logging/douyin_logging_wrapper.py`。
- 路径与状态:`path_config.py`、`state/reservations.json`。
- 路径与状态:`douyin/core/path_config.py`、`state/reservations.json`。
以上补充将帮助运维快速定位截图/OCR/日志相关问题并提供明确采样路径供后续模型/规则优化使用。
## 核心模块地图(快捷索引)
- `run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。
- `bin/run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。
- `douyin/core/douyin_fudai.py`:主分析器/主循环(`fudai_choujiang`、`run_once_basic`)。
- `Underlying_Operations.py`:底层设备/截图/OCR/文件操作。
- `douyin/core/underlying_operations.py`:底层设备/截图/OCR/文件操作。
- `douyin/detection/douyin_pixel.py`:像素检测与并行检测实现。
- `douyin/fudai/douyin_fudai_core.py`:福袋核心逻辑。
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py` 第214行,`fudai_detail_modules/fudai_detail_reader.py` 第15行和第315行。
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py`、`douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`,已合并到 core/)。具体行号会随重构变化,以代码当前状态为准。
- `basic_join_decision`:基础版参与决策,根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。调用位置:`douyin/core/douyin_fudai.py` 第3127行和第3721行。
- `attend_choujiang`:点击参与抽奖。调用位置:`douyin/core/douyin_fudai.py` 第2892行,`douyin/core/fudai_modules/fudai_main_logic.py` 第223行,以及文件内多处。
- `check_lucky_draw_result`:判定福袋抽奖的结果(简化)。统一只检测开奖结果按钮区域(使用 HelperFunctions.check_lottery_result_by_ocr),不再对弹窗文字或其它区域进行OCR识别。返回:1='我知道了', 2='立即领取奖品', False=未识别。调用位置:文件内第3913行。
@@ -527,7 +546,7 @@ text = op.analyse_pic_word(img)
- `douyin/stage/douyin_stage.py`:阶段诊断入口(`diagnose_stage_from_current_screen`)。
- `douyin/reservation/douyin_reservation_logic.py`:预约加载与回退处理。
- `path_config.py`:统一路径获取,避免硬编码。
- `douyin/core/path_config.py`:统一路径获取,避免硬编码。
在文档中引用这些文件并包含小示例会帮助维护者快速定位实现点。
@@ -573,7 +592,7 @@ text = op.analyse_pic_word(img)
## 运行流程概览(精简)
1. `run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
1. `bin/run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
2. `fudai_choujiang()` 循环调用 `run_once_basic()`
3. `run_once_basic()` 流程要点:
- 处理等待开奖 / 预约回退
@@ -586,7 +605,7 @@ text = op.analyse_pic_word(img)
1. 验证截图是否可用:
```powershell
python -c "from Underlying_Operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot('<DEVICE_ID>'))"
python -c "from douyin.core.underlying_operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot('<DEVICE_ID>'))"
```
2. 快速语法检查(仓库级):
@@ -599,7 +618,7 @@ python -m py_compile $(git ls-files "**/*.py")
```powershell
# 伪命令示例:运行一段短时日志以产生调试图片
python run_cli.py --device-id <ADB_ID> --wait-minutes 1
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 1
# 手动或团队自定义脚本筛选 pic/ 下的失败图片并复制到约定目录(例如 tools/samples/)
```
@@ -620,7 +639,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 1
## 验证清单(可纳入 CI)
1. `python -m py_compile` 全仓库通过。
2. 关键路径存在检查:`run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py`。
2. 关键路径存在检查:`bin/run_cli.py`、`douyin/core/underlying_operations.py`、`config/config.json`、`douyin/core/path_config.py`。
3. `path_config.get_reservations_path()` 返回文件夹存在性检查。
示例 CI 命令片段:
@@ -628,7 +647,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 1
```bash
python -m py_compile $(git ls-files "**/*.py") || exit 1
python - <<'PY'
from path_config import get_reservations_path
from douyin.core.path_config import get_reservations_path
import os
print('reservations path', get_reservations_path())
assert os.path.isdir(os.path.dirname(get_reservations_path()))
@@ -941,7 +960,7 @@ _handle_in_fudai_detail()
#### `run_cli.py::main(argv: list[str]) -> int`
- **文件位置**: `run_cli.py`
- **文件位置**: `bin/run_cli.py`
- **作用**: 命令行入口函数,解析参数并启动主程序
- **参数**:
- `argv`: 命令行参数列表
@@ -1860,7 +1879,7 @@ def attend_choujiang(analyser) -> bool:
```python
def load_reservations_from_state(analyser) -> list:
import json
import path_config
from douyin.core import path_config
reservations_path = path_config.get_reservations_path()
if not os.path.exists(reservations_path):
@@ -2250,19 +2269,19 @@ is_match, reason, debug = match_reservation(item, detail)
## 5. 底层操作函数
底层操作函数封装在 `Underlying_Operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。
底层操作函数封装在 `douyin/core/underlying_operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。
### 5.1 设备操作函数
#### `underlying_operations.select_device() -> str | bool`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 选择需要连接的Android设备
- **参数**: 无
- **返回值**:
- `str`: 设备ID(单设备或多设备选择后)
- `False`: 无设备连接
- **调用位置**: `run_cli.py` 的 `main()` 函数中调用
- **调用位置**: `bin/run_cli.py` 的 `main()` 函数中调用
- **实现细节**:
- 执行 `adb devices` 命令获取设备列表
- 使用正则表达式提取设备ID(支持IP地址和序列号)
@@ -2281,7 +2300,7 @@ if not device_id:
#### `underlying_operations.get_device_resolution(device_id: str) -> Tuple[int, int]`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 获取Android设备的分辨率
- **参数**:
- `device_id: str`: 设备ID
@@ -2301,7 +2320,7 @@ analyser.resolution_ratio_y = height
#### `underlying_operations.click(device_id: str, x: int, y: int) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 在设备屏幕上点击指定坐标
- **参数**:
- `device_id: str`: 设备ID
@@ -2320,7 +2339,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
#### `underlying_operations.click_back(device_id: str) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 点击Android返回键(KEYCODE_BACK)
- **参数**:
- `device_id: str`: 设备ID
@@ -2331,7 +2350,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
#### `underlying_operations.click_confirm(device_id: str) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 点击确认键(KEYCODE_ENTER)
- **参数**:
- `device_id: str`: 设备ID
@@ -2344,7 +2363,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
#### `underlying_operations.get_screenshot(device_id: str, path: str = "pic") -> bool`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 获取设备屏幕截图并保存到本地
- **参数**:
- `device_id: str`: 设备ID
@@ -2380,7 +2399,7 @@ else:
#### `underlying_operations.save_reward_pic(device_id: str) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 保存中奖截图(带时间戳)
- **参数**:
- `device_id: str`: 设备ID
@@ -2395,7 +2414,7 @@ else:
#### `underlying_operations.cut_pic(left_up: Tuple[int, int] = (0, 63), right_down: Tuple[int, int] = (1080, 1620), target: str = "", name: str = "") -> bool`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 裁剪图片,获取指定区域的子图片(用于OCR识别)
- **参数**:
- `left_up: Tuple[int, int]`: 左上角坐标(默认(0, 63))
@@ -2432,7 +2451,7 @@ else:
#### `underlying_operations.analyse_pic_word(picname: str, change_color: int = 0, pic_path: Optional[str] = None) -> str`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 对指定图片运行OCR识别,返回拼接后的文本结果
- **参数**:
- `picname: str`: 图片名称(不含扩展名,如"福袋内容")
@@ -2475,7 +2494,7 @@ else:
#### `underlying_operations.analyse_pic_digits(picname: str, change_color: int = 1, pic_path: Optional[str] = None) -> str`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 对指定图片运行OCR识别,专门用于识别数字(倒计时、价值、参与人数等)
- **参数**:
- `picname: str`: 图片名称(不含扩展名,如"倒计时")
@@ -2496,7 +2515,7 @@ countdown_text = operation.analyse_pic_digits("倒计时")
#### `underlying_operations.extract_ocr_content(content: List, return_confidence: bool = False) -> str | Tuple[str, float]`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 从OCR结果中提取文本内容(去除坐标、置信度等信息)
- **参数**:
- `content: List`: OCR原始结果(EasyOCR或PaddleOCR格式)
@@ -2515,7 +2534,7 @@ countdown_text = operation.analyse_pic_digits("倒计时")
#### `underlying_operations.swipe(device_id: str, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 600) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 在设备屏幕上执行滑动操作(从起点滑动到终点)
- **参数**:
- `device_id: str`: 设备ID
@@ -2543,7 +2562,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
#### `underlying_operations.delay(seconds: float = 1.0) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 延迟指定秒数
- **参数**:
- `seconds: float`: 延迟秒数(默认1.0秒)
@@ -2552,7 +2571,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
#### `underlying_operations.random_delay(min_seconds: float = 1.0, max_seconds: float = 100.0) -> None`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 随机延迟指定范围内的秒数(模拟人工操作)
- **参数**:
- `min_seconds: float`: 最小延迟秒数(默认1.0秒)
@@ -2562,7 +2581,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
#### `underlying_operations.check_countdown(last_time: str = "") -> Optional[int]`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 检查倒计时文本,转换为剩余秒数
- **参数**:
- `last_time: str`: 倒计时文本(格式:`mm:ss` 或 `m:ss` 或 `ss`)
@@ -2582,7 +2601,7 @@ remaining_seconds = operation.check_countdown(countdown_text)
#### `underlying_operations.get_current_hour() -> int`
- **文件位置**: `Underlying_Operations.py`
- **文件位置**: `douyin/core/underlying_operations.py`
- **作用**: 获取当前时间的小时数(0-23)
- **参数**: 无
- **返回值**: `int` - 当前小时数(0-23)
@@ -2916,7 +2935,7 @@ class fudai_analyse(
- `needswitch: bool` - 是否允许切换直播间
- `wait_minutes: int` - 每次循环等待时间(分钟)
- **实现**: 设置设备ID和配置,然后循环调用 `run_once_basic()`
- **调用位置**: `run_cli.py` 的 `main()` 函数中调用
- **调用位置**: `bin/run_cli.py` 的 `main()` 函数中调用
#### 6.2.7 BaseFudaiMixin(基础混入类)
@@ -3030,7 +3049,7 @@ UNKNOWN = "UNKNOWN" # 未知阶段
配置文件位于 `config/config.json`,路径通过 `path_config.get_config_path()` 获取。
### 7.1.1 `path_config.py` 用法
### 7.1.1 `douyin/core/path_config.py` 用法
- 使用 `path_config.get_config_path()` 获取配置文件的绝对路径;
- 常用路径获取函数:
@@ -3047,9 +3066,9 @@ UNKNOWN = "UNKNOWN" # 未知阶段
1. 代码中内置的默认值(类属性或常量);
2. `config/config.json`(通过 `path_config.get_config_path()` 指定的文件);
3. 环境变量(仅少数开关被代码显式读取,如 `SKIP_OCR_INIT`, `EXTERNAL_DOUYIN_FUDAI_DIR`, `DISABLE_MODEL_SOURCE_CHECK`, `DISABLE_SCREENSHOT_MIRROR` 等);
4. 命令行参数(`run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
4. 命令行参数(`bin/run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `bin/run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
### 7.2 配置项详解
@@ -3940,7 +3959,7 @@ logger.error(
```python
# run_cli.py
from douyin.core.douyin_fudai import fudai_analyse
from Underlying_Operations import underlying_operations
from douyin.core.underlying_operations import underlying_operations
# 初始化
operation = underlying_operations()
@@ -4673,7 +4692,7 @@ self.new_config_item = self.config.get("new_config_item", False)
#### 15.1.1 入口文件
- **`run_cli.py`**: 命令行入口,初始化设备和分析器
- **`bin/run_cli.py`**: 命令行入口,初始化设备和分析器
- **`gui/gui_app.py`**: Tkinter GUI入口
- **`gui/web_gui.py`**: Web GUI入口
@@ -4706,7 +4725,7 @@ self.new_config_item = self.config.get("new_config_item", False)
#### 15.1.7 底层操作
- **`Underlying_Operations.py`**: 底层操作类(ADB、OCR、图像处理)
- **`douyin/core/underlying_operations.py`**: 底层操作类(ADB、OCR、图像处理)
#### 15.1.8 配置文件
@@ -7097,13 +7116,13 @@ debug_logger.log_exception(e, context={"step": "处理福袋"})
示例:快速启用截图镜像并保留调试图像(Linux/WSL 或 PowerShell 环境变量用法相似)
```bash
EXTERNAL_DOUYIN_FUDAI_DIR=<外部调试目录> SKIP_OCR_INIT=1 python run_cli.py --device-id <DEVICE_ID> --needswitch
EXTERNAL_DOUYIN_FUDAI_DIR=<外部调试目录> SKIP_OCR_INIT=1 python bin/run_cli.py --device-id <DEVICE_ID> --needswitch
```
示例:禁用截图镜像以提高性能
```bash
DISABLE_SCREENSHOT_MIRROR=1 python run_cli.py --device-id <DEVICE_ID>
DISABLE_SCREENSHOT_MIRROR=1 python bin/run_cli.py --device-id <DEVICE_ID>
```
@@ -7197,7 +7216,7 @@ result = analyser.operation.analyse_pic_word(preprocessed_name, 0)
#### 24.2.2 OCR识别优化
**文件位置**: `Underlying_Operations.py`
**文件位置**: `douyin/core/underlying_operations.py`
**优化措施**:
+1 -1
View File
@@ -50,7 +50,7 @@ python gui_app.py
```
#### 方法3:在代码中修改
修改 `Underlying_Operations.py` 中的 `_detect_gpu_available` 方法,将核显检测部分改为:
修改 `douyin/core/underlying_operations.py` 中的 `_detect_gpu_available` 方法,将核显检测部分改为:
```python
if is_integrated:
# 核显:尝试使用GPU加速
+19 -706
View File
@@ -1,710 +1,23 @@
"""
Flow control main helpers (本地模块化实现,基础版)
================================================
"""douyin_flow_control - 兼容入口(保留外部 import 路径)。
当前只实现与你"基础抢福袋、不启用预约"相关的核心流程:
- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)
- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情
- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换
- filter_fudai_detail:根据 config.json 对福袋进行基础筛选
实际实现位于子包 ``douyin.core.douyin_flow_control_pkg``。
本文件仅 re-export 公共符号;详见各子模块文档:
- ``douyin_flow_control_pkg.stage_handler`` handle_stage_after_diagnosis
- ``douyin_flow_control_pkg.find_open`` find_and_open_fudai_detail(最大头 520 行)
- ``douyin_flow_control_pkg.filter`` filter_fudai_detail
- ``douyin_flow_control_pkg.no_fudai`` handle_no_fudai_situation
"""
from __future__ import annotations
from douyin.core.douyin_flow_control_pkg import (
filter_fudai_detail,
find_and_open_fudai_detail,
handle_no_fudai_situation,
handle_stage_after_diagnosis,
)
from typing import Any, Callable, List, Optional, Tuple
import logging
import time
import os
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
import path_config
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
func_start_time: float | None = None,
):
if func_start_time is None:
func_start_time = time.time()
return find_and_open_fudai_detail(
analyser=analyser,
stage=stage,
seen=seen,
func_start_time=func_start_time,
)
def find_and_open_fudai_detail(
analyser: Any,
stage: Any = "",
seen: Any = "",
func_start_time: float | None = None,
):
"""主实现:检测福袋图标并点击打开详情页。"""
if func_start_time is None:
func_start_time = time.time()
# 如果正在等待开奖,不应该再次打开福袋详情
try:
if getattr(analyser, "_waiting_for_lottery_result", False):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
)
except Exception as e:
logging.debug("日志记录失败: %s", e)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception as e:
logging.debug("检查等待开奖状态失败: %s", e)
device_id = getattr(analyser, "device_id", "")
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
# 在配置的最大等待时间内重复检测福袋图标
max_wait_seconds = float(
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
)
retry_delay_seconds = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
start_time = time.time()
x = False
while (time.time() - start_time) < max_wait_seconds:
# 在调用检测函数之前,检查是否还有足够的时间
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
if remaining < 1.0:
break
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
if not x:
# 再次检查时间,防止第二次调用导致超时
elapsed = time.time() - start_time
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
x = check_have_fudai_with_ready_screenshot(
analyser, screenshot_ready=False
)
if x:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标",
x=int(x or 0),
elapsed_seconds=round(time.time() - start_time, 2),
)
except Exception:
pass
# 结构化统计:检测到福袋(attempt)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_detected",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
break
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
if remaining <= 0:
break
wait_time = min(retry_delay_seconds, remaining)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
elapsed_seconds=round(elapsed, 2),
remaining_seconds=round(remaining, 2),
wait_seconds=round(wait_time, 2),
)
except Exception:
pass
try:
analyser.operation.delay(wait_time)
except Exception:
time.sleep(wait_time)
if not x:
try:
total_elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
x=int(x or 0),
max_wait_seconds=max_wait_seconds,
total_elapsed_seconds=round(total_elapsed, 2),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(未找到福袋)",
elapsed_seconds=round(elapsed, 2),
)
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
try:
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
cur += 1
setattr(analyser, "_consecutive_no_fudai_count", cur)
threshold = (
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
)
if threshold is None or threshold <= 0:
# 如果未配置阈值,则尝试读取配置属性(兼容性)
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
threshold = int(
cfg.get("fudai_exit_after_misses", 30) or 30
)
except Exception:
threshold = 30
# 如果计数达到阈值,执行返回键退出直播间并重置计数
if threshold and cur >= threshold:
try:
analyser._log_kv(
"流程",
"连续未找到福袋达到阈值:按返回键退出直播间",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 检查是否启用了返回键回退(优先 analyser 属性,回退到配置文件)
enabled = getattr(analyser, "enable_back_on_misses", None)
if enabled is None:
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
enabled = bool(cfg.get("enable_back_on_misses", True))
else:
enabled = True
except Exception:
enabled = True
if enabled:
# 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复
try:
import time as _time
recent_ts = getattr(analyser, "_recent_reset_ts", 0)
if recent_ts and (_time.time() - float(recent_ts) < 5.0):
try:
analyser._log_kv(
"流程",
"检测到近期已由滑动重置触发回退,跳过重复按返回键",
)
except Exception:
pass
else:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
try:
# 兜底:使用通用 click 返回坐标
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
back_x = int(50 * rx / 1080)
back_y = int(50 * ry / 2400)
analyser.operation.click(
analyser.device_id, back_x, back_y
)
except Exception:
pass
except Exception:
# 在异常情况下保守地尝试按返回键
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
else:
try:
analyser._log_kv(
"流程",
"返回键回退已禁用,跳过按返回键",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 重置计数,避免重复触发
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
except Exception:
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
pass
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
base_y = 403 # 与检测时使用的同一水平线附近
click_x = int(x * rx / 1080)
click_y = int(base_y * ry / 2400)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标并点击",
fudai_x=int(x),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 结构化统计:点击尝试
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_click_attempt",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image # type: ignore[import]
import importlib
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
try:
box_r = 30
coord_box = (
max(0, click_x - box_r),
max(0, click_y - box_r),
click_x + box_r,
click_y + box_r,
)
except Exception:
coord_box = None
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=coord_box,
extra_info={
"source": "flow_on_detect",
"click_x": click_x,
"click_y": click_y,
"detected_x_scaled": click_x,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"流程检测到福袋图标后保存完整截图",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后固定等待",
wait_seconds=wait_seconds,
)
except Exception:
pass
try:
analyser.operation.delay(wait_seconds)
except Exception:
time.sleep(wait_seconds)
from douyin.stage import douyin_stage
analyser.operation.get_screenshot(device_id, use_service=False)
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
)
except Exception:
pass
return False
try:
result = douyin_stage.diagnose_stage_from_current_screen(
analyser, trigger_reason="find_and_open_fudai_detail_click_verification"
)
if result is None:
stage, reason = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, reason = result
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测",
stage=stage,
reason=reason,
)
except Exception:
pass
if stage == "FUDai_DETAIL":
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
stage=stage,
reason=reason,
)
except Exception:
pass
try:
# 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:阶段诊断后诊断结果状态",
task_count_from_stage=getattr(
analyser, "_fudai_detail_task_count_from_stage", None
),
screenshot_ready_for_ocr=getattr(
analyser, "_screenshot_ready_for_ocr", False
),
)
except Exception:
pass
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
# 成功打开福袋详情:重置连续未找到计数
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
try:
# 结构化统计:成功打开详情(success)
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return True
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
stage=stage,
reason=reason,
)
except Exception:
pass
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
try:
back_click_x = int(520 * rx / 1080)
back_click_y = int(505 * ry / 2400)
except Exception:
back_click_x, back_click_y = 520, 505
try:
analyser.operation.click(device_id, back_click_x, back_click_y)
except Exception:
try:
analyser.click(back_click_x, back_click_y)
except Exception:
pass
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
try:
analyser.last_fudai_x = 0
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="fail",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return False
except Exception as e:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测异常",
error=str(e),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(阶段检测异常)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
try:
analyser.click(x, base_y)
wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
analyser.operation.delay(wait_seconds)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底成功)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
return False
def filter_fudai_detail(
analyser: Any,
detail: tuple,
x: int,
needswitch: bool,
post_switch_delay_s: float,
close_detail_callback,
swipe_up_switch_callback,
add_reservation_callback,
) -> bool:
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
start_time = time.time()
skip, reason = should_skip_fudai_by_config(analyser, detail)
try:
content = (
str(detail[0] or "")
if isinstance(detail, tuple) and len(detail) >= 1
else ""
)
analyser._log_kv(
"流程",
"filter_fudai_detail",
x=x,
needswitch=needswitch,
skip=int(bool(skip)),
reason=reason,
content_preview=content[:60] if content else "",
)
except Exception:
pass
if not skip:
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选通过)",
elapsed_seconds=round(elapsed, 2),
)
return False
try:
close_detail_callback(analyser)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
try:
time.sleep(post_switch_delay_s or 1.2)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选不通过)",
elapsed_seconds=round(elapsed, 2),
reason=reason,
)
return True
def handle_no_fudai_situation(
analyser: Any,
x: int,
swipe_times: int,
wait_times_ref: List[int],
needswitch: bool,
reservation_focus_until_ts: float,
reservations: list,
room_pos: int,
post_switch_delay_s: float,
swipe_up_switch_callback: Optional[Callable[[], None]],
swipe_down_back_callback: Callable[[], None],
sort_reservations_callback: Callable[[], None],
clear_reservations_callback: Callable[[], None],
write_state_callback: Callable[[], None],
back_to_list_callback: Callable[[], None],
into_list_callback: Callable[[], None],
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
reservation_after_action_pending_ref: Optional[List[bool]] = None,
reservation_back_swipe_delay_s: Optional[float] = None,
) -> bool:
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
handled_reservation = False
seek_callback = seek_reservation_room_callback or (lambda item: False)
reservation_after_action_pending_ref = (
reservation_after_action_pending_ref
if reservation_after_action_pending_ref
else [False]
)
reservation_back_swipe_delay_s = (
reservation_back_swipe_delay_s
if reservation_back_swipe_delay_s is not None
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
)
try:
from douyin.reservation import douyin_reservation_logic
handled_reservation = (
douyin_reservation_logic.process_reservation_attend_window(
analyser,
reservations,
room_pos,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
reservation_back_swipe_delay_s,
swipe_down_back_callback,
seek_callback,
sort_reservations_callback,
write_state_callback,
)
)
except Exception:
handled_reservation = False
if handled_reservation:
return True
if wait_times_ref:
wait_times_ref[0] += 1
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
except Exception:
pass
delay_seconds = float(post_switch_delay_s or 1.0)
try:
analyser.operation.delay(delay_seconds)
except Exception:
time.sleep(delay_seconds)
if swipe_times_ref:
swipe_times_ref[0] += 1
return False
__all__ = [
"handle_stage_after_diagnosis",
"find_and_open_fudai_detail",
"filter_fudai_detail",
"handle_no_fudai_situation",
]
@@ -0,0 +1,25 @@
"""douyin_flow_control_pkg - 流程控制子包。
原 douyin/core/douyin_flow_control.py 拆成 4 个子模块:
- stage_handler handle_stage_after_diagnosis 阶段后状态记录
- find_open find_and_open_fudai_detail 找福袋并打开详情(最大头 520 行)
- filter filter_fudai_detail 配置筛选决策
- no_fudai handle_no_fudai_situation 无福袋时的简单流程
外部 import 路径不变:
``from douyin.core.douyin_flow_control import find_and_open_fudai_detail``
仍可用(原文件改成 re-export shim)。
"""
from .stage_handler import handle_stage_after_diagnosis
from .find_open import find_and_open_fudai_detail
from .filter import filter_fudai_detail
from .no_fudai import handle_no_fudai_situation
__all__ = [
"handle_stage_after_diagnosis",
"find_and_open_fudai_detail",
"filter_fudai_detail",
"handle_no_fudai_situation",
]
@@ -0,0 +1,85 @@
"""douyin_flow_control_pkg.filter - 福袋详情筛选决策。
filter_fudai_detail:调用 should_skip_fudai_by_config 做配置层筛选,
返回是否参与的决策。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def filter_fudai_detail(
analyser: Any,
detail: tuple,
x: int,
needswitch: bool,
post_switch_delay_s: float,
close_detail_callback,
swipe_up_switch_callback,
add_reservation_callback,
) -> bool:
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
start_time = time.time()
skip, reason = should_skip_fudai_by_config(analyser, detail)
try:
content = (
str(detail[0] or "")
if isinstance(detail, tuple) and len(detail) >= 1
else ""
)
analyser._log_kv(
"流程",
"filter_fudai_detail",
x=x,
needswitch=needswitch,
skip=int(bool(skip)),
reason=reason,
content_preview=content[:60] if content else "",
)
except Exception:
pass
if not skip:
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选通过)",
elapsed_seconds=round(elapsed, 2),
)
return False
try:
close_detail_callback(analyser)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
try:
time.sleep(post_switch_delay_s or 1.2)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选不通过)",
elapsed_seconds=round(elapsed, 2),
reason=reason,
)
return True
@@ -0,0 +1,537 @@
"""douyin_flow_control_pkg.find_open - 主流程:找福袋图标并打开详情页。
find_and_open_fudai_detail:通过像素检测 / 模板匹配找到福袋图标位置,
点击进入详情页,处理打开失败、被弹窗遮挡等异常情况。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def find_and_open_fudai_detail(
analyser: Any,
stage: Any = "",
seen: Any = "",
func_start_time: float | None = None,
):
"""主实现:检测福袋图标并点击打开详情页。"""
if func_start_time is None:
func_start_time = time.time()
# 如果正在等待开奖,不应该再次打开福袋详情
try:
if getattr(analyser, "_waiting_for_lottery_result", False):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
)
except Exception as e:
logging.debug("日志记录失败: %s", e)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception as e:
logging.debug("检查等待开奖状态失败: %s", e)
device_id = getattr(analyser, "device_id", "")
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
# 在配置的最大等待时间内重复检测福袋图标
max_wait_seconds = float(
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
)
retry_delay_seconds = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
start_time = time.time()
x = False
while (time.time() - start_time) < max_wait_seconds:
# 在调用检测函数之前,检查是否还有足够的时间
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
if remaining < 1.0:
break
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
if not x:
# 再次检查时间,防止第二次调用导致超时
elapsed = time.time() - start_time
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
x = check_have_fudai_with_ready_screenshot(
analyser, screenshot_ready=False
)
if x:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标",
x=int(x or 0),
elapsed_seconds=round(time.time() - start_time, 2),
)
except Exception:
pass
# 结构化统计:检测到福袋(attempt)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_detected",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
break
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
if remaining <= 0:
break
wait_time = min(retry_delay_seconds, remaining)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
elapsed_seconds=round(elapsed, 2),
remaining_seconds=round(remaining, 2),
wait_seconds=round(wait_time, 2),
)
except Exception:
pass
try:
analyser.operation.delay(wait_time)
except Exception:
time.sleep(wait_time)
if not x:
try:
total_elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
x=int(x or 0),
max_wait_seconds=max_wait_seconds,
total_elapsed_seconds=round(total_elapsed, 2),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(未找到福袋)",
elapsed_seconds=round(elapsed, 2),
)
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
try:
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
cur += 1
setattr(analyser, "_consecutive_no_fudai_count", cur)
threshold = (
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
)
if threshold is None or threshold <= 0:
# 如果未配置阈值,则尝试读取配置属性(兼容性)
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
threshold = int(
cfg.get("fudai_exit_after_misses", 30) or 30
)
except Exception:
threshold = 30
# 如果计数达到阈值,执行返回键退出直播间并重置计数
if threshold and cur >= threshold:
try:
analyser._log_kv(
"流程",
"连续未找到福袋达到阈值:按返回键退出直播间",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 检查是否启用了返回键回退(优先 analyser 属性,回退到配置文件)
enabled = getattr(analyser, "enable_back_on_misses", None)
if enabled is None:
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
enabled = bool(cfg.get("enable_back_on_misses", True))
else:
enabled = True
except Exception:
enabled = True
if enabled:
# 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复
try:
import time as _time
recent_ts = getattr(analyser, "_recent_reset_ts", 0)
if recent_ts and (_time.time() - float(recent_ts) < 5.0):
try:
analyser._log_kv(
"流程",
"检测到近期已由滑动重置触发回退,跳过重复按返回键",
)
except Exception:
pass
else:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
try:
# 兜底:使用通用 click 返回坐标
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
back_x = int(50 * rx / 1080)
back_y = int(50 * ry / 2400)
analyser.operation.click(
analyser.device_id, back_x, back_y
)
except Exception:
pass
except Exception:
# 在异常情况下保守地尝试按返回键
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
else:
try:
analyser._log_kv(
"流程",
"返回键回退已禁用,跳过按返回键",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
# 重置计数,避免重复触发
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
except Exception:
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
pass
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
base_y = 403 # 与检测时使用的同一水平线附近
click_x = int(x * rx / 1080)
click_y = int(base_y * ry / 2400)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标并点击",
fudai_x=int(x),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 结构化统计:点击尝试
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_click_attempt",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image # type: ignore[import]
from douyin.handlers import douyin_screenshot_manager
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
try:
box_r = 30
coord_box = (
max(0, click_x - box_r),
max(0, click_y - box_r),
click_x + box_r,
click_y + box_r,
)
except Exception:
coord_box = None
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=coord_box,
extra_info={
"source": "flow_on_detect",
"click_x": click_x,
"click_y": click_y,
"detected_x_scaled": click_x,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"流程检测到福袋图标后保存完整截图",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后固定等待",
wait_seconds=wait_seconds,
)
except Exception:
pass
try:
analyser.operation.delay(wait_seconds)
except Exception:
time.sleep(wait_seconds)
from douyin.stage import douyin_stage
analyser.operation.get_screenshot(device_id, use_service=False)
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
)
except Exception:
pass
return False
try:
result = douyin_stage.diagnose_stage_from_current_screen(
analyser, trigger_reason="find_and_open_fudai_detail_click_verification"
)
if result is None:
stage, reason = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, reason = result
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测",
stage=stage,
reason=reason,
)
except Exception:
pass
if stage == "FUDai_DETAIL":
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
stage=stage,
reason=reason,
)
except Exception:
pass
try:
# 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:阶段诊断后诊断结果状态",
task_count_from_stage=getattr(
analyser, "_fudai_detail_task_count_from_stage", None
),
screenshot_ready_for_ocr=getattr(
analyser, "_screenshot_ready_for_ocr", False
),
)
except Exception:
pass
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
# 成功打开福袋详情:重置连续未找到计数
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
try:
# 结构化统计:成功打开详情(success)
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return True
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
stage=stage,
reason=reason,
)
except Exception:
pass
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
try:
back_click_x = int(520 * rx / 1080)
back_click_y = int(505 * ry / 2400)
except Exception:
back_click_x, back_click_y = 520, 505
try:
analyser.operation.click(device_id, back_click_x, back_click_y)
except Exception:
try:
analyser.click(back_click_x, back_click_y)
except Exception:
pass
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
try:
analyser.last_fudai_x = 0
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="fail",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return False
except Exception as e:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测异常",
error=str(e),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(阶段检测异常)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
try:
analyser.click(x, base_y)
wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
analyser.operation.delay(wait_seconds)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底成功)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
return False
@@ -0,0 +1,94 @@
"""douyin_flow_control_pkg.no_fudai - 无福袋情况的简单流程。
handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待 / 上滑切换。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def handle_no_fudai_situation(
analyser: Any,
x: int,
swipe_times: int,
wait_times_ref: List[int],
needswitch: bool,
reservation_focus_until_ts: float,
reservations: list,
room_pos: int,
post_switch_delay_s: float,
swipe_up_switch_callback: Optional[Callable[[], None]],
swipe_down_back_callback: Callable[[], None],
sort_reservations_callback: Callable[[], None],
clear_reservations_callback: Callable[[], None],
write_state_callback: Callable[[], None],
back_to_list_callback: Callable[[], None],
into_list_callback: Callable[[], None],
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
reservation_after_action_pending_ref: Optional[List[bool]] = None,
reservation_back_swipe_delay_s: Optional[float] = None,
) -> bool:
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
handled_reservation = False
seek_callback = seek_reservation_room_callback or (lambda item: False)
reservation_after_action_pending_ref = (
reservation_after_action_pending_ref
if reservation_after_action_pending_ref
else [False]
)
reservation_back_swipe_delay_s = (
reservation_back_swipe_delay_s
if reservation_back_swipe_delay_s is not None
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
)
try:
from douyin.reservation import douyin_reservation_logic
handled_reservation = (
douyin_reservation_logic.process_reservation_attend_window(
analyser,
reservations,
room_pos,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
reservation_back_swipe_delay_s,
swipe_down_back_callback,
seek_callback,
sort_reservations_callback,
write_state_callback,
)
)
except Exception:
handled_reservation = False
if handled_reservation:
return True
if wait_times_ref:
wait_times_ref[0] += 1
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
except Exception:
pass
delay_seconds = float(post_switch_delay_s or 1.0)
try:
analyser.operation.delay(delay_seconds)
except Exception:
time.sleep(delay_seconds)
if swipe_times_ref:
swipe_times_ref[0] += 1
return False
@@ -0,0 +1,34 @@
"""douyin_flow_control_pkg.stage_handler - 阶段诊断后的状态记录。
handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转),
为基础抢福袋流程的状态机提供锚点。
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
func_start_time: float | None = None,
):
if func_start_time is None:
func_start_time = time.time()
return find_and_open_fudai_detail(
analyser=analyser,
stage=stage,
seen=seen,
func_start_time=func_start_time,
)
+132 -3654
View File
File diff suppressed because it is too large. Load diff
+11 -3
View File
@@ -5,9 +5,14 @@
from __future__ import annotations
import logging
from typing import Any, Protocol, Optional
from abc import ABC
# 模块级 logger:当 _enhanced_log_kv 不可用时走 logging 而非 stdout,
# 避免日志记录路径在异常分支里降级为裸 print。
_LOGGER = logging.getLogger("douyin.core.fudai_modules.base_interface")
class FudaiAnalyzerInterface(Protocol):
"""福袋分析器接口协议"""
@@ -54,11 +59,14 @@ class BaseFudaiMixin:
if hasattr(self, '_enhanced_log_kv'):
self._enhanced_log_kv(*args, **fields) # type: ignore
else:
# 兜底:使用标准print
print(f"[LOG] {args} {fields}")
# 兜底:走模块级 logger
_LOGGER.info("[LOG] %s %s", args, fields)
except Exception:
# 最后兜底
print(f"[LOG] {args} {fields}")
try:
_LOGGER.info("[LOG] %s %s", args, fields)
except Exception:
pass
def _safe_operation_call(self, operation_name: str, *args, **kwargs) -> Any:
"""安全的操作调用,避免依赖未定义的属性"""
@@ -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] = []
@@ -74,7 +74,7 @@ class MainLogicMixin(BaseFudaiMixin):
# #region agent log
import json
import time as time_module
from path_config import get_debug_log_path
from douyin.core.path_config import get_debug_log_path
current_ts = int(time_module.time() * 1000)
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
@@ -143,7 +143,7 @@ class MainLogicMixin(BaseFudaiMixin):
# #region agent log
import json
from path_config import get_debug_log_path
from douyin.core.path_config import get_debug_log_path
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
+187
View File
@@ -0,0 +1,187 @@
"""文件 IO 与截图镜像辅助函数。
从 douyin/core/underlying_operations.py 顶部抽离的模块级函数,
为多个模块提供共用的安全文件替换和截图镜像能力。
外部 import 路径已通过 underlying_operations 重新导出,保持向后兼容。
"""
from __future__ import annotations
import logging
import os
import time as time_module
from typing import Optional
# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。
# 仅在显式设置 EXTERNAL_DOUYIN_FUDAI_DIR 时启用。
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
_EXTERNAL_AXF_SCREENSHOT = (
os.path.join(_EXTERNAL_DOUYIN_FUDAI_DIR, "pic", "screenshot.png")
if _EXTERNAL_DOUYIN_FUDAI_DIR
else ""
)
def _verify_png_integrity(path: str) -> bool:
"""验证 PNG 文件头尾完整性,防止读取半写文件"""
try:
with open(path, "rb") as f:
header = f.read(8)
if len(header) < 8 or header[:4] != b"\x89PNG":
return False
f.seek(-12, 2) # IEND chunk 至少 12 字节
tail = f.read(12)
return b"IEND" in tail
except Exception:
return False
def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool:
"""安全地替换文件,处理 Windows 文件锁定问题。
优先 os.replace 原子替换;失败时回退到 shutil.copy2,避免长时间等待。
对 PNG 文件会先校验完整性,避免发布半写文件。
Args:
tmp_file: 临时文件路径
out_file: 目标文件路径
max_retries: 最大重试次数(已优化为 2 次)
Returns:
True if successful, False otherwise
"""
import shutil
if not os.path.exists(tmp_file):
return False
# PNG 完整性校验
if tmp_file.lower().endswith(".png"):
if not _verify_png_integrity(tmp_file):
logging.debug("PNG 文件不完整,跳过替换: %s", tmp_file)
return False
# 方法 1:原子替换
try:
os.replace(tmp_file, out_file)
return True
except (OSError, PermissionError):
pass
# 方法 2:shutil.copy2(保留元数据)
try:
shutil.copy2(tmp_file, out_file)
try:
os.remove(tmp_file)
except Exception:
pass
return True
except Exception:
pass
# 方法 3:手动复制(最后手段)
try:
with open(tmp_file, "rb") as src, open(out_file, "wb") as dst:
while True:
chunk = src.read(1048576) # 1MB chunks
if not chunk:
break
dst.write(chunk)
try:
os.remove(tmp_file)
except Exception:
pass
return True
except Exception:
return False
def _ensure_parent_dir(path: str) -> None:
"""确保 path 的父目录存在。"""
try:
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
except Exception:
logging.exception("无法创建父目录: %s", path)
def _mirror_screenshot_to_external(src_file: str) -> None:
"""将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。
若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。
可通过环境变量 DISABLE_SCREENSHOT_MIRROR=1 禁用此功能以提升性能。
"""
if os.environ.get("DISABLE_SCREENSHOT_MIRROR", "0") == "1":
return
mirror_start = time_module.time()
try:
external_path = _EXTERNAL_AXF_SCREENSHOT
if not external_path:
return
external_dir = os.path.dirname(external_path)
if not external_dir:
return
external_base = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "")
is_network_path = False
if external_base:
if external_base.startswith("\\\\") or external_base.startswith("//"):
is_network_path = True
logging.warning(
"[截图] 检测到网络路径,镜像可能较慢: %s", external_base
)
elif ":" in external_base and len(external_base) > 3:
logging.debug("[截图] 镜像目标路径: %s", external_path)
os.makedirs(external_dir, exist_ok=True)
if not os.path.exists(src_file):
return
tmp = external_path + ".tmp"
import shutil
copy_start = time_module.time()
shutil.copyfile(src_file, tmp)
copy_dur = (time_module.time() - copy_start) * 1000.0
if copy_dur > 50.0 or is_network_path:
logging.info(
"[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)",
copy_dur,
src_file,
tmp,
is_network_path,
)
replace_start = time_module.time()
_safe_replace_file(tmp, external_path)
replace_dur = (time_module.time() - replace_start) * 1000.0
if replace_dur > 50.0 or is_network_path:
logging.info(
"[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)",
replace_dur,
is_network_path,
)
mirror_total_dur = (time_module.time() - mirror_start) * 1000.0
if mirror_total_dur > 100.0 or is_network_path:
logging.info(
"[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)",
mirror_total_dur,
external_path,
is_network_path,
)
except Exception:
# 任何错误都不应该影响截图主流程
pass
__all__ = [
"_verify_png_integrity",
"_safe_replace_file",
"_ensure_parent_dir",
"_mirror_screenshot_to_external",
"_EXTERNAL_DOUYIN_FUDAI_DIR",
"_EXTERNAL_AXF_SCREENSHOT",
]
+11 -3
View File
@@ -5,7 +5,11 @@ import os
from typing import Optional
# 项目根目录(所有路径的基准)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# __file__ 位于 <project_root>/douyin/core/path_config.py,
# 所以项目根是当前文件向上两级目录。
PROJECT_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
def get_project_root() -> str:
@@ -57,7 +61,11 @@ def get_state_dir() -> str:
def get_reservations_path() -> str:
"""返回预约队列状态文件的路径(实际位置在douyin/core/state/reservations.json)"""
"""返回预约队列状态文件的路径(实际位置:douyin/core/state/reservations.json)。
该文件由 fudai_analyse 在 douyin/core/douyin_fudai.py 中写入,
供 WebGUI / 桌面 GUI 跨进程读取。
"""
return os.path.join(PROJECT_ROOT, "douyin", "core", "state", "reservations.json")
@@ -127,7 +135,7 @@ def get_robot_verify_pic_path(save_subdir: bool = False) -> str:
def get_run_cli_path() -> str:
"""返回 run_cli.py 的路径(绝对路径)"""
return os.path.abspath(os.path.join(PROJECT_ROOT, "run_cli.py"))
return os.path.abspath(os.path.join(PROJECT_ROOT, "bin", "run_cli.py"))
def ensure_dir(path: str) -> None:
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,42 @@
"""underlying_operations_pkg - underlying_operations 类的零 self 方法子包。
原 douyin/core/underlying_operations.py(3021 行)的 6 个零 self 方法搬出到本子包:
- adb_helpers _adb_path / _pick_adbkeyboard_ime
- pic_path _find_pic_path
- ocr_content extract_ocr_content (218 行)
- countdown check_countdown (161 行)
- bounds _parse_bounds
类 ``underlying_operations`` 留在原文件,方法保留为 1 行 @staticmethod
forwarding(签名不变,外部调用 ``self.X()`` / ``cls.X()`` 全部兼容)。
"""
from .adb_helpers import _adb_path, _pick_adbkeyboard_ime
from .pic_path import _find_pic_path
from .ocr_content import extract_ocr_content
from .countdown import check_countdown
from .bounds import _parse_bounds
from .reward_pic import save_reward_pic
from .swipe_sendevent import _swipe_with_sendevent_improved
from .clipboard import set_clipboard_text
from .device_select import select_device
from .ocr_digits import analyse_pic_digits
from .adb_helpers import _adb_args
__all__ = [
"_adb_path",
"_pick_adbkeyboard_ime",
"_find_pic_path",
"extract_ocr_content",
"check_countdown",
"_parse_bounds",
"save_reward_pic",
"_swipe_with_sendevent_improved",
"set_clipboard_text",
"_adb_args",
"select_device",
"analyse_pic_digits",
]
@@ -0,0 +1,38 @@
"""underlying_operations_pkg.adb_helpers - ADB 辅助。
- _adb_path 返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)
- _pick_adbkeyboard_ime 从 IME 列表里挑出 ADBKeyboard 的 ID
"""
from __future__ import annotations
import os
from typing import List
def _adb_path() -> str:
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
if adb.startswith('"') and adb.endswith('"'):
adb = adb[1:-1]
return adb
def _pick_adbkeyboard_ime(imes: list[str]) -> str:
# 兼容不同包名/组件名写法,优先匹配常见的 AdbIME
for cand in imes or []:
s = str(cand).strip()
ls = s.lower()
if "adbkeyboard" in ls and "adbime" in ls:
return s
for cand in imes or []:
s = str(cand).strip()
ls = s.lower()
if "adbkeyboard" in ls or "adbime" in ls:
return s
return ""
def _adb_args(device_id: str, *args: object) -> list[str]:
"""构造 ``adb -s <device> <args>`` 的命令行参数列表。"""
return [_adb_path(), "-s", str(device_id), *[str(arg) for arg in args]]
@@ -0,0 +1,17 @@
"""underlying_operations_pkg.bounds - bounds 字符串解析。
_parse_bounds: 解析 UI dump 里的 ``[x1,y1][x2,y2]`` 格式。
"""
from __future__ import annotations
import re
from typing import Optional, Tuple
def _parse_bounds(bounds: str):
m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", str(bounds or ""))
if not m:
return None
x1, y1, x2, y2 = map(int, m.groups())
return x1, y1, x2, y2
@@ -0,0 +1,70 @@
"""underlying_operations_pkg.clipboard - 设备剪贴板设置。
set_clipboard_text(device_id, text): 在设备上设置剪贴板内容(支持中文)。
优先 ``cmd clipboard set``(Android 10+),失败回退到 Clipper broadcast。
"""
from __future__ import annotations
import shlex
import subprocess
from .adb_helpers import _adb_args
def set_clipboard_text(device_id: str, text: str) -> bool:
"""设置设备剪贴板文本(尽量支持中文)。
优先:Android 10+ 的 `cmd clipboard set`。
兜底:Clipper(若设备装了 clipper app)。
"""
t = str(text or "").strip()
if not t:
return False
# 使用 shlex.quote 转义文本,防止 shell 注入
safe_t = shlex.quote(t)
# 1) cmd clipboard set
try:
if (
subprocess.run(
_adb_args(device_id, "shell", "cmd", "clipboard", "set", safe_t),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
):
return True
except Exception:
pass
# 2) Clipper broadcast: am broadcast -a clipper.set -e text "..."
try:
if (
subprocess.run(
_adb_args(
device_id,
"shell",
"am",
"broadcast",
"-a",
"clipper.set",
"-e",
"text",
safe_t,
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
):
return True
except Exception:
pass
return False
@@ -0,0 +1,200 @@
"""underlying_operations_pkg.countdown - 倒计时文本解析。
check_countdown: 兼容多种 OCR 误识别的倒计时格式:
- 11:37 / 11:37 / 11:37后开奖
- 1分23秒 / 23秒
- 1137 / 934 / 31
- 字符混淆纠正:O→0, l/I→1, S→5 等
返回 (剩余秒数, 预计开奖时间戳)。
"""
from __future__ import annotations
import logging
import re
import time
from datetime import datetime, timedelta
from typing import Tuple
# 与原 underlying_operations._uo_log 同名 logger,避免改变历史日志检索
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
def _uo_log(msg, level: str = "INFO") -> None:
"""统一底层操作日志出口;本地实现避免对原文件的循环依赖。"""
try:
lv = str(level or "INFO").upper()
text = str(msg)
if lv == "ERROR":
_LOGGER.error(text)
elif lv == "WARNING":
_LOGGER.warning(text)
elif lv == "DEBUG":
_LOGGER.debug(text)
else:
_LOGGER.info(text)
except Exception:
pass
def check_countdown(last_time=""):
"""对倒计时时间进行转化,返回 (剩余秒数, 预计开奖时间戳)。
兼容 OCR 常见格式与误识别:
- 11:37 / 11:37 / 11:37后开奖
- 1分23秒 / 23秒
- 1137 / 934 / 31
- 字符混淆:O->0, l/I->1, S->5 等
"""
def _norm(s: str) -> str:
t = str(s or "")
t = re.sub(r"\s+", "", t)
t = t.replace(":", ":")
# 常见 OCR 混淆纠正
trans = str.maketrans(
{
"O": "0",
"o": "0",
"Q": "0",
"D": "0",
"I": "1",
"l": "1",
"|": "1",
"!": "1",
"S": "5",
"s": "5",
"B": "8",
"G": "6",
"Z": "2",
}
)
t = t.translate(trans)
return t
def _parse_seconds(text: str) -> Optional[int]:
t = _norm(text)
if not t:
return None
# 1) mm:ss(允许 ss 为 1 位)
m = re.search(r"(\d{1,2})[:](\d{1,2})", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
# 若秒数 >= 60,优先尝试交换(OCR 容易把分秒顺序颠倒)
if ss >= 60 and mm < 60:
mm, ss = ss, mm
# 兜底:仍不合法则做进位
if ss >= 60:
mm += ss // 60
ss = ss % 60
return max(0, mm * 60 + ss)
# 2) 中文:x分y秒 / y秒
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
if ss >= 60:
mm += ss // 60
ss = ss % 60
return max(0, mm * 60 + ss)
m = re.search(r"(\d{1,3})秒", t)
if m:
return max(0, int(m.group(1)))
# 3) 纯数字:1137(=11:37) / 934(=9:34) / 31(=31秒)
digits = "".join(ch for ch in t if ch.isdigit())
if not digits:
return None
if len(digits) == 4:
a = int(digits[:2])
b = int(digits[2:])
# 两种解释:a:b 或 b:a。
# 默认按“前两位=分、后两位=秒”,只有在明显异常(>15分钟)或秒不合法时才交换。
if b < 60:
total1 = a * 60 + b
else:
total1 = None
if a < 60:
total2 = b * 60 + a
else:
total2 = None
if total1 is not None and total1 <= 900:
return total1
if total2 is not None and total2 <= 900:
return total2
# 若一个明显异常而另一个更合理(<=900),交换
if total1 is not None and total2 is not None:
if total1 > 900 and total2 <= 900:
return total2
if total2 > 900 and total1 <= 900:
return total1
# 兜底:谁能解析就用谁;都不行则做进位
if total1 is not None:
return total1
if total2 is not None:
return total2
mm, ss = a, b
mm += ss // 60
ss = ss % 60
return mm * 60 + ss
if len(digits) == 3:
mm = int(digits[0])
ss = int(digits[1:])
if ss >= 60:
# 例如 159 可能是 15:09(OCR 丢 0)
mm2 = int(digits[:2])
ss2 = int(digits[2])
if ss2 < 60:
return mm2 * 60 + ss2
mm += ss // 60
ss = ss % 60
return mm * 60 + ss
if len(digits) == 2:
return int(digits) # 直接当秒(更符合“临近开奖”场景)
if len(digits) == 1:
return int(digits)
# 太长:取最后4位(OCR 常把别的数字也识别进来)
tail = digits[-4:]
a = int(tail[:2])
b = int(tail[2:])
if b >= 60 and a < 60:
a, b = b, a
if b >= 60:
a += b // 60
b = b % 60
return a * 60 + b
try:
total_seconds = _parse_seconds(last_time)
if total_seconds is None:
_uo_log("时间格式异常")
return False
_uo_log("剩余总秒数:", total_seconds)
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
if total_seconds > 900:
total_seconds = 890
now = datetime.now()
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
future_time = now + timedelta(seconds=int(total_seconds))
future_timestamp = future_time.timestamp()
future_datetime = datetime.fromtimestamp(future_timestamp)
formatted_future_time = future_datetime.strftime("%Y-%m-%d %H:%M:%S")
_uo_log("预计开奖时间:", formatted_future_time)
return int(total_seconds), future_timestamp
except Exception:
_uo_log("输入的字符串不是有效的时间格式")
return False
@@ -0,0 +1,66 @@
"""underlying_operations_pkg.device_select - 设备选择交互。
select_device(): 列出 adb devices,单设备直接返回,多设备时让用户选。
保留交互 print(CLI 用户在 stdout 看提示),无设备返回 False。
"""
from __future__ import annotations
import subprocess
import sys
from .adb_helpers import _adb_args, _adb_path
def select_device():
"""选择需要连接的设备"""
result = subprocess.run(
[_adb_path(), "devices", "-l"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
totalstring = result.stdout or ""
# print(totalstring)
devicelist = []
for line in totalstring.splitlines()[1:]:
parts = line.split()
if len(parts) >= 2 and parts[1] == "device":
devicelist.append(parts[0])
# devicelist = re.compile(r'(\w*)\s*device\b').findall(totalstring)
devicenum = len(devicelist)
if devicenum == 0:
print("当前无设备连接电脑,请检查设备连接情况!")
return False
elif devicenum == 1:
print("当前有一台设备连接,编号:%s." % devicelist[0])
return devicelist[0]
else:
print("当前存在多台设备连接! 输入数字选择对应设备:")
dictdevice = {}
for i in range(devicenum):
prop = subprocess.run(
_adb_args(devicelist[i], "shell", "getprop", "ro.product.device"),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
modestring = (prop.stdout or "").strip()
print("%s:%s---%s" % (i + 1, devicelist[i], modestring))
dictdevice[i + 1] = devicelist[i]
if not sys.stdin.isatty():
print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。")
return False
num = input()
num = int(num)
while not num in dictdevice.keys():
print("输入不正确,请重新输入:")
num = input()
num = int(num)
return dictdevice[num]
@@ -0,0 +1,228 @@
"""underlying_operations_pkg.ocr_content - OCR 文本拼接 + 置信度。
extract_ocr_content: 把 OCR 引擎返回的多行结果拼成一段文本,
可选附带置信度统计(avg/min/max/count)。
"""
from __future__ import annotations
from typing import Any
def extract_ocr_content(content=None, return_confidence=False):
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容
参数:
content: OCR识别结果
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
返回:
如果return_confidence=False: 返回文本字符串
如果return_confidence=True: 返回(text, confidence_info)元组,其中confidence_info是置信度信息字典
"""
ocr_result = content or []
# 用于收集置信度信息
confidence_scores = []
confidence_info = {
"avg_confidence": 0.0,
"min_confidence": 1.0,
"max_confidence": 0.0,
"item_count": 0,
}
def _extract_text_and_confidence_from_item(item):
"""提取文本和置信度"""
text = ""
confidence = None
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
if isinstance(item, (list, tuple)) and len(item) >= 2:
# EasyOCR格式:item = (bbox, text, confidence),text在索引1,confidence在索引2
if len(item) >= 3:
confidence = item[2]
if isinstance(item[1], str):
text = item[1]
return text, confidence
# 兼容旧格式:[box, (text, score)]
second = item[1]
if isinstance(second, (list, tuple)) and len(second) >= 1:
if isinstance(second[0], str):
return second[0]
if isinstance(second, dict):
for key in ("text", "rec_text", "transcription"):
val = second.get(key)
if isinstance(val, str) and val:
return val
if isinstance(second, str):
return second
# 兼容新格式:dict / 对象
if isinstance(item, dict):
# 常见:rec_texts 为字符串列表
for list_key in ("rec_texts", "texts", "text_list"):
vals = item.get(list_key)
if isinstance(vals, list) and vals:
vals = [v for v in vals if isinstance(v, str) and v]
if vals:
return "".join(vals)
for key in ("text", "rec_text", "transcription"):
val = item.get(key)
if isinstance(val, str) and val:
return val
for attr in ("text", "rec_text", "transcription"):
val = getattr(item, attr, None)
if isinstance(val, str) and val:
return val
# 对象属性里也可能是列表
for list_attr in ("rec_texts", "texts", "text_list"):
vals = getattr(item, list_attr, None)
if isinstance(vals, list) and vals:
vals = [v for v in vals if isinstance(v, str) and v]
if vals:
return "".join(vals)
return ""
# PaddleOCR 可能返回 [[...]] 或 [...]
items = ocr_result
if (
isinstance(ocr_result, list)
and len(ocr_result) == 1
and isinstance(ocr_result[0], list)
):
items = ocr_result[0]
def _extract_xy_from_item(item):
"""尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。"""
try:
if isinstance(item, (list, tuple)) and len(item) >= 1:
box = item[0]
# EasyOCR格式:bbox = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
# PaddleOCR格式:box 为 4 点坐标列表
if isinstance(box, (list, tuple)) and box:
xs = []
ys = []
for p in box:
if isinstance(p, (list, tuple)) and len(p) >= 2:
xs.append(float(p[0]))
ys.append(float(p[1]))
if xs and ys:
return (min(ys), min(xs))
except Exception:
return None
return None
def _extract_text_from_item(item):
"""提取文本(原始逻辑,保持向后兼容)"""
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
if isinstance(item, (list, tuple)) and len(item) >= 2:
# EasyOCR格式:item = (bbox, text, confidence),text在索引1
if isinstance(item[1], str):
return item[1]
# 兼容旧格式:[box, (text, score)]
second = item[1]
if isinstance(second, (list, tuple)) and len(second) >= 1:
if isinstance(second[0], str):
return second[0]
if isinstance(second, dict):
for key in ("text", "rec_text", "transcription"):
val = second.get(key)
if isinstance(val, str) and val:
return val
if isinstance(second, str):
return second
# 兼容新格式:dict / 对象
if isinstance(item, dict):
# 常见:rec_texts 为字符串列表
for list_key in ("rec_texts", "texts", "text_list"):
vals = item.get(list_key)
if isinstance(vals, list) and vals:
vals = [v for v in vals if isinstance(v, str) and v]
if vals:
return "".join(vals)
for key in ("text", "rec_text", "transcription"):
val = item.get(key)
if isinstance(val, str) and val:
return val
for attr in ("text", "rec_text", "transcription"):
val = getattr(item, attr, None)
if isinstance(val, str) and val:
return val
# 对象属性里也可能是列表
for list_attr in ("rec_texts", "texts", "text_list"):
vals = getattr(item, list_attr, None)
if isinstance(vals, list) and vals:
vals = [v for v in vals if isinstance(v, str) and v]
if vals:
return "".join(vals)
return ""
extracted_items = []
if isinstance(items, list):
for idx, item in enumerate(items):
text = _extract_text_from_item(item)
if not text:
continue
xy = _extract_xy_from_item(item)
if xy is None:
# 无坐标信息:保持原相对顺序
extracted_items.append((1e18, float(idx), text))
else:
y, x = xy
extracted_items.append((float(y), float(x), text))
# 按从上到下、从左到右排序;解决同一行多个框的乱序拼接(例如倒计时两段数字)
extracted_items.sort(key=lambda t: (t[0], t[1]))
# 如果不需要返回置信度,直接返回文本(保持向后兼容)
if not return_confidence:
return "".join([t[2] for t in extracted_items])
# 如果需要返回置信度,提取置信度信息
if return_confidence:
for item in items:
confidence = None
# EasyOCR格式:[(bbox, text, confidence), ...]
if isinstance(item, (list, tuple)) and len(item) >= 3:
confidence = item[2]
# PaddleOCR格式:[box, (text, score)]
elif isinstance(item, (list, tuple)) and len(item) >= 2:
second = item[1]
if isinstance(second, (list, tuple)) and len(second) >= 2:
confidence = second[1]
elif isinstance(second, dict):
confidence = second.get("confidence") or second.get("score")
if confidence is not None:
try:
conf_float = float(confidence)
confidence_scores.append(conf_float)
confidence_info["min_confidence"] = min(
confidence_info["min_confidence"], conf_float
)
confidence_info["max_confidence"] = max(
confidence_info["max_confidence"], conf_float
)
except (ValueError, TypeError):
pass
if confidence_scores:
confidence_info["avg_confidence"] = sum(confidence_scores) / len(
confidence_scores
)
confidence_info["item_count"] = len(confidence_scores)
else:
confidence_info["min_confidence"] = 0.0
return "".join([t[2] for t in extracted_items]), confidence_info
return "".join([t[2] for t in extracted_items])
@@ -0,0 +1,47 @@
"""underlying_operations_pkg.ocr_digits - 数字 OCR 识别。
analyse_pic_digits(analyser, picname, change_color=1, pic_path=None):
轻量数字 OCR 识别。复用 analyser.analyse_pic_word 的核心路径,
拿到原始文本后做数字过滤与智能段提取(保留 . 用于小数)。
"""
from __future__ import annotations
import re
def analyse_pic_digits(analyser, picname, change_color=1, pic_path=None):
"""轻量数字OCR识别函数,专门用于识别数字(0-9)。
策略:
1. 复用 analyse_pic_word 的核心路径(缓存 / 预处理 / OCR 调用 / 调试图保存)
2. change_color=1/2 触发二值化(数字框背景简单时有效)
3. 在拿到原始文本后做数字过滤与智能段提取(保留 . 用于小数)
"""
text = analyser.analyse_pic_word(
picname, change_color=change_color, pic_path=pic_path
)
if not text:
return ""
# 规范化常见全角/中文标点 -> 英文点
text_norm = (
str(text).replace("。", ".").replace(",", ".").replace(".", ".")
)
digits_only = "".join(ch for ch in text_norm if ch.isdigit())
digits = "".join(ch for ch in text_norm if ch.isdigit() or ch == ".")
# 智能过滤:识别出的数字过多通常意味着混入了非目标内容
# (例如把文件名/坐标也识别进来),尝试提取合理段
if len(digits_only) > 10:
digit_segments = re.findall(r"\d+(?:\.\d+)?", text_norm)
if digit_segments:
# 价值类:1-6 位最合理;倒计时:1-2 位最合理
reasonable_segments = [
s for s in digit_segments if 1 <= len(s.replace(".", "")) <= 6
]
if reasonable_segments:
return max(reasonable_segments, key=len)
return min(digit_segments, key=len) if digit_segments else digits[:6]
return digits
@@ -0,0 +1,65 @@
"""underlying_operations_pkg.pic_path - 图片路径查找(含新旧位置兼容)。
_find_pic_path: 按图片名查找路径。运行时必需文件(screenshot/cut)放在
``pic/`` 根;OCR 调试图片按 douyin_screenshot_manager 分类组织到子目录。
"""
from __future__ import annotations
import os
from typing import Optional
def _find_pic_path(picname: str, for_reading: bool = True) -> Optional[str]:
"""查找图片路径,支持新旧位置(向后兼容),并按分类组织
Args:
picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容'
for_reading: True=读取(支持新旧位置),False=写入(使用新位置+分类目录)
Returns:
图片的完整路径,如果找不到且for_reading=True则返回None
"""
try:
from douyin.core import path_config
pic_base = path_config.get_pic_dir()
except Exception:
from douyin.core import path_config
pic_base = path_config.get_pic_dir()
# 运行时必需文件始终在根目录(不需要移动)
runtime_files = {"screenshot", "cut"}
if picname in runtime_files:
path = os.path.join(pic_base, f"{picname}.png")
return path if (os.path.exists(path) or not for_reading) else None
# OCR图片文件:按分类组织到子目录
try:
from douyin.handlers import douyin_screenshot_manager
category = douyin_screenshot_manager.get_category_for_picname(picname)
except Exception:
category = "others"
if for_reading:
# 读取:先查分类目录,再查旧位置(向后兼容)
# 1. 新位置(分类目录)
category_path = os.path.join(pic_base, "ocr", category, f"{picname}.png")
if os.path.exists(category_path):
return category_path
# 2. 旧位置(ocr根目录)
old_ocr_path = os.path.join(pic_base, "ocr", f"{picname}.png")
if os.path.exists(old_ocr_path):
return old_ocr_path
# 3. 更旧的位置(pic根目录)
old_root_path = os.path.join(pic_base, f"{picname}.png")
if os.path.exists(old_root_path):
return old_root_path
return None
else:
# 写入:使用分类目录,确保目录存在
category_dir = os.path.join(pic_base, "ocr", category)
os.makedirs(category_dir, exist_ok=True)
return os.path.join(category_dir, f"{picname}.png")
@@ -0,0 +1,97 @@
"""underlying_operations_pkg.reward_pic - 中奖截图保存。
save_reward_pic(device_id): 中奖时保存当前屏幕截图到 ``pic/<时间>.png``。
优先 exec-out 模式(更快),失败回退到 shell screencap + pull。
"""
from __future__ import annotations
import logging
import os
import subprocess
from datetime import datetime
from douyin.core import path_config
from .adb_helpers import _adb_path
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
def _uo_log(msg, level: str = "INFO") -> None:
try:
lv = str(level or "INFO").upper()
if lv == "ERROR":
_LOGGER.error(str(msg))
elif lv == "WARNING":
_LOGGER.warning(str(msg))
elif lv == "DEBUG":
_LOGGER.debug(str(msg))
else:
_LOGGER.info(str(msg))
except Exception:
pass
def save_reward_pic(device_id):
try:
from douyin.core import path_config
out_dir = path_config.get_pic_dir()
except Exception:
from douyin.core import path_config
out_dir = path_config.get_pic_dir()
if not os.path.exists(out_dir):
os.makedirs(out_dir)
timepic = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
out_file = os.path.join(out_dir, f"{timepic}.png")
adb = _adb_path()
# 同样优先使用 exec-out,减少手机端 I/O
try:
with open(out_file, "wb") as f:
subprocess.run(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=f,
stderr=subprocess.DEVNULL,
check=True,
)
_uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
return
except Exception:
pass
# 回退:shell screencap + pull
try:
subprocess.run(
[
adb,
"-s",
device_id,
"shell",
"screencap",
"-p",
"/sdcard/DCIM/screenshot.png",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
subprocess.run(
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", out_file],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
subprocess.run(
[adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
_uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
except Exception:
# 保存失败不打断主流程
_uo_log("保存中奖截图失败")
@@ -0,0 +1,49 @@
"""underlying_operations_pkg.swipe_sendevent - sendevent 滑动(占位实现)。
_swipe_with_sendevent_improved(...) 是更底层的触摸事件模拟方式,需要 root 权限
且不同设备的事件格式可能不同。当前实现只做检测和异常抛出,主流程不依赖它。
"""
from __future__ import annotations
import subprocess
from .adb_helpers import _adb_args
def _swipe_with_sendevent_improved(device_id, x1, y1, x2, y2, steps=50):
"""使用 sendevent 方法滑动(需要 root 权限)
这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。
优点:绕过部分权限检查
缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同
"""
# 获取触摸设备路径(通常是 /dev/input/eventX)
result = subprocess.run(
_adb_args(device_id, "shell", "getevent", "-p"),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
timeout=3.0,
check=False,
)
# 解析设备路径(简化版,实际需要更复杂的解析)
# 这里只是示例,完整实现需要:
# 1. 解析 getevent -p 输出找到触摸设备
# 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max)
# 3. 将屏幕坐标转换为设备坐标
# 4. 发送 DOWN -> MOVE -> UP 事件序列
if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower():
raise FileNotFoundError("无法找到触摸设备(需要 root 权限)")
# 注意:完整的 sendevent 实现非常复杂,需要:
# - 设备特定的坐标转换
# - 正确的事件序列(SYN_REPORT 等)
# - 不同 Android 版本的事件格式可能不同
raise PermissionError("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
File renamed without changes.
-20
View File
@@ -1,20 +0,0 @@
"""检测核心模块
本目录包含从 douyin_detection.py 模块化后的检测功能。
"""
# 临时导入:从原文件导入,后续会逐步迁移
# TODO: 迁移完成后改为从子模块导入
from ...detection.douyin_detection import (
_ensure_detection_cache,
check_detail_height,
check_have_fudai_with_ready_screenshot,
check_in_fudai_detail,
)
__all__ = [
"_ensure_detection_cache",
"check_detail_height",
"check_have_fudai_with_ready_screenshot",
"check_in_fudai_detail",
]
@@ -0,0 +1,23 @@
"""detection_pkg - 福袋检测子包。
原 douyin/detection/douyin_detection.py 拆成 3 个子模块:
- _common _ensure_detection_cache
- detail check_detail_height / check_in_fudai_detail
- finder check_have_fudai_with_ready_screenshot(最大头)
外部 import 路径不变:
``from douyin.detection.douyin_detection import check_in_fudai_detail`` 仍可用
(原文件改成 re-export shim)。
"""
from ._common import _ensure_detection_cache
from .detail import check_detail_height, check_in_fudai_detail
from .finder import check_have_fudai_with_ready_screenshot
__all__ = [
"_ensure_detection_cache",
"check_detail_height",
"check_have_fudai_with_ready_screenshot",
"check_in_fudai_detail",
]
+14
View File
@@ -0,0 +1,14 @@
"""detection_pkg._common - 共享:分析器检测缓存初始化。"""
from __future__ import annotations
from typing import Any
def _ensure_detection_cache(analyser: Any) -> None:
"""Ensure analyser has a simple detection cache structure."""
if not hasattr(analyser, "_detection_cache"):
analyser._detection_cache = {}
if not hasattr(analyser, "_detection_cache_ttl"):
analyser._detection_cache_ttl = 2.0
+323
View File
@@ -0,0 +1,323 @@
"""detection_pkg.detail - 福袋详情页相关检测。
- check_detail_height 识别详情页弹窗中"任务"数量(0/1/2/3)
- check_in_fudai_detail 判断当前是否处于福袋详情页(综合多种特征)
"""
from __future__ import annotations
# pylint: disable=no-member
import os
import time
from typing import Any
from PIL import Image
from ._common import _ensure_detection_cache
def check_detail_height(analyser: Any) -> int:
"""Detect how many tasks are required in the fudai detail popup.
Returns:
0 / 1 / 2 / 3 (number of tasks).
"""
# 使用统一的截图路径配置
try:
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
# 记录截图文件的时间戳(如果存在)
screenshot_timestamp = None
try:
if os.path.exists(pic1_path):
screenshot_timestamp = os.path.getmtime(pic1_path)
except Exception:
pass
pic = None
for attempt in range(3):
try:
pic = Image.open(pic1_path)
pic.load() # force load to catch truncated files early
break
except Exception:
if attempt < 2:
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
analyser.operation.delay(0.2)
# 重新获取截图后,更新时间戳
try:
if os.path.exists(pic1_path):
screenshot_timestamp = os.path.getmtime(pic1_path)
except Exception:
pass
except Exception:
pass
pic = None
if pic is None:
try:
analyser._log_kv(
"检测",
"读取截图失败,默认不需要任务",
level="WARN",
screenshot_timestamp=screenshot_timestamp,
)
except Exception:
pass
return 0
pic_new = pic.convert("RGBA")
pix = pic_new.load()
width, height = pic_new.size
# X of “参与” button
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
x = 536 * rx // 1080
if not (0 <= x < width):
return 0
# (base_y, y_pianyi_offset, task_count)
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
check_points = [
(983, 0, 2),
(983, y_pianyi_val, 2),
(983, -y_pianyi_val, 2),
(883, 0, 3),
(883, y_pianyi_val, 3),
(883, -y_pianyi_val, 3),
(1058, 0, 1),
(1058, y_pianyi_val, 1),
(1058, -y_pianyi_val, 1),
]
def _check_pixel_color(y_coord: int) -> bool:
if not (0 <= y_coord < height):
return False
try:
p = pix[x, y_coord]
if not (isinstance(p, tuple) and len(p) >= 3):
return False
r, g, b = int(p[0]), int(p[1]), int(p[2])
return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86
except Exception:
return False
detected_task_count = None
detected_y = None
try:
for base_y, dy, task_count in check_points:
y = base_y * ry // 2400 + dy
if _check_pixel_color(y):
detected_task_count = task_count
detected_y = y
try:
import time
current_time = time.time()
analyser._log_kv(
"检测",
f"识别到福袋任务数量:{task_count}个",
task_count=task_count,
detected_y=detected_y,
screenshot_timestamp=screenshot_timestamp,
current_time=current_time,
time_diff=(
round(current_time - screenshot_timestamp, 3)
if screenshot_timestamp
else None
),
)
except Exception:
pass
break
except Exception:
pass
# 保存调试图片:标注检测区域和检测点
try:
from douyin.handlers import douyin_screenshot_manager
# 计算检测区域(参与按钮附近的区域)
check_region_x1 = max(0, x - 50)
check_region_x2 = min(width, x + 50)
check_region_y1 = max(0, (883 * ry // 2400) - 100) # 3个任务的Y坐标附近
check_region_y2 = min(height, (1058 * ry // 2400) + 100) # 1个任务的Y坐标附近
# 标注检测点
coords_list = []
for base_y, dy, task_count_val in check_points:
check_y = base_y * ry // 2400 + dy
if 0 <= check_y < height:
# 标注检测点(小矩形区域)
coords_list.append(
(
max(0, x - 10),
max(0, check_y - 5),
min(width, x + 10),
min(height, check_y + 5),
)
)
# 保存调试图片
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="detection",
picname="福袋任务数量",
step="task_count_detection",
coords=(check_region_x1, check_region_y1, check_region_x2, check_region_y2),
extra_info={
"task_count": (
detected_task_count if detected_task_count is not None else 0
),
"detected_y": detected_y,
"check_x": x,
"check_points_count": len(check_points),
"region": f"({check_region_x1},{check_region_y1})-({check_region_x2},{check_region_y2})",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋任务数量检测",
path=debug_path,
task_count=(
detected_task_count if detected_task_count is not None else 0
),
)
except Exception:
pass
except Exception:
pass
if detected_task_count is not None:
return detected_task_count
# Optional robot-check path from original implementation
try:
if (
hasattr(analyser, "check_have_robot_analyse")
and analyser.check_have_robot_analyse()
):
analyser.deal_robot_analyse()
except Exception:
pass
try:
import time
current_time = time.time()
analyser._log_kv(
"检测",
"识别福袋任务数量:0个(不需要任务)",
level="INFO",
task_count=0,
screenshot_timestamp=screenshot_timestamp,
current_time=current_time,
time_diff=(
current_time - screenshot_timestamp if screenshot_timestamp else None
),
)
except Exception:
pass
return 0
def check_in_fudai_detail(analyser: Any) -> bool:
"""Detect whether we are currently on the fudai detail page.
使用模板匹配检测,与 detect_fudai_detail_page 保持一致。
"""
_ensure_detection_cache(analyser)
cache_key = "check_in_fudai_detail"
now = time.time()
cached = analyser._detection_cache.get(cache_key)
if cached:
cached_ts, cached_result = cached
ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0)
if (now - cached_ts) < ttl:
return bool(cached_result)
# 使用模板匹配检测,与 detect_fudai_detail_page 保持一致
try:
from douyin.detection import douyin_pixel
from douyin.core import path_config
# 获取截图
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
analyser._detection_cache[cache_key] = (now, False)
return False
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
analyser._detection_cache[cache_key] = (now, False)
return False
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
# 获取分辨率比例和Y偏移
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
template_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
if template_threshold < 0.0:
template_threshold = 0.0
if template_threshold > 1.0:
template_threshold = 1.0
# 使用任务数量检测
result = douyin_pixel.detect_fudai_detail_page(
pic_rgb,
rx,
ry,
y_pianyi,
template_threshold,
return_info=False, # 不需要详细信息
analyser=analyser,
)
is_in_detail = bool(result)
analyser._detection_cache[cache_key] = (now, is_in_detail)
return is_in_detail
except Exception:
analyser._detection_cache[cache_key] = (now, False)
return False
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
# 像素检测代码已删除,使用模板匹配替代
# 如需恢复像素检测,请参考 git 历史记录
+320
View File
@@ -0,0 +1,320 @@
"""detection_pkg.finder - 找福袋图标主入口(1420 行)。
包含 check_have_fudai_with_ready_screenshot:在直播间内通过模板匹配
定位福袋图标,并把找到的位置写到 analyser 上供后续点击使用。
"""
from __future__ import annotations
# pylint: disable=no-member
import os
import time
from typing import Any
from PIL import Image
from ._common import _ensure_detection_cache
def check_have_fudai_with_ready_screenshot(
analyser: Any, screenshot_ready: bool = False
):
"""判定直播页面福袋的小图标是否存在(优化版,优先使用模块化查找器)。
如果启用了优化查找器(fudai_finder_optimized_enabled=True),则使用新的模块化查找器。
否则使用原版像素检测实现。
"""
# 检查是否启用优化查找器
try:
use_optimized = bool(getattr(analyser, "fudai_finder_optimized_enabled", False))
except Exception:
use_optimized = False
if use_optimized:
try:
from douyin.fudai.douyin_fudai_finder import (
check_have_fudai_with_ready_screenshot_optimized,
)
return check_have_fudai_with_ready_screenshot_optimized(
analyser, screenshot_ready
)
except ImportError:
# 优化版不可用,回退到原版
try:
analyser._log_kv(
"[找福袋图标]", "优化查找器不可用,使用原版", error="ImportError"
)
except Exception:
pass
except Exception as e:
# 优化版异常,回退到原版
try:
analyser._log_kv(
"[找福袋图标]",
"优化查找器异常,使用原版",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 原版实现(像素检测版)
func_start = time.time()
# 使用统一的截图路径配置
try:
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
attempt_count = 0 # 仅用于日志记录,不影响循环控制
# ===== 像素检测版(优先使用),不依赖 OpenCV =====
# 改为按时间控制循环,而不是按次数限制
try:
retry_delay_s = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
except Exception:
retry_delay_s = 0.6
try:
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0)
except Exception:
max_wait_s = 5.0
if retry_delay_s < 0.1:
retry_delay_s = 0.1 # 最小间隔改为0.1秒
if max_wait_s < 0:
max_wait_s = 0.0
# 防止无限等待:最大等待时间限制为30秒
if max_wait_s > 30.0:
max_wait_s = 30.0
loop = 0
max_loops = int(max_wait_s / retry_delay_s) + 10 # 额外的循环次数保护
consecutive_failures = 0 # 连续失败计数
max_consecutive_failures = 5 # 最大连续失败次数
# 额外的时间限制保护,防止死循环
absolute_timeout = func_start + max(
max_wait_s * 1.5, 15
) # 最长15秒,但不超过 max_wait_s * 1.5
while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout:
# 额外的循环次数保护:防止无限循环
if loop >= max_loops:
try:
analyser._log_kv(
"[找福袋图标] 警告",
"达到最大循环次数限制,提前退出",
max_loops=max_loops,
elapsed_s=round(time.time() - func_start, 2),
)
except Exception:
pass
break
# 每次循环都重新截图(除了第一次如果已经提供了截图)
from douyin.detection.detection_pkg.finder_screenshot import (
capture_screenshot_for_loop,
handle_screenshot_load_failure,
load_screenshot_with_retry,
)
capture_screenshot_for_loop(analyser, screenshot_ready, loop, pic1_path)
# 读取截图
pic = load_screenshot_with_retry(analyser, pic1_path)
# 如果截图读取失败,等待后继续下一次循环
if pic is None:
loop += 1
consecutive_failures += 1
action = handle_screenshot_load_failure(
analyser,
consecutive_failures,
max_consecutive_failures,
func_start,
max_wait_s,
retry_delay_s,
)
if action == "break":
break
continue
pic_new = pic.convert("RGBA")
width, height = pic_new.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
detected = False
detected_x = None
# 初始化扫描范围变量(用于日志记录)
scan_x_start = 41 * rx // 1080
scan_x_end = min(410 * rx // 1080, 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 <= 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))
# 保存完整截图用于调试(检测前)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb_full = pic_new.convert("RGB")
# 保存完整截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="before_detect",
coords=(
(scan_x_start, scan_y - 3, scan_x_end, scan_y + 4)
if scan_y >= 3
else None
),
extra_info={
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"resolution": f"{rx}x{ry}",
"y_offset": y_pianyi_val,
"loop": loop,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]", "福袋图标检测前保存完整截图", path=debug_path
)
except Exception:
pass
except Exception:
pass
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
from douyin.detection.detection_pkg.finder_numpy_scan import (
numpy_band_scan,
)
detected, detected_x = numpy_band_scan(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, optimal_x_scaled,
)
# numpy 未命中/不可用时回退到原始逐像素检查
from douyin.detection.detection_pkg.finder_pixel_scan import (
pixel_scan_fallback,
)
detected, detected_x = pixel_scan_fallback(
analyser, detected, detected_x, pic_new, rx, ry, y_pianyi_val,
)
if detected:
break # 找到后退出外层 while 循环
# 像素检测未命中时,使用模板匹配作为兜底
from douyin.detection.detection_pkg.finder_template_match import (
template_match_fallback,
)
detected, detected_x = template_match_fallback(
analyser, detected, detected_x, pic_new,
width, height, rx, ry, y_pianyi_val, loop,
)
if detected and detected_x is not None:
# 重置连续失败计数
consecutive_failures = 0
# 记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
from douyin.detection.detection_pkg.finder_loop_logging import (
log_fudai_found_and_metrics,
)
log_fudai_found_and_metrics(
analyser, detected_x, func_start, loop, ry, y_pianyi_val
)
return int(detected_x or 0)
loop += 1
consecutive_failures += 1
# 如果连续失败太多次,提前退出(避免无效循环)
if consecutive_failures >= max_consecutive_failures:
try:
elapsed_ms = int((time.time() - func_start) * 1000)
analyser._log_kv(
"[找福袋图标] 警告",
"连续检测失败次数过多,提前退出",
consecutive_failures=consecutive_failures,
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y,
)
except Exception:
pass
break
# 每轮记录一次轻量调试信息(每 3 次循环一次,减少日志量)
from douyin.detection.detection_pkg.finder_loop_logging import (
log_loop_progress,
)
log_loop_progress(
analyser, loop, func_start, pic_new, width, height,
scan_x_start, scan_x_end, scan_y, consecutive_failures,
)
# 检查是否还有剩余时间
elapsed = time.time() - func_start
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)
else:
# 时间已到,退出循环
break
# 像素检测未找到时,返回 False,并记录总耗时与循环次数
from douyin.detection.detection_pkg.finder_loop_logging import (
log_no_fudai_found,
)
log_no_fudai_found(analyser, func_start, loop, max_wait_s, retry_delay_s)
return False
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
# 像素检测代码已删除,使用模板匹配替代
# 如需恢复像素检测,请参考 git 历史记录
@@ -0,0 +1,131 @@
"""find_fudai 辅助:循环中的调试日志
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
- log_fudai_found_and_metrics:命中福袋后记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
- log_loop_progress:每 3 次循环记录一次轻量调试信息
- log_no_fudai_found:未找到时记录总耗时与循环次数
"""
from __future__ import annotations
import time
from typing import Any
def log_fudai_found_and_metrics(
analyser: Any,
detected_x,
func_start: float,
loop: int,
ry: int,
y_pianyi_val: int,
) -> None:
"""命中福袋后:记录"进入直播间→找到福袋"耗时统计 + 命中调试信息。"""
# 统计:每次"进入直播间"后首次找到福袋图标耗时
try:
enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0)
except Exception:
enter_ts = 0.0
try:
already = bool(getattr(analyser, "_enter_live_fudai_logged", False))
except Exception:
already = False
if (enter_ts > 0) and (not already):
try:
dt = float(time.time() - enter_ts)
except Exception:
dt = -1.0
if dt >= 0:
try:
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
except Exception:
reason = ""
try:
analyser._enter_live_fudai_logged = True
except Exception:
pass
try:
analyser._log_kv(
"性能",
"进入直播间后找到福袋耗时",
seconds=round(dt, 2),
enter_reason=reason,
fudai_x=int(detected_x or 0),
)
except Exception:
pass
# 命中时记录调试信息
try:
elapsed_ms = int((time.time() - func_start) * 1000)
scan_y_for_log = 403 * ry // 2400 + y_pianyi_val
analyser._log_kv(
"[找福袋图标] 命中",
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y_for_log,
x=detected_x,
)
except Exception:
pass
def log_loop_progress(
analyser: Any,
loop: int,
func_start: float,
pic_new,
width: int,
height: int,
scan_x_start: int,
scan_x_end: int,
scan_y: int,
consecutive_failures: int,
) -> None:
"""每 3 次循环记录一次轻量调试信息(帮助诊断为何未命中)。"""
if loop % 3 != 0:
return
try:
elapsed_ms = int((time.time() - func_start) * 1000)
sample_color = None
try:
mid_x = (scan_x_start + scan_x_end) // 2
if 0 <= scan_y < height and 0 <= mid_x < width:
pix_sample = pic_new.load()
sample_color = pix_sample[mid_x, scan_y]
except Exception:
sample_color = None
analyser._log_kv(
"[找福袋图标] 循环中",
loop=loop,
elapsed_ms=elapsed_ms,
scan_y=scan_y,
scan_x_start=scan_x_start,
scan_x_end=scan_x_end,
sample_color=(
str(sample_color) if sample_color is not None else "None"
),
consecutive_failures=consecutive_failures,
)
except Exception:
pass
def log_no_fudai_found(
analyser: Any,
func_start: float,
loop: int,
max_wait_s: float,
retry_delay_s: float,
) -> None:
"""像素检测未找到时记录总耗时与循环次数。"""
try:
total_elapsed_ms = int((time.time() - func_start) * 1000)
analyser._log_kv(
"[找福袋图标] 未找到福袋图标",
elapsed_ms=total_elapsed_ms,
total_loops=loop,
max_wait_s=max_wait_s,
retry_delay_s=retry_delay_s,
)
except Exception:
pass
@@ -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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+40
View File
@@ -0,0 +1,40 @@
"""pixel - 像素 / 模板匹配检测子包。
原 douyin/detection/douyin_pixel.py 拆成 4 个子模块:
- _common 共享:_safe_open_screenshot_rgb
- popups 弹窗类检测:优惠券 / 红包 / 抽奖结果
- buttons 按钮区域红色检测:参与按钮 / 粉丝团加入
- stage 阶段诊断:直播间图标 / 福袋详情页 / 综合阶段状态读取
外部 import 路径不变:
``from douyin.detection.douyin_pixel import detect_fudai_detail_page`` 仍可用。
"""
from ._common import _safe_open_screenshot_rgb
from .popups import (
detect_coupon_popup_background,
detect_redpacket_popup_background,
detect_lucky_draw_result_popup,
)
from .buttons import (
detect_attend_button_red_area,
detect_fansclub_join_red_area,
)
from .stage import (
detect_live_room_icons_by_pixel,
detect_fudai_detail_page,
read_pixel_stage_state_from_screenshot,
)
__all__ = [
"_safe_open_screenshot_rgb",
"detect_coupon_popup_background",
"detect_redpacket_popup_background",
"detect_lucky_draw_result_popup",
"detect_attend_button_red_area",
"detect_fansclub_join_red_area",
"detect_live_room_icons_by_pixel",
"detect_fudai_detail_page",
"read_pixel_stage_state_from_screenshot",
]
+32
View File
@@ -0,0 +1,32 @@
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
# pyright: reportUnknownMemberType=false
# pyright: reportUnknownVariableType=false
# pylint: disable=no-member
"""pixel._common - 共享工具函数。
只包含 _safe_open_screenshot_rgb:安全打开截图为 RGB Image,
处理 truncated/损坏文件。被 popups / buttons / stage 子模块共用。
"""
import os
from typing import Any, Optional
from PIL import Image
def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
try:
if not pic_path or (not os.path.exists(pic_path)):
return None
pic = Image.open(pic_path)
pic.load() # Force load to catch truncated files early
return pic.convert("RGB")
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return None
except Exception as e: # type: ignore[general-exception]
return None
+340
View File
@@ -0,0 +1,340 @@
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
# pyright: reportUnknownMemberType=false
# pyright: reportUnknownVariableType=false
# pylint: disable=no-member
"""pixel.buttons - 按钮区域的红色检测。
- detect_attend_button_red_area 福袋详情页"参与抽奖"按钮
- detect_fansclub_join_red_area 粉丝团加入按钮
"""
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
from PIL import Image
from ._common import _safe_open_screenshot_rgb
def detect_attend_button_red_area(
pic_rgb: Image.Image,
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测参与按钮:大片红色区域。
参与按钮通常在屏幕底部,有大片红色背景。
检测区域:(306,2030)-(780,2110) 基准1080x2400,但实际可能更宽
扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮
"""
try:
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮)
x1 = int(200 * scale_x) # 扩展左侧
y1 = int(2000 * scale_y) # 稍微上移
x2 = int(880 * scale_x) # 扩展右侧
y2 = int(2120 * scale_y) # 稍微下移
# 确保坐标在范围内
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
return False
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path)
except Exception: # type: ignore[general-exception]
pass
except Exception: # type: ignore[general-exception]
pass
# 采样检测点:检测大片红色区域
red_count = 0
step_x = max(1, (x2 - x1) // 15)
step_y = max(1, (y2 - y1) // 10)
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
except Exception as e: # type: ignore[general-exception]
continue
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(
list(range(x1, x2, step_x))
)
if total_samples == 0:
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
if red_ratio_threshold is not None:
threshold = float(red_ratio_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "attend_button_red_ratio_threshold", 0.25) or 0.25
)
except Exception as e: # type: ignore[general-exception]
threshold = 0.25
else:
threshold = 0.25
result = red_ratio >= threshold
# 如果请求详细信息,返回包含red_ratio的字典
if return_info:
reason_value: Optional[str] = (
None if result else "red_ratio_below_threshold"
)
return result, {
"method": "pixel_detect",
"red_ratio": red_ratio,
"red_count": red_count,
"total_samples": total_samples,
"effective_threshold": threshold,
"reason": reason_value,
}
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
# 无论成功失败都保存debug截图
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
return result
except Exception:
if return_info:
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "exception",
}
return False
def detect_fansclub_join_red_area(
pic_rgb: Image.Image,
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测粉丝团加入:大片红色区域。
粉丝团加入按钮通常在屏幕中下部,有大片红色背景。
检测区域:(200,1940)-(880,2140) 基准1080x2400
"""
try:
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400)
x1 = int(200 * scale_x)
y1 = int(1940 * scale_y)
x2 = int(880 * scale_x)
y2 = int(2140 * scale_y)
# 确保坐标在范围内
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
if return_info:
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "invalid_region",
}
return False
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 粉丝团加入检测前保存: %s",
debug_path,
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
# 采样检测点:检测大片红色区域
red_count = 0
step_x = max(1, (x2 - x1) // 15)
step_y = max(1, (y2 - y1) // 10)
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
except Exception:
continue
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(
list(range(x1, x2, step_x))
)
if total_samples == 0:
if return_info:
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "no_samples",
}
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
if red_ratio_threshold is not None:
threshold = float(red_ratio_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25
)
except Exception as e: # type: ignore[general-exception]
threshold = 0.25
else:
threshold = 0.25
result = red_ratio >= threshold
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
if return_info:
reason_value: Optional[str] = (
None if result else "red_ratio_below_threshold"
)
return result, {
"method": "pixel_detect",
"red_ratio": red_ratio,
"red_count": red_count,
"total_samples": total_samples,
"effective_threshold": threshold,
"reason": reason_value,
}
return result
except Exception:
if return_info:
return False, {
"method": "pixel_detect",
"red_ratio": None,
"reason": "exception",
}
return False
+444
View File
@@ -0,0 +1,444 @@
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
# pyright: reportUnknownMemberType=false
# pyright: reportUnknownVariableType=false
# pylint: disable=no-member
"""pixel.popups - 弹窗类像素 / 模板检测。
- detect_coupon_popup_background 优惠券大弹窗
- detect_redpacket_popup_background 购物红包大弹窗
- detect_lucky_draw_result_popup 抽奖结果弹窗
"""
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
from PIL import Image
from ._common import _safe_open_screenshot_rgb
def detect_coupon_popup_background(
pic_rgb: Image.Image,
return_info: bool = False,
template_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测底部优惠券大弹窗(仅模板匹配)。
模板匹配区域(基于1080x2400基准):
- 左上: (9, 1173)
- 右下: (1079, 2255)
使用 `assets/coupon.png` 作为模板。
参数:
pic_rgb: RGB格式的整屏截图
return_info: 是否返回详细信息(包含检测分数)
template_threshold: 模板匹配阈值(默认0.75,如果提供则使用,否则从analyser读取)
analyser: analyser对象,用于读取配置阈值
返回:
bool: 是否检测到优惠券背景(return_info=False时)
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
"""
try:
try:
import cv2 # type: ignore[import-untyped]
import numpy as np # type: ignore[import-untyped]
except Exception as e: # type: ignore[general-exception]
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": "opencv_unavailable",
}
return False
width, height = pic_rgb.size
scale_x = width / 1080.0
scale_y = height / 2400.0
x1 = int(9 * scale_x)
y1 = int(1173 * scale_y)
x2 = int(1079 * scale_x)
y2 = int(2255 * scale_y)
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": "invalid_region",
}
return False
bgr = cv2.cvtColor( # type: ignore[attr-defined]
np.asarray(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined]
)
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
if roi.size == 0:
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": "empty_roi",
}
return False
# 使用统一的模板路径配置
try:
from douyin.core import path_config
template_path = path_config.get_assets_dir() + "/coupon.png"
except Exception:
# 回退到旧路径(向后兼容)
base_dir = os.path.dirname(__file__)
template_path = os.path.join(base_dir, "assets", "coupon.png")
if not os.path.exists(template_path):
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": "template_not_found",
}
return False
template = cv2.imread( # type: ignore[attr-defined,assignment]
template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined]
)
if template is None:
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": "template_load_failed",
}
return False
if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]:
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": "template_too_large",
}
return False
res = cv2.matchTemplate( # type: ignore[attr-defined]
roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
)
_, max_val, _, _ = cv2.minMaxLoc(res) # type: ignore[attr-defined]
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
if template_threshold is not None:
threshold = float(template_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75
)
except Exception as e: # type: ignore[general-exception]
threshold = 0.75
else:
threshold = 0.75
result = max_val >= threshold
if return_info:
reason_value: Optional[str] = None if result else "score_below_threshold"
return result, {
"method": "template_match",
"template_score": float(max_val),
"effective_threshold": threshold,
"reason": reason_value,
}
return result
except Exception as e: # type: ignore[general-exception]
if return_info:
return False, {
"method": "template_match",
"template_score": None,
"reason": f"exception: {str(e)}",
}
return False
def detect_redpacket_popup_background(
pic_rgb: Image.Image,
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""中央购物红包弹窗检测:检测中央大红包区域的红色占比。
购物红包特征:
- 中央大型红色弹窗
- 包含黄色圆形"抢"按钮
- 主要颜色为红色(RGB约 255, 100-150, 100-150)
检测区域(基准1080x2400):大约中央区域
- 左上:(300, 400)
- 右下:(780, 1200)
参数:
pic_rgb: RGB格式的整屏截图
return_info: 是否返回详细信息(包含红色比例)
red_ratio_threshold: 红色占比阈值(默认0.15,若提供则使用)
analyser: analyser对象,用于读取配置阈值
返回:
bool: 是否检测到购物红包背景(return_info=False时)
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
"""
try:
import numpy as np # type: ignore[import-untyped]
width, height = pic_rgb.size
scale_x = width / 1080.0
scale_y = height / 2400.0
# 购物红包通常出现在屏幕中央
# 基准坐标(1080x2400)
x1 = int(200 * scale_x)
y1 = int(300 * scale_y)
x2 = int(880 * scale_x)
y2 = int(1400 * scale_y)
# 边界检查
x1 = max(0, min(x1, width))
x2 = max(0, min(x2, width))
y1 = max(0, min(y1, height))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
if return_info:
return False, {
"method": "pixel_detection",
"red_ratio": 0.0,
"reason": "invalid_region",
}
return False
# 裁剪感兴趣区域
roi = pic_rgb.crop((x1, y1, x2, y2))
arr = np.asarray(roi)
if arr.size == 0:
if return_info:
return False, {
"method": "pixel_detection",
"red_ratio": 0.0,
"reason": "empty_roi",
}
return False
# 提取RGB通道
r = arr[:, :, 0] # type: ignore[index]
g = arr[:, :, 1] # type: ignore[index]
b = arr[:, :, 2] # type: ignore[index]
# 红色特征:R > 200, G < 180, B < 180
# 购物红包的红色通常很纯,R值很高
mask = (r >= 220) & (g <= 160) & (b <= 160)
# 计算红色像素占比
total_pixels = mask.size
red_pixels = np.sum(mask) # type: ignore[call-overload]
red_ratio = red_pixels / total_pixels if total_pixels > 0 else 0
# 阈值:至少15%的像素满足红色特征
if red_ratio_threshold is not None:
threshold = float(red_ratio_threshold)
elif analyser is not None:
try:
threshold = float(
getattr(analyser, "shopping_redpacket_red_ratio_threshold", 0.15)
or 0.15
)
except Exception as e: # type: ignore[general-exception]
threshold = 0.15
else:
threshold = 0.15
result = bool(red_ratio > threshold)
if return_info:
reason_value: Optional[str] = (
None if result else "red_ratio_below_threshold"
)
return result, {
"method": "pixel_detection",
"red_ratio": float(red_ratio),
"effective_threshold": threshold,
"reason": reason_value,
}
return result
except Exception as e: # type: ignore[general-exception]
if return_info:
return False, {
"method": "pixel_detection",
"red_ratio": 0.0,
"reason": f"exception: {str(e)}",
}
return False
def detect_lucky_draw_result_popup(
pic_rgb: Image.Image, red_ratio_threshold: float = 0.8, return_info: bool = False
) -> bool | tuple[bool, dict]:
"""检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。
使用基准 1080x2400 坐标的检测区域:
- 左上: (181, 1261)
- 右下: (890, 1389)
"""
try:
width, height = pic_rgb.size
scale_x = width / 1080.0
scale_y = height / 2400.0
x1 = int(181 * scale_x)
y1 = int(1261 * scale_y)
x2 = int(890 * scale_x)
y2 = int(1389 * scale_y)
# 边界与顺序
x1, x2 = max(0, min(x1, width)), max(0, min(x2, width))
y1, y2 = max(0, min(y1, height)), max(0, min(y2, height))
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
if x1 >= x2 or y1 >= y2:
return False
# 双截图记录:保存实时操作截图(像素检测区域)
detect_roi = None
try:
from douyin.handlers import douyin_screenshot_manager
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"threshold": red_ratio_threshold,
"region_size": f"{x2-x1}x{y2-y1}",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 像素检测前保存: %s, threshold=%s",
debug_path,
red_ratio_threshold,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
red_count = 0
total_samples = 0
step_x = max(1, (x2 - x1) // 10)
step_y = max(1, (y2 - y1) // 10)
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
total_samples += 1
# 根据实际检测结果:R: 245-255, G: 44-255, B: 85-255
# 红色按钮检测:R >= 245 且 R 明显大于 G 和 B
if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50:
red_count += 1
except Exception as e: # type: ignore[general-exception]
continue
if total_samples == 0:
return False
red_ratio = red_count / total_samples
result = red_ratio >= red_ratio_threshold
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if result:
# 检测成功
if detect_roi is None:
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": red_ratio_threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
debug_path,
red_ratio,
red_ratio_threshold,
red_ratio,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
# 如果请求详细信息,返回包含red_ratio的字典
if return_info:
reason_value: Optional[str] = (
None if result else "red_ratio_below_threshold"
)
return result, {
"method": "pixel_detect",
"red_ratio": red_ratio,
"red_count": red_count,
"total_samples": total_samples,
"effective_threshold": red_ratio_threshold,
"reason": reason_value,
}
return result
except Exception as e: # type: ignore[general-exception]
return False
+436
View File
@@ -0,0 +1,436 @@
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
# pyright: reportUnknownMemberType=false
# pyright: reportUnknownVariableType=false
# pylint: disable=no-member
"""pixel.stage - 阶段诊断相关像素检测。
- detect_live_room_icons_by_pixel 直播间图标检测
- detect_fudai_detail_page 福袋详情页识别
- read_pixel_stage_state_from_screenshot 综合多种检测,返回阶段状态
"""
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
from PIL import Image
from ._common import _safe_open_screenshot_rgb
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
"""通过像素检测多边形区域内的白色像素,判断是否在直播间。
检测指定多边形区域内的白色像素比例,基于1080x2400分辨率:
- 多边形顶点坐标(12个点):
(1002,172), (999,174), (1011,186), (999,199), (1002,202), (1013,190),
(1025,201), (1028,198), (1017,187), (1028,174), (1025,172), (1014,184)
- 白色像素比例 >= 0.8 则认为在直播间内
返回:
(detected, confidence) 其中 confidence 为白色像素比例(0.0~1.0)
"""
try:
from PIL import ImageDraw
import numpy as np
width, height = pic_rgb.size
# 缩放坐标到实际尺寸(基于1080x2400)
scale_x = width / 1080.0
scale_y = height / 2400.0
# 多边形顶点坐标(基于1080x2400基准分辨率)
polygon_base_points = [
(1002, 172),
(999, 174),
(1011, 186),
(999, 199),
(1002, 202),
(1013, 190),
(1025, 201),
(1028, 198),
(1017, 187),
(1028, 174),
(1025, 172),
(1014, 184),
]
# 缩放多边形坐标到实际截图尺寸
polygon_points = [
(int(x * scale_x), int(y * scale_y)) for x, y in polygon_base_points
]
# 创建多边形mask
mask = Image.new("L", (width, height), 0)
draw = ImageDraw.Draw(mask)
# 绘制多边形(填充为白色)
draw.polygon(polygon_points, fill=255)
# 将mask转换为numpy数组
mask_array = np.asarray(mask)
# 获取原始图像的像素数据
img_array = np.asarray(pic_rgb)
# 计算多边形内部的总像素数
total_pixels = np.sum(mask_array > 0)
if total_pixels == 0:
return False, 0.0
# 计算多边形内部的白色像素(RGB值都>=240)——使用 numpy 向量化计算以加速
# mask_array 为 uint8,mask_bool 为布尔数组
mask_bool = mask_array > 0
# 将 img_array 转为 numpy 数组并选择掩膜区域内的像素,shape -> (N, 3)
masked_pixels = img_array[mask_bool]
if masked_pixels.size == 0:
white_count = 0
else:
# 检查 RGB 三通道是否都 >= 240
white_flags = (
(masked_pixels[:, 0] >= 240)
& (masked_pixels[:, 1] >= 240)
& (masked_pixels[:, 2] >= 240)
)
white_count = int(np.count_nonzero(white_flags))
white_ratio = white_count / total_pixels if total_pixels > 0 else 0.0
# 白色像素比例 >= 0.8 则认为在直播间内
detected = white_ratio >= 0.8
confidence = white_ratio # 置信度就是白色比例
# 计算多边形边界框(用于调试图像)
if polygon_points:
x_coords = [p[0] for p in polygon_points]
y_coords = [p[1] for p in polygon_points]
x1 = max(0, min(x_coords))
y1 = max(0, min(y_coords))
x2 = min(width, max(x_coords))
y2 = min(height, max(y_coords))
else:
x1, y1, x2, y2 = 0, 0, 0, 0
# 保存调试图像(检测结果)
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="live_room_icons",
step="detected" if detected else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域边界框
extra_info={
"white_ratio": round(white_ratio, 4),
"white_count": white_count,
"total_pixels": total_pixels,
"confidence": round(confidence, 4),
"threshold": 0.8,
"result": "success" if detected else "failed",
"polygon_points": len(polygon_points),
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
debug_path,
white_ratio,
white_count,
total_pixels,
confidence,
"success" if detected else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
return bool(detected), float(confidence)
except Exception as e: # type: ignore[general-exception]
return False, 0.0
def detect_fudai_detail_page(
_pic_rgb: Image.Image,
_resolution_ratio_x: int = 1080,
_resolution_ratio_y: int = 2400,
_y_pianyi: int = 0,
_template_threshold: float = 0.7,
return_info: bool = False,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测是否处于福袋详情页。
检测策略:任务数量检测
1. 通过检测任务数量来判断是否在福袋详情页
2. 如果任务数量 <= 0,则认为不在福袋详情页
3. 如果任务数量 >= 1,则认为在福袋详情页,并返回任务数量
参数:
pic_rgb: RGB格式的整屏截图(保留用于兼容性,实际不使用)
resolution_ratio_x: 分辨率X比例(默认1080,保留用于兼容性)
resolution_ratio_y: 分辨率Y比例(默认2400,保留用于兼容性)
y_pianyi: Y轴偏移(默认0,保留用于兼容性)
template_threshold: 模板匹配阈值(保留用于兼容性,不再使用)
return_info: 是否返回详细信息(包含任务数量)
analyser: 分析器对象(必需,用于任务数量检测)
返回:
bool: 是否检测到福袋详情页(return_info=False时)
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
详细信息包含:
- method: 检测方法("task_count")
- task_count: 任务数量(0/1/2/3)
"""
# ---------- 任务数量检测 ----------
if analyser is None:
# analyser 参数必需
if return_info:
return False, {
"method": "task_count",
"task_count": 0,
"reason": "analyser_required",
}
return False
try:
from .douyin_detection import check_detail_height
# 执行任务数量检测
task_count = int(check_detail_height(analyser) or 0)
# 判断是否在福袋详情页
# 如果任务数量 <= 0,则认为不在福袋详情页
# 如果任务数量 >= 1,则认为在福袋详情页
is_in_detail = task_count >= 1
if return_info:
return is_in_detail, {
"method": "task_count",
"task_count": task_count,
}
return is_in_detail
except Exception as e: # type: ignore[general-exception]
# 检测异常
if return_info:
return False, {
"method": "task_count",
"task_count": 0,
"reason": f"detection_exception: {str(e)}",
}
return False
def read_pixel_stage_state_from_screenshot(
pic_path: str,
resolution_ratio_x: int = 1080,
resolution_ratio_y: int = 2400,
y_pianyi: int = 0,
lucky_draw_red_ratio_threshold: float = 0.8,
fudai_template_threshold: float = 0.7,
return_details: bool = False,
analyser: Any = None,
) -> dict[str, bool] | tuple[dict[str, bool], dict[str, dict]]:
"""从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。
使用多线程并行执行所有检测函数以提高性能。
参数:
pic_path: 截图路径
resolution_ratio_x: 分辨率X比例(默认1080)
resolution_ratio_y: 分辨率Y比例(默认2400)
y_pianyi: Y轴偏移(默认0)
lucky_draw_red_ratio_threshold: 抽奖结果红色比例阈值(默认0.8)
fudai_template_threshold: 福袋详情模板匹配阈值(默认0.7)
return_details: 是否返回每个检测步骤的详细信息(包括分数)
返回:
dict[str, bool]: 检测结果(return_details=False时)
tuple[dict[str, bool], dict[str, dict]]: (检测结果, 详细信息)(return_details=True时)
"""
state: dict[str, bool] = {
"has_coupon_bg": False,
"has_redpacket_bg": False,
"has_lucky_draw_result": False,
"has_attend_button_red": False,
"has_fansclub_join_red": False,
"has_fudai_detail": False,
"has_live_room_pixel": False, # 直播间图标像素检测(多边形区域白色像素检测)
}
details: dict[str, dict] = {}
pic_rgb = _safe_open_screenshot_rgb(pic_path)
if pic_rgb is None:
if return_details:
return state, details
return state
# 并行执行所有检测函数
# 注意:优惠券检测需要额外参数,使用lambda包装
# 注意:福袋详情检测使用任务数量检测,需要analyser参数
# 从analyser读取阈值(如果可用)
coupon_threshold = None
attend_button_threshold = None
fansclub_threshold = None
redpacket_threshold = None
live_room_pixel_threshold = None
if analyser is not None:
try:
coupon_threshold = float(
getattr(analyser, "coupon_template_match_threshold", None) or 0.75
)
except Exception as e: # type: ignore[general-exception]
pass
try:
attend_button_threshold = float(
getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25
)
except Exception as e: # type: ignore[general-exception]
pass
try:
fansclub_threshold = float(
getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25
)
except Exception as e: # type: ignore[general-exception]
pass
try:
redpacket_threshold = float(
getattr(analyser, "shopping_redpacket_red_ratio_threshold", None)
or 0.15
)
except Exception as e: # type: ignore[general-exception]
pass
try:
live_room_pixel_threshold = float(
getattr(analyser, "live_room_match_threshold", None) or 0.8
)
except Exception as e: # type: ignore[general-exception]
pass
# 定义直播间图标像素检测包装函数
def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]:
"""直播间图标像素检测包装函数,返回 (bool, dict) 格式"""
try:
detected, confidence = detect_live_room_icons_by_pixel(pic)
threshold = live_room_pixel_threshold or 0.8
is_detected = detected and confidence >= threshold
return is_detected, {
"method": "pixel_detection",
"confidence": confidence,
"effective_threshold": threshold,
}
except Exception as e: # type: ignore[general-exception]
return False, {"method": "pixel_detection", "error": str(e)}
# 模板匹配已删除,只使用像素检测
detection_tasks = {
"has_coupon_bg": lambda pic: detect_coupon_popup_background(
pic,
return_info=True,
template_threshold=coupon_threshold,
analyser=analyser,
),
"has_redpacket_bg": lambda pic: detect_redpacket_popup_background(
pic,
return_info=True,
red_ratio_threshold=redpacket_threshold,
analyser=analyser,
),
"has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(
pic, lucky_draw_red_ratio_threshold, return_info=True
),
"has_attend_button_red": lambda pic: detect_attend_button_red_area(
pic,
return_info=True,
red_ratio_threshold=attend_button_threshold,
analyser=analyser,
),
"has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(
pic,
return_info=True,
red_ratio_threshold=fansclub_threshold,
analyser=analyser,
),
"has_fudai_detail": lambda pic: detect_fudai_detail_page(
pic,
resolution_ratio_x,
resolution_ratio_y,
y_pianyi,
fudai_template_threshold,
return_info=True,
analyser=analyser,
),
"has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测)
}
# 使用线程池并行执行检测(增加线程数以支持直播间图标检测)
with ThreadPoolExecutor(max_workers=8) as executor:
# 提交所有任务,并记录开始时间
import time
future_to_key = {}
for key, detect_func in detection_tasks.items():
start_time = time.time()
future = executor.submit(detect_func, pic_rgb)
future_to_key[future] = (key, start_time)
# 收集结果
for future in as_completed(future_to_key):
key, start_time = future_to_key[future]
elapsed_ms = (time.time() - start_time) * 1000
try:
result = future.result()
# 处理结果
if isinstance(result, tuple):
# 检测函数返回 (bool, dict) 格式
is_detected, info = result
state[key] = bool(is_detected)
if return_details:
details[key] = {
"detected": bool(is_detected),
"method": info.get("method", "unknown"),
"template_score": info.get("template_score"),
"confidence": info.get(
"confidence"
), # 添加confidence支持(用于像素检测)
"task_count": info.get("task_count"), # 添加task_count支持
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
"effective_threshold": info.get("effective_threshold"),
"reason": info.get("reason"),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
else:
# 其他检测返回 bool(不应该发生,因为所有检测都支持return_info)
state[key] = bool(result)
if return_details:
details[key] = {
"detected": bool(result),
"method": "unknown",
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
except Exception as e: # type: ignore[general-exception]
# 如果某个检测失败,保持默认值 False
state[key] = False
if return_details:
details[key] = {
"detected": False,
"error": str(e),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
if return_details:
return state, details
return state
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
+2 -3
View File
@@ -11,7 +11,7 @@ import traceback
from typing import Any, Tuple, Optional, Dict
from PIL import Image, UnidentifiedImageError
import path_config
from douyin.core import path_config
def log_debug_error(
@@ -156,8 +156,7 @@ def save_full_screenshot_with_ocr_region(
}
try:
import importlib
douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager")
from douyin.handlers import douyin_screenshot_manager
except Exception as e:
log_debug_error(
analyser,
@@ -36,12 +36,12 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
try:
# 使用统一的截图路径配置
try:
import path_config
from douyin.core import path_config
path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
from douyin.core import path_config
path = path_config.get_screenshot_path()
@@ -228,12 +228,12 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
# 使用统一的截图路径配置
try:
import path_config
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
@@ -0,0 +1,17 @@
"""fudai_detail_orchestrator - 兼容入口(保留外部 import 路径)。
实际实现位于子包 ``douyin.fudai.core.fudai_detail_orchestrator_pkg``。
本文件仅 re-export 公共符号;详见各子模块文档:
- ``fudai_detail_orchestrator_pkg.read_once`` 单次福袋详情识别
- ``fudai_detail_orchestrator_pkg.read_with_retries`` 带重试的版本
"""
from douyin.fudai.core.fudai_detail_orchestrator_pkg import (
read_fudai_detail_once,
read_fudai_detail_with_retries,
)
__all__ = [
"read_fudai_detail_once",
"read_fudai_detail_with_retries",
]
@@ -0,0 +1,19 @@
"""fudai_detail_orchestrator_pkg - 福袋详情读取子包。
原 douyin/fudai/core/fudai_detail_orchestrator.py 拆成 2 个子模块:
- read_once read_fudai_detail_once(单次识别)
- read_with_retries read_fudai_detail_with_retries(带重试)
外部 import 路径不变:
``from douyin.fudai.core.fudai_detail_orchestrator import read_fudai_detail_with_retries``
仍可用(原文件改成 re-export shim)。
"""
from .read_once import read_fudai_detail_once
from .read_with_retries import read_fudai_detail_with_retries
__all__ = [
"read_fudai_detail_once",
"read_fudai_detail_with_retries",
]
@@ -0,0 +1,546 @@
"""fudai_detail_orchestrator_pkg.read_once - 单次福袋详情识别。
read_fudai_detail_once:执行一次完整的 OCR 识别(任务数 / 内容 / 时间 / 价值 / 参与人数)
"""
from __future__ import annotations
import os
import time
from typing import Any, Dict, Tuple
from PIL import Image
from douyin.fudai.douyin_fudai_core import get_fudai_contain
from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
"""执行一次福袋详情识别(本地完整版实现)。
流程:
1. 获取截图(任务数量检测和弹窗检测已在阶段检测中完成,不再重复检测);
2. 从阶段检测结果中获取任务数量(_fudai_detail_task_count_from_stage);
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
"""
start_time = time.time()
# 性能标记变量
screenshot_reused = False
screenshot_start = None
screenshot_end = None
ocr_start = None
ocr_end = None
wait_file_ms: Optional[float] = None
image_load_ms: Optional[float] = None
service_stop_ms: Optional[float] = None
countdown_parse_ms: Optional[float] = None
def _log_perf(tag: str) -> None:
try:
total_ms = round((time.time() - start_time) * 1000, 1)
screenshot_ms = None
if screenshot_start is not None and screenshot_end is not None:
screenshot_ms = round((screenshot_end - screenshot_start) * 1000, 1)
ocr_ms = None
if ocr_start is not None and ocr_end is not None:
ocr_ms = round((ocr_end - ocr_start) * 1000, 1)
analyser._log_kv(
"性能",
"福袋详情关键耗时(ms)",
log_type="PERF",
total_ms=total_ms,
screenshot_ms=screenshot_ms,
ocr_ms=ocr_ms,
wait_file_ms=wait_file_ms,
image_load_ms=image_load_ms,
service_stop_ms=service_stop_ms,
countdown_parse_ms=countdown_parse_ms,
screenshot_reused=bool(screenshot_reused),
tag=tag,
)
except Exception:
pass
# 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取)
# 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage
task_count = 0
try:
task_count_from_stage = getattr(
analyser, "_fudai_detail_task_count_from_stage", None
)
if task_count_from_stage is not None:
task_count = int(task_count_from_stage or 0)
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:从阶段检测获取任务数量(无需截图)",
log_type="OP",
task_count=task_count,
)
except Exception:
pass
else:
# 如果阶段检测未保存任务数量,记录警告日志
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:警告:阶段检测未保存任务数量,使用默认值0",
log_type="WARNING",
可能原因="点击验证阶段检测未执行或像素检测失败",
建议="检查阶段检测日志,确认触发原因和检测结果",
task_count_from_stage=task_count_from_stage,
)
except Exception:
pass
pass
# 使用默认值
task_count = 0
# 注意:任务数量标志不由 read_fudai_detail_once 清除
# 应该由调用方在完成所有相关处理后清除,避免影响后续逻辑
# 保留此代码块以便将来需要时恢复
# try:
# analyser._fudai_detail_task_count_from_stage = None
# try:
# analyser._log_kv(
# "福袋详情",
# "read_fudai_detail_once:清除任务数量标志",
# log_type="DEBUG",
# )
# except Exception:
# pass
# except Exception:
# # 忽略异常,继续处理
# pass
# 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底)
# 在获取截图之前就返回错误,避免不必要的截图
if task_count <= 0:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR",
task_count=task_count,
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(任务数量为0)",
elapsed_seconds=round(elapsed, 2),
log_type="OP",
)
_log_perf("taskcount_zero")
return (
"error",
tup_err,
{"reason": "not_in_fudai_detail", "task_count": task_count},
)
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
if task_count not in (1, 2, 3):
task_count = 2
except Exception as e:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:获取任务数量异常,使用默认值",
log_type="ERR",
error=str(e),
)
except Exception:
pass
# 异常时使用默认值
task_count = 2
# 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量)
# 注意:此时后台截图服务已被停止,直接调用底层截图避免递归
# 检查是否可以复用阶段诊断时的截图
screenshot_reused = False
try:
if getattr(analyser, "_screenshot_ready_for_ocr", False):
try:
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用
screenshot_reused = True
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:复用阶段诊断截图",
log_type="SCREENSHOT",
reason="stage_diagnosed_task_count_gt_zero",
path=pic_path,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)",
log_type="SCREENSHOT",
path=pic_path,
size=(
os.path.getsize(pic_path) if os.path.exists(pic_path) else 0
),
)
except Exception:
pass
except Exception:
pass
# 只有在不能复用截图时才进行新的截图
if not screenshot_reused:
try:
screenshot_start = time.time()
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
# 等待截图文件确实存在(最多等待3秒)
try:
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
wait_start = time.time()
while time.time() - wait_start < 3.0:
if os.path.exists(pic_path):
file_size = os.path.getsize(pic_path)
if file_size >= 1024: # 至少1KB
break
time.sleep(0.1)
screenshot_end = time.time()
wait_file_ms = round((screenshot_end - wait_start) * 1000, 1)
_log_perf("after_screenshot") # 移除:避免过多性能日志
except Exception:
screenshot_end = time.time() if screenshot_start is not None else None
pass
# 使用统一的截图路径配置
try:
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
pic_rgb = None
try:
if os.path.exists(pic_path):
_img0 = time.time()
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
image_load_ms = round((time.time() - _img0) * 1000, 1)
_log_perf("after_image_load") # 移除:避免过多性能日志
except Exception:
pass
if pic_rgb is None:
try:
analyser._log_kv(
"福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别"
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(截图失败)",
elapsed_seconds=round(elapsed, 2),
)
_log_perf("screenshot_failed")
return "error", tup_err, {"reason": "screenshot_failed"}
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
if task_count not in (1, 2, 3):
task_count = 2
# 识别福袋内容 / 倒计时 / 价值
# 在OCR密集操作期间临时禁用截图服务,避免后台截图干扰
_ocr_screenshot_service_disabled = False
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
if service.is_running():
_svc0 = time.time()
# 临时停止后台截图服务,避免在OCR过程中继续截图
service.stop()
_ocr_screenshot_service_disabled = True
service_stop_ms = round((time.time() - _svc0) * 1000, 1)
try:
analyser._log_kv(
"截图服务",
"OCR密集操作期间停止后台截图服务",
reason="prevent_background_screenshots_during_ocr",
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
"截图服务", "停止后台截图服务失败", error=str(e), level="WARNING"
)
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
try:
ocr_start = time.time()
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
analyser, renwu=task_count
)
ocr_end = time.time()
_log_perf("after_get_fudai_contain") # 移除:避免过多性能日志
except Exception as e: # pyright: ignore[reportTooBroadExceptionType]
# 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查
try:
import traceback
tb = traceback.format_exc()
# 先尝试通过 analyser._log_kv 输出完整 trace(如果可用)
try:
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
error_type=type(e).__name__,
traceback=tb,
)
except Exception: # pyright: ignore[reportTooBroadExceptionType]
# fallback: 将 traceback 写入统一错误日志
try:
from douyin.core import path_config
err_log = path_config.get_error_log_path()
with open(err_log, "a", encoding="utf-8") as ef:
ef.write(
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\\n"
)
ef.write(tb)
ef.write("\\n")
except Exception:
pass
except Exception: # pyright: ignore[reportTooBroadExceptionType]
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常(无法格式化 traceback)",
error=str(e),
) # pyright: ignore[reportPrivateUsage]
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(识别异常)",
elapsed_seconds=round(elapsed, 2),
) # pyright: ignore[reportPrivateUsage]
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
_log_perf("exception_in_get_fudai_contain")
return "error", tup_err, {}
# 由于已全局禁用流式截图,不再重新启动服务
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
is_watch_task = False
try:
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False))
# 清除标志,避免影响后续调用
if is_watch_task:
try:
analyser._is_watch_task_detected = (
False # pyright: ignore[reportPrivateUsage]
)
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
except Exception:
pass
# 如果检测到观看任务,返回 watch_task 状态
if is_watch_task:
try:
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
"福袋详情",
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
)
except Exception:
pass
now = time.time()
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(观看任务)",
elapsed_seconds=round(elapsed, 2),
) # pyright: ignore[reportPrivateUsage]
return (
"watch_task",
tup_watch,
{"reason": "watch_task_detected", "task_count": task_count},
)
# 解析倒计时 -> (剩余秒数, 未来时间戳)
countdown_start = time.time()
countdown_end = countdown_start + 60.0
total_seconds_from_ocr = None # 保存OCR识别到的原始秒数
try:
_cd0 = time.time()
if time_text:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
total_seconds, future_ts = res
try:
total_seconds = int(total_seconds)
total_seconds_from_ocr = total_seconds # 保存原始秒数
except Exception:
total_seconds = int(float(total_seconds or 0))
total_seconds_from_ocr = total_seconds
if total_seconds >= 0 and isinstance(future_ts, (int, float)):
countdown_start = float(countdown_start)
countdown_end = float(future_ts)
countdown_parse_ms = round((time.time() - _cd0) * 1000, 1)
# _log_perf("after_countdown_parse") # 移除:避免过多性能日志
except Exception:
pass
detail_tuple = (
content or "",
time_text or "",
int(participants or 0),
int(copies or 0),
float(prize_value_yuan or 0.0),
(countdown_start, countdown_end, total_seconds_from_ocr), # 添加原始秒数
)
extra: Dict[str, Any] = {
"task_count": task_count,
}
# 获取直播间名字
room_title = ""
room_title_raw = ""
try:
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
room_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
).strip()
except Exception:
pass
# 输出所有识别到的内容到运行日志和行为日志
try:
from datetime import datetime
# 格式化时间戳为可读格式
countdown_start_str = ""
countdown_end_str = ""
if countdown_start and countdown_end:
try:
if countdown_start > 0:
countdown_start_str = datetime.fromtimestamp(
countdown_start
).strftime("%Y-%m-%d %H:%M:%S")
if countdown_end > 0:
countdown_end_str = datetime.fromtimestamp(countdown_end).strftime(
"%Y-%m-%d %H:%M:%S"
)
except Exception:
pass
# 计算剩余秒数 - 优先使用OCR识别到的原始秒数,避免时间差导致的误差
remain_seconds = 0
if total_seconds_from_ocr is not None:
# 使用OCR识别到的原始秒数,这更准确地反映了识别时刻的倒计时
remain_seconds = max(0, total_seconds_from_ocr)
elif countdown_end > countdown_start:
# 兜底:使用时间戳计算(可能有误差)
remain_seconds = int(max(0, countdown_end - time.time()))
# 输出完整的识别结果到运行日志
content_preview = (content or "")[:60] if content else "未识别到"
content_full = content or ""
# 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出)
analyser._log_kv(
"福袋",
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
level="DEBUG",
)
except Exception as e:
# 如果详细日志输出失败,至少输出基本信息
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果(简化)",
status="ok",
content=content or "",
time_text=time_text or "",
participants=int(participants or 0),
copies=int(copies or 0),
prize_value_yuan=float(prize_value_yuan or 0.0),
error=str(e),
)
except Exception:
pass
elapsed = time.time() - start_time
# 计算各阶段耗时(可能为 None)
screenshot_ms = (
round((screenshot_end - screenshot_start) * 1000, 1)
if screenshot_start is not None and screenshot_end is not None
else None
)
ocr_ms = (
round((ocr_end - ocr_start) * 1000, 1)
if ocr_start is not None and ocr_end is not None
else None
)
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(成功)",
log_type="OP",
level="INFO",
elapsed_seconds=round(elapsed, 2),
screenshot_ms=screenshot_ms,
ocr_ms=ocr_ms,
wait_file_ms=wait_file_ms,
image_load_ms=image_load_ms,
service_stop_ms=service_stop_ms,
countdown_parse_ms=countdown_parse_ms,
screenshot_reused=bool(getattr(analyser, "_screenshot_ready_for_ocr", False)),
content_preview=(content or "")[:60],
prize_value_yuan=float(prize_value_yuan or 0.0),
time_text=time_text or "",
participants=int(participants or 0),
copies=int(copies or 0),
task_count=task_count,
)
_log_perf("success") # 只在最终成功时输出性能日志
return "ok", detail_tuple, extra
@@ -1,550 +1,20 @@
"""
福袋详情读取模块
================
"""fudai_detail_orchestrator_pkg.read_with_retries - 带重试的福袋详情识别。
执行福袋详情的OCR识别和读取,包括单次读取和重试读取。
read_fudai_detail_with_retries:包装 read_fudai_detail_once,按配置做多轮重试,
解决 OCR 偶发误识别 / 内容尚未渲染完整的情况。
"""
from __future__ import annotations
from typing import Any, Dict, Tuple, Optional
import os
import time
from typing import Any, Dict, Optional, Tuple
from PIL import Image
from douyin.fudai.douyin_fudai_core import get_fudai_contain
from .fudai_detail_validator import validate_fudai_detail
from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
"""执行一次福袋详情识别(本地完整版实现)。
流程:
1. 获取截图(任务数量检测和弹窗检测已在阶段检测中完成,不再重复检测);
2. 从阶段检测结果中获取任务数量(_fudai_detail_task_count_from_stage);
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
"""
start_time = time.time()
# 性能标记变量
screenshot_reused = False
screenshot_start = None
screenshot_end = None
ocr_start = None
ocr_end = None
wait_file_ms: Optional[float] = None
image_load_ms: Optional[float] = None
service_stop_ms: Optional[float] = None
countdown_parse_ms: Optional[float] = None
def _log_perf(tag: str) -> None:
try:
total_ms = round((time.time() - start_time) * 1000, 1)
screenshot_ms = None
if screenshot_start is not None and screenshot_end is not None:
screenshot_ms = round((screenshot_end - screenshot_start) * 1000, 1)
ocr_ms = None
if ocr_start is not None and ocr_end is not None:
ocr_ms = round((ocr_end - ocr_start) * 1000, 1)
analyser._log_kv(
"性能",
"福袋详情关键耗时(ms)",
log_type="PERF",
total_ms=total_ms,
screenshot_ms=screenshot_ms,
ocr_ms=ocr_ms,
wait_file_ms=wait_file_ms,
image_load_ms=image_load_ms,
service_stop_ms=service_stop_ms,
countdown_parse_ms=countdown_parse_ms,
screenshot_reused=bool(screenshot_reused),
tag=tag,
)
except Exception:
pass
# 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取)
# 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage
task_count = 0
try:
task_count_from_stage = getattr(
analyser, "_fudai_detail_task_count_from_stage", None
)
if task_count_from_stage is not None:
task_count = int(task_count_from_stage or 0)
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:从阶段检测获取任务数量(无需截图)",
log_type="OP",
task_count=task_count,
)
except Exception:
pass
else:
# 如果阶段检测未保存任务数量,记录警告日志
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:警告:阶段检测未保存任务数量,使用默认值0",
log_type="WARNING",
可能原因="点击验证阶段检测未执行或像素检测失败",
建议="检查阶段检测日志,确认触发原因和检测结果",
task_count_from_stage=task_count_from_stage,
)
except Exception:
pass
pass
# 使用默认值
task_count = 0
# 注意:任务数量标志不由 read_fudai_detail_once 清除
# 应该由调用方在完成所有相关处理后清除,避免影响后续逻辑
# 保留此代码块以便将来需要时恢复
# try:
# analyser._fudai_detail_task_count_from_stage = None
# try:
# analyser._log_kv(
# "福袋详情",
# "read_fudai_detail_once:清除任务数量标志",
# log_type="DEBUG",
# )
# except Exception:
# pass
# except Exception:
# # 忽略异常,继续处理
# pass
# 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底)
# 在获取截图之前就返回错误,避免不必要的截图
if task_count <= 0:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR",
task_count=task_count,
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(任务数量为0)",
elapsed_seconds=round(elapsed, 2),
log_type="OP",
)
_log_perf("taskcount_zero")
return (
"error",
tup_err,
{"reason": "not_in_fudai_detail", "task_count": task_count},
)
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
if task_count not in (1, 2, 3):
task_count = 2
except Exception as e:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:获取任务数量异常,使用默认值",
log_type="ERR",
error=str(e),
)
except Exception:
pass
# 异常时使用默认值
task_count = 2
# 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量)
# 注意:此时后台截图服务已被停止,直接调用底层截图避免递归
# 检查是否可以复用阶段诊断时的截图
screenshot_reused = False
try:
if getattr(analyser, "_screenshot_ready_for_ocr", False):
try:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用
screenshot_reused = True
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:复用阶段诊断截图",
log_type="SCREENSHOT",
reason="stage_diagnosed_task_count_gt_zero",
path=pic_path,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)",
log_type="SCREENSHOT",
path=pic_path,
size=(
os.path.getsize(pic_path) if os.path.exists(pic_path) else 0
),
)
except Exception:
pass
except Exception:
pass
# 只有在不能复用截图时才进行新的截图
if not screenshot_reused:
try:
screenshot_start = time.time()
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
# 等待截图文件确实存在(最多等待3秒)
try:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
pic_path = os.path.join(
os.path.dirname(__file__), "pic", "screenshot.png"
)
wait_start = time.time()
while time.time() - wait_start < 3.0:
if os.path.exists(pic_path):
file_size = os.path.getsize(pic_path)
if file_size >= 1024: # 至少1KB
break
time.sleep(0.1)
screenshot_end = time.time()
wait_file_ms = round((screenshot_end - wait_start) * 1000, 1)
_log_perf("after_screenshot") # 移除:避免过多性能日志
except Exception:
screenshot_end = time.time() if screenshot_start is not None else None
pass
# 使用统一的截图路径配置
try:
import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
import path_config
pic_path = path_config.get_screenshot_path()
pic_rgb = None
try:
if os.path.exists(pic_path):
_img0 = time.time()
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
image_load_ms = round((time.time() - _img0) * 1000, 1)
_log_perf("after_image_load") # 移除:避免过多性能日志
except Exception:
pass
if pic_rgb is None:
try:
analyser._log_kv(
"福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别"
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(截图失败)",
elapsed_seconds=round(elapsed, 2),
)
_log_perf("screenshot_failed")
return "error", tup_err, {"reason": "screenshot_failed"}
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
if task_count not in (1, 2, 3):
task_count = 2
# 识别福袋内容 / 倒计时 / 价值
# 在OCR密集操作期间临时禁用截图服务,避免后台截图干扰
_ocr_screenshot_service_disabled = False
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
if service.is_running():
_svc0 = time.time()
# 临时停止后台截图服务,避免在OCR过程中继续截图
service.stop()
_ocr_screenshot_service_disabled = True
service_stop_ms = round((time.time() - _svc0) * 1000, 1)
try:
analyser._log_kv(
"截图服务",
"OCR密集操作期间停止后台截图服务",
reason="prevent_background_screenshots_during_ocr",
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
"截图服务", "停止后台截图服务失败", error=str(e), level="WARNING"
)
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
try:
ocr_start = time.time()
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
analyser, renwu=task_count
)
ocr_end = time.time()
_log_perf("after_get_fudai_contain") # 移除:避免过多性能日志
except Exception as e: # pyright: ignore[reportTooBroadExceptionType]
# 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查
try:
import traceback
tb = traceback.format_exc()
# 先尝试通过 analyser._log_kv 输出完整 trace(如果可用)
try:
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
error_type=type(e).__name__,
traceback=tb,
)
except Exception: # pyright: ignore[reportTooBroadExceptionType]
# fallback: 将 traceback 写入统一错误日志
try:
import path_config
err_log = path_config.get_error_log_path()
with open(err_log, "a", encoding="utf-8") as ef:
ef.write(
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\\n"
)
ef.write(tb)
ef.write("\\n")
except Exception:
pass
except Exception: # pyright: ignore[reportTooBroadExceptionType]
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常(无法格式化 traceback)",
error=str(e),
) # pyright: ignore[reportPrivateUsage]
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(识别异常)",
elapsed_seconds=round(elapsed, 2),
) # pyright: ignore[reportPrivateUsage]
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
_log_perf("exception_in_get_fudai_contain")
return "error", tup_err, {}
# 由于已全局禁用流式截图,不再重新启动服务
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
is_watch_task = False
try:
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False))
# 清除标志,避免影响后续调用
if is_watch_task:
try:
analyser._is_watch_task_detected = (
False # pyright: ignore[reportPrivateUsage]
)
except Exception: # pyright: ignore[reportTooBroadExceptionType]
pass
except Exception:
pass
# 如果检测到观看任务,返回 watch_task 状态
if is_watch_task:
try:
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
"福袋详情",
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
)
except Exception:
pass
now = time.time()
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
elapsed = time.time() - start_time
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(观看任务)",
elapsed_seconds=round(elapsed, 2),
) # pyright: ignore[reportPrivateUsage]
return (
"watch_task",
tup_watch,
{"reason": "watch_task_detected", "task_count": task_count},
)
# 解析倒计时 -> (剩余秒数, 未来时间戳)
countdown_start = time.time()
countdown_end = countdown_start + 60.0
total_seconds_from_ocr = None # 保存OCR识别到的原始秒数
try:
_cd0 = time.time()
if time_text:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
total_seconds, future_ts = res
try:
total_seconds = int(total_seconds)
total_seconds_from_ocr = total_seconds # 保存原始秒数
except Exception:
total_seconds = int(float(total_seconds or 0))
total_seconds_from_ocr = total_seconds
if total_seconds >= 0 and isinstance(future_ts, (int, float)):
countdown_start = float(countdown_start)
countdown_end = float(future_ts)
countdown_parse_ms = round((time.time() - _cd0) * 1000, 1)
# _log_perf("after_countdown_parse") # 移除:避免过多性能日志
except Exception:
pass
detail_tuple = (
content or "",
time_text or "",
int(participants or 0),
int(copies or 0),
float(prize_value_yuan or 0.0),
(countdown_start, countdown_end, total_seconds_from_ocr), # 添加原始秒数
)
extra: Dict[str, Any] = {
"task_count": task_count,
}
# 获取直播间名字
room_title = ""
room_title_raw = ""
try:
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
room_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
).strip()
except Exception:
pass
# 输出所有识别到的内容到运行日志和行为日志
try:
from datetime import datetime
# 格式化时间戳为可读格式
countdown_start_str = ""
countdown_end_str = ""
if countdown_start and countdown_end:
try:
if countdown_start > 0:
countdown_start_str = datetime.fromtimestamp(
countdown_start
).strftime("%Y-%m-%d %H:%M:%S")
if countdown_end > 0:
countdown_end_str = datetime.fromtimestamp(countdown_end).strftime(
"%Y-%m-%d %H:%M:%S"
)
except Exception:
pass
# 计算剩余秒数 - 优先使用OCR识别到的原始秒数,避免时间差导致的误差
remain_seconds = 0
if total_seconds_from_ocr is not None:
# 使用OCR识别到的原始秒数,这更准确地反映了识别时刻的倒计时
remain_seconds = max(0, total_seconds_from_ocr)
elif countdown_end > countdown_start:
# 兜底:使用时间戳计算(可能有误差)
remain_seconds = int(max(0, countdown_end - time.time()))
# 输出完整的识别结果到运行日志
content_preview = (content or "")[:60] if content else "未识别到"
content_full = content or ""
# 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出)
analyser._log_kv(
"福袋",
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
level="DEBUG",
)
except Exception as e:
# 如果详细日志输出失败,至少输出基本信息
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果(简化)",
status="ok",
content=content or "",
time_text=time_text or "",
participants=int(participants or 0),
copies=int(copies or 0),
prize_value_yuan=float(prize_value_yuan or 0.0),
error=str(e),
)
except Exception:
pass
elapsed = time.time() - start_time
# 计算各阶段耗时(可能为 None)
screenshot_ms = (
round((screenshot_end - screenshot_start) * 1000, 1)
if screenshot_start is not None and screenshot_end is not None
else None
)
ocr_ms = (
round((ocr_end - ocr_start) * 1000, 1)
if ocr_start is not None and ocr_end is not None
else None
)
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once完成(成功)",
log_type="OP",
level="INFO",
elapsed_seconds=round(elapsed, 2),
screenshot_ms=screenshot_ms,
ocr_ms=ocr_ms,
wait_file_ms=wait_file_ms,
image_load_ms=image_load_ms,
service_stop_ms=service_stop_ms,
countdown_parse_ms=countdown_parse_ms,
screenshot_reused=bool(getattr(analyser, "_screenshot_ready_for_ocr", False)),
content_preview=(content or "")[:60],
prize_value_yuan=float(prize_value_yuan or 0.0),
time_text=time_text or "",
participants=int(participants or 0),
copies=int(copies or 0),
task_count=task_count,
)
_log_perf("success") # 只在最终成功时输出性能日志
return "ok", detail_tuple, extra
from .read_once import read_fudai_detail_once
def read_fudai_detail_with_retries(
File diff suppressed because it is too large. Load diff
@@ -207,7 +207,7 @@ def read_live_room_title_core(
else:
# 检查是否有可用的截图文件
try:
import path_config
from douyin.core import path_config
pic_path = path_config.get_screenshot_path()
except Exception:
@@ -12,7 +12,7 @@ import logging
import re
import os
import json
import path_config
from douyin.core import path_config
def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]:
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,27 @@
"""fudai_filter_pkg - 福袋筛选决策子包。
原 douyin/fudai/core/fudai_filter.py 拆成 3 个子模块:
- helpers 小工具:倒计时短文本 / 黑名单 / 观看任务识别
- should_skip should_skip_fudai_by_config 配置筛选总决策
- join_decision basic_join_decision 最终参与决策
外部 import 路径不变:``from douyin.fudai.core.fudai_filter import basic_join_decision``
仍可用(原文件改成 re-export shim)。
"""
from .helpers import (
_is_short_countdown_text,
check_contain,
is_watch_task_fudai,
)
from .should_skip import should_skip_fudai_by_config
from .join_decision import basic_join_decision
__all__ = [
"_is_short_countdown_text",
"check_contain",
"is_watch_task_fudai",
"should_skip_fudai_by_config",
"basic_join_decision",
]
@@ -0,0 +1,126 @@
"""fudai_filter_pkg.helpers - 小型工具函数。
- _is_short_countdown_text 判断倒计时文本是否表示 "剩余 ≤2 秒" 应跳过
- check_contain 黑名单关键词检查(contains_not_want)
- is_watch_task_fudai 识别 "观看 X 分钟" 类观看任务福袋
"""
from __future__ import annotations
import re
def _is_short_countdown_text(time_text: str) -> bool:
"""检查倒计时文本是否表示剩余时间很短(应跳过)"""
if not time_text:
return False
time_text = time_text.strip()
# 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒
if re.match(r"^00:0[0-2]$", time_text):
return True
# 匹配 0:00, 0:01, 0:02 等(有时没有前导零)
if re.match(r"^0:0[0-2]$", time_text):
return True
# 匹配 "00秒", "01秒", "02秒" 等
if re.match(r"^0[0-2]秒$", time_text):
return True
return False
def check_contain(analyser, contains: str = "") -> bool:
"""检查福袋内容是否命中"黑名单"关键词(只保留黑名单逻辑,不再使用白名单)。
返回值语义(调整后):
- True : "建议丢弃"(内容命中黑名单 contains_not_want)
- False : "可以保留"(未命中黑名单)
"""
try:
for contain in getattr(analyser, "contains_not_want", []) or []:
if contain and contain in (contains or ""):
try:
analyser._log_kv(
"筛选",
"福袋内容命中黑名单,将丢弃",
keyword=contain,
contains=contains[:80] if contains else "",
)
except Exception:
pass
return True
try:
analyser._log_kv(
"筛选",
"福袋内容未命中黑名单,保留",
contains=contains[:80] if contains else "",
)
except Exception:
pass
return False
except Exception:
# 容错:异常时不过滤
try:
analyser._log_kv(
"筛选",
"check_contain 异常,默认保留",
contains=contains[:80] if contains else "",
)
except Exception:
pass
return False
def is_watch_task_fudai(content: str) -> bool:
"""检测是否为"观看X分钟"类任务福袋。
参数:
content: 福袋内容文本
返回:
True 表示是"观看X分钟"类任务,应放弃
False 表示不是此类任务
"""
if not content:
return False
try:
import re
# 将内容转换为字符串并去除空白
content_str = re.sub(r"\s+", "", str(content))
# 中文数字字符
chinese_num_chars = "零一二三四五六七八九十百千两"
# 匹配模式1:观看/看 + (可选"直播") + 数字或中文数字 + 分钟
patt1 = rf"(?:观看|看)(?:直播)?(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
# 匹配模式2:需要观看/需要看 + 数字或中文数字 + 分钟
patt2 = rf"需要(?:观看|看)(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
# 匹配模式3:观看时长 + 数字或中文数字 + 分钟
patt3 = rf"观看时长(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
# 匹配模式4:看播 + 数字或中文数字 + 分钟
patt4 = rf"看播(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
# 检查是否匹配任一模式
patterns = [patt1, patt2, patt3, patt4]
for patt in patterns:
if re.search(patt, content_str):
return True
return False
except Exception:
return False
@@ -0,0 +1,524 @@
"""fudai_filter_pkg.join_decision - basic_join_decision 主决策。
包含 basic_join_decision:在 should_skip_fudai_by_config 通过后,
做最终的 "是否真的点击参与按钮" 决策(含运行时校验、按钮文本识别等)。
"""
from __future__ import annotations
import re
import time
from typing import Any, Tuple
from .helpers import _is_short_countdown_text
from .should_skip import should_skip_fudai_by_config
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
"""基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。
返回:
True 表示已经参与或已处理完成;
False 表示未参与(例如被配置筛掉或参与失败)。
"""
# time 模块在文件开头已导入
start_time = time.time()
# 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值
content = ""
prize_value_yuan = 0.0
countdown_tuple = None
try:
if isinstance(detail, tuple) and len(detail) >= 6:
content = str(detail[0] or "")
prize_value_yuan = float(detail[4] or 0.0)
countdown_tuple = detail[5]
except Exception:
pass
# 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理
try:
last_status = getattr(analyser, "_last_fudai_detail_status", "")
if last_status == "coupon_popup":
try:
analyser._log_kv(
"参与",
"basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理",
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(优惠券弹窗)",
elapsed_seconds=round(elapsed, 2),
)
return False
elif last_status == "validation_failed":
try:
analyser._log_kv(
"参与",
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
# 强制参与标志已移除:始终进行正常验证流程
force_attend = False
# 继续走后续验证分支
# 额外验证:使用验证函数检查数据合理性
try:
# 在函数开头导入,避免作用域问题
from douyin.fudai import douyin_fudai_detail as dfd_module
is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser)
if not is_valid:
try:
analyser._log_kv(
"参与",
"basic_join_decision:福袋详情数据验证失败,识别出错",
validation_reason=reason,
content=content[:50] if content else "",
prize_value_yuan=prize_value_yuan,
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
if not content and prize_value_yuan == 0.0:
try:
analyser._log_kv(
"参与",
"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
content=content,
prize_value_yuan=prize_value_yuan,
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(无效详情)",
elapsed_seconds=round(elapsed, 2),
)
return False
# 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if not needswitch:
try:
analyser._log_kv(
"参与",
"basic_join_decision:单间模式,忽略阈值与预约逻辑,直接参与当前福袋",
)
except Exception:
pass
# 这里需要导入 attend_choujiang 函数
from .fudai_attend import attend_choujiang
result = attend_choujiang(analyser)
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(单间模式参与)",
elapsed_seconds=round(elapsed, 2),
result=result,
)
return result
# 检查是否启用高价值预约,以及价值是否达到阈值
try:
high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False))
except Exception:
high_value_enabled = False
try:
high_value_threshold = float(
getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0
)
except Exception:
high_value_threshold = 500.0
# 计算 future_timestamp(预计开奖时间戳)
future_ts = 0.0
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
try:
future_ts = float(countdown_tuple[1] or 0.0)
except Exception:
future_ts = 0.0
# 检查是否已经参与过这个福袋(通过 future_ts 匹配,避免重复参与)
if future_ts > 0:
try:
participated_fudai_ts = getattr(
analyser, "_participated_fudai_future_ts", set()
)
if not isinstance(participated_fudai_ts, set):
participated_fudai_ts = set()
# 检查是否已经参与过(允许5秒误差,因为倒计时可能略有变化)
for participated_ts in participated_fudai_ts:
if abs(future_ts - participated_ts) < 5.0:
try:
analyser._log_kv(
"参与",
"basic_join_decision:已参与过此福袋,跳过重复参与",
future_ts=future_ts,
participated_ts=participated_ts,
)
except Exception:
pass
# 已参与过,直接返回 True(表示已处理完成)
return True
except Exception:
pass
# 检查价值是否达到高价值阈值
is_high_value = (
high_value_enabled
and prize_value_yuan > 0
and prize_value_yuan >= high_value_threshold
and future_ts > 0.0
)
# 执行筛选检查
skip, reason = should_skip_fudai_by_config(analyser, detail)
# 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
# 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected)
if skip and reason.startswith("countdown_gt_") and is_high_value:
# 再次检查是否是观看任务(双重保险)
is_watch_task = False
try:
is_watch_task = is_watch_task_fudai(content)
if is_watch_task:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"[预约]",
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
except Exception:
pass
# 关闭详情页
try:
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv(
"参与",
"basic_join_decision:已关闭详情(观看任务)",
action="close_detail",
)
except Exception:
pass
# 如果允许切换直播间,切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
analyser._log_kv(
"参与",
"basic_join_decision:观看任务后切换直播间",
reason="watch_task",
)
except Exception:
pass
try:
# 优先使用封装好的上滑切房方法
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
try:
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
analyser.operation.swipe(
analyser.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
except Exception:
# 切房失败不影响主流程,直接返回
pass
# 直接返回 False,不参与抽奖
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(观看任务,已丢弃)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
pass
# 计算剩余秒数
remain_seconds = None
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
try:
now = time.time()
cd_start = float(countdown_tuple[0] or 0.0)
cd_end = float(countdown_tuple[1] or 0.0)
if cd_start > 0 and cd_end > cd_start:
remain_seconds = float(cd_end - now)
except Exception:
pass
# 获取"预约参与阈值"配置
try:
join_ahead_seconds = int(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120
)
except Exception:
join_ahead_seconds = 120
# 检查是否是回退后强制参与
# 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约
if remain_seconds is not None and remain_seconds <= join_ahead_seconds:
try:
analyser._log_kv(
"参与",
"basic_join_decision:倒计时大于阈值,但剩余秒数在预约参与阈值内或回退后强制参与,立即参与",
reason=reason,
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=(
int(remain_seconds) if remain_seconds is not None else None
),
join_ahead_threshold=join_ahead_seconds,
force_attend=force_attend,
)
except Exception:
pass
# 不关闭详情,继续走立即参与逻辑
skip = False
reason = (
"high_value_immediate_join"
if not force_attend
else "reservation_back_force_attend"
)
# 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约)
# 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋
# no-op: 强制参与标志已删除
else:
# 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务
is_watch_task_check = False
try:
is_watch_task_check = is_watch_task_fudai(content)
if is_watch_task_check:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"[预约]",
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
except Exception:
pass
# 关闭详情页
try:
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv(
"参与",
"basic_join_decision:已关闭详情(观看任务)",
action="close_detail",
)
except Exception:
pass
# 如果允许切换直播间,切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
analyser._log_kv(
"参与",
"basic_join_decision:观看任务后切换直播间",
reason="watch_task",
)
except Exception:
pass
try:
# 优先使用封装好的上滑切房方法
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
try:
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
analyser.operation.swipe(
analyser.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
except Exception:
# 切房失败不影响主流程,直接返回
pass
# 直接返回 False,不参与抽奖
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(观看任务,已丢弃)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
pass
# 剩余秒数大于"预约参与阈值",记录预约
try:
analyser._log_kv(
"参与",
"basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约",
reason=reason,
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=(
int(remain_seconds) if remain_seconds is not None else None
),
join_ahead_threshold=join_ahead_seconds,
level="DEBUG",
)
except Exception:
pass
# 这里需要实现预约逻辑,由于代码太长,这里暂时简化
# 不关闭详情,继续走预约逻辑
skip = False
reason = "high_value_reservation"
if skip:
try:
analyser._log_kv(
"参与",
"basic_join_decision:按配置丢弃福袋",
reason=reason,
)
except Exception:
pass
# 丢弃时,尽量关闭详情,避免停留在详情页
try:
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv(
"参与", "basic_join_decision:已关闭详情", action="close_detail"
)
except Exception:
pass
# 如果允许切换直播间,筛选不通过直接切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
analyser._log_kv(
"参与", "basic_join_decision:丢弃后切换直播间", reason=reason
)
except Exception:
pass
# 这里需要实现切换直播间的逻辑,由于代码太长,这里暂时简化
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(丢弃)",
elapsed_seconds=round(elapsed, 2),
result=False,
)
return False
# 参与抽奖
try:
analyser._log_kv("参与", "basic_join_decision:开始参与抽奖")
except Exception:
pass
from .fudai_attend import attend_choujiang
result = attend_choujiang(analyser)
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(参与抽奖)",
elapsed_seconds=round(elapsed, 2),
result=result,
)
return result
@@ -0,0 +1,483 @@
"""fudai_filter_pkg.should_skip - 福袋是否应跳过的总决策。
包含 should_skip_fudai_by_config:基于 config.json 中的价值/参与人数/
观看任务/黑白名单等多维度配置,决定是否跳过当前福袋。
返回 (skip, reason):
- skip=True 应跳过,reason 说明原因(low_value / blacklist / ...)
- skip=False 应继续参与,reason="ok"
"""
from __future__ import annotations
import re
import time
from typing import Any, Tuple
from .helpers import (
_is_short_countdown_text,
check_contain,
is_watch_task_fudai,
)
def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]:
"""根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。
返回:
(skip, reason) 其中 reason 为简单文字原因,便于日志查看。
"""
start_time = time.time()
# 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if not needswitch:
try:
analyser._log_kv(
"筛选",
"单间模式:忽略所有福袋阈值配置,直接参与",
needswitch=0,
)
except Exception:
pass
return False, "single_room_mode"
if not isinstance(detail, tuple) or len(detail) < 6:
return False, "detail_tuple_invalid"
content = str(detail[0] or "")
# 优先检查是否为"观看X分钟"类任务:若是,直接放弃
if is_watch_task_fudai(content):
try:
analyser._log_kv(
"筛选",
"检测到'观看X分钟'类任务,自动放弃",
content=content[:80] if content else "",
reason="watch_task_detected",
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"筛选",
"should_skip_fudai_by_config完成(观看任务)",
elapsed_seconds=round(elapsed, 2),
)
return True, "watch_task_detected"
time_text = str(detail[1] or "")
try:
participants = int(detail[2] or 0)
except Exception:
participants = 0
try:
copies = int(detail[3] or 0)
except Exception:
copies = 0
try:
prize_value_yuan = float(detail[4] or 0.0)
except Exception:
prize_value_yuan = 0.0
cd_start, cd_end = None, None
if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2:
cd_start, cd_end = detail[5][0], detail[5][1]
now = time.time()
remain_seconds = None
try:
if isinstance(cd_end, (int, float)) and cd_end > now:
remain_seconds = float(cd_end - now)
try:
analyser._log_kv(
"筛选",
"倒计时计算成功",
cd_end=cd_end,
now=now,
剩余秒数=remain_seconds,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"倒计时计算失败或已过期",
cd_end=cd_end,
now=now,
cd_end类型=type(cd_end).__name__,
cd_end大于now=(
bool(isinstance(cd_end, (int, float)) and cd_end > now)
if isinstance(cd_end, (int, float))
else False
),
)
except Exception:
pass
except Exception as e:
remain_seconds = None
try:
analyser._log_kv(
"筛选",
"倒计时计算异常",
异常=str(e),
异常类型=type(e).__name__,
)
except Exception:
pass
# 读取配置阈值
try:
min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0)
except Exception:
min_value = 0.0
try:
min_participants = int(getattr(analyser, "min_participants", 0) or 0)
except Exception:
min_participants = 0
try:
max_participants = int(getattr(analyser, "max_participants", 0) or 0)
except Exception:
max_participants = 0
skip_if_gt = 0 # Initialize before try block
try:
skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0)
except Exception:
skip_if_gt = 0
skip_if_lt = 0 # Initialize before try block
try:
skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0)
except Exception:
skip_if_lt = 0
# 获取按钮文本,用于记录
button_text = str(getattr(analyser, "button_text_raw", "") or "").strip()
# 记录所有配置值和实际值,便于调试
try:
analyser._log_kv(
"筛选",
"should_skip_fudai_by_config 开始检查",
配置_最小价值=min_value,
配置_最小参与人数=min_participants,
配置_最大参与人数=max_participants,
配置_倒计时大于秒数=skip_if_gt,
配置_倒计时小于秒数=skip_if_lt,
实际_价值=prize_value_yuan,
实际_参与人数=participants,
实际_份数=copies,
实际_剩余秒数=int(remain_seconds) if remain_seconds is not None else None,
实际_内容=content[:60] if content else "",
按钮文本=button_text if button_text else "未识别",
)
except Exception:
pass
# 并行检查所有筛选条件,收集所有不符合的原因
skip_reasons = []
# 1) 价值过滤
if min_value > 0:
if prize_value_yuan > 0:
if prize_value_yuan < min_value:
skip_reasons.append(f"value_lt_{min_value}")
try:
analyser._log_kv(
"筛选",
"价值过滤:不符合(价值过低)",
实际价值=prize_value_yuan,
配置最小价值=min_value,
判断条件=f"{prize_value_yuan} < {min_value} = True",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"价值过滤:通过",
实际价值=prize_value_yuan,
配置最小价值=min_value,
判断条件=f"{prize_value_yuan} >= {min_value} = True",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"价值过滤:跳过(未识别到价值)",
实际价值=prize_value_yuan,
)
except Exception:
pass
# 2) 参与人数过滤
if min_participants > 0:
if participants > 0:
if participants < min_participants:
skip_reasons.append(f"participants_lt_{min_participants}")
try:
analyser._log_kv(
"筛选",
"参与人数过滤:不符合(小于最小值)",
实际参与人数=participants,
配置最小参与人数=min_participants,
判断条件=f"{participants} < {min_participants} = True",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"参与人数过滤:通过(最小值检查)",
实际参与人数=participants,
配置最小参与人数=min_participants,
判断条件=f"{participants} >= {min_participants} = True",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"参与人数过滤:跳过(未识别到参与人数)",
实际参与人数=participants,
)
except Exception:
pass
if max_participants > 0:
if participants > 0:
if participants > max_participants:
skip_reasons.append(f"participants_gt_{max_participants}")
try:
analyser._log_kv(
"筛选",
"参与人数过滤:不符合(大于最大值)",
实际参与人数=participants,
配置最大参与人数=max_participants,
判断条件=f"{participants} > {max_participants} = True",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"参与人数过滤:通过(最大值检查)",
实际参与人数=participants,
配置最大参与人数=max_participants,
判断条件=f"{participants} <= {max_participants} = True",
)
except Exception:
pass
# 3) 倒计时过滤
# 3.1) 倒计时小于阈值:直接丢弃(不参与)
if skip_if_lt > 0:
if remain_seconds is not None:
if remain_seconds < skip_if_lt:
skip_reasons.append(f"countdown_lt_{skip_if_lt}")
try:
analyser._log_kv(
"筛选",
"倒计时过滤:不符合(剩余秒数小于阈值)",
实际剩余秒数=int(remain_seconds),
配置阈值秒数=skip_if_lt,
判断条件=f"{remain_seconds} < {skip_if_lt} = True",
)
except Exception:
pass
# 3.2) 倒计时大于阈值:不参与(但如果价值达到高价值阈值,可以预约)
if skip_if_gt > 0:
if remain_seconds is not None:
if remain_seconds > skip_if_gt:
skip_reasons.append(f"countdown_gt_{skip_if_gt}")
try:
analyser._log_kv(
"筛选",
"倒计时过滤:不符合(剩余秒数大于阈值)",
实际剩余秒数=int(remain_seconds),
配置阈值秒数=skip_if_gt,
判断条件=f"{remain_seconds} > {skip_if_gt} = True",
说明="如果价值达到高价值阈值,basic_join_decision 会记录预约",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"倒计时过滤:通过",
实际剩余秒数=int(remain_seconds),
配置阈值秒数=skip_if_gt,
判断条件=f"{remain_seconds} <= {skip_if_gt} = True",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"倒计时过滤:跳过(未识别到倒计时或倒计时已过期)",
剩余秒数=remain_seconds,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)",
配置阈值秒数=skip_if_gt,
)
except Exception:
pass
# 4) 内容关键词过滤(复用 check_contain 逻辑)
content_check_result = check_contain(analyser, content)
if content_check_result:
skip_reasons.append("content_not_wanted")
try:
analyser._log_kv(
"筛选",
"内容关键词过滤:不符合",
内容=content[:60] if content else "",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"内容关键词过滤:通过",
内容=content[:60] if content else "",
)
except Exception:
pass
# 5) 按钮文本过滤:检查按钮是否显示无法参与、还需看播等状态
try:
if button_text:
# 检查是否包含无法参与的关键词
unable_to_participate_keywords = [
"无法参与",
"不能参与",
"不可参与",
"还没到时间",
"活动已结束",
"活动结束",
"已结束",
"已过期",
"已截止",
"时长不足",
]
watch_required_keywords = [
"还需看播",
"观看",
"看播",
"观看时长",
"观看分钟",
]
# 检查无法参与关键词
for keyword in unable_to_participate_keywords:
if keyword in button_text:
skip_reasons.append("button_unable_to_participate")
try:
analyser._log_kv(
"筛选",
"按钮文本过滤:不符合(无法参与)",
按钮文本=button_text,
匹配关键词=keyword,
)
except Exception:
pass
break
# 检查观看要求关键词
for keyword in watch_required_keywords:
if keyword in button_text:
skip_reasons.append("button_watch_required")
try:
analyser._log_kv(
"筛选",
"按钮文本过滤:不符合(观看任务)",
按钮文本=button_text,
匹配关键词=keyword,
)
except Exception:
pass
break
if not any(reason.startswith("button_") for reason in skip_reasons):
try:
analyser._log_kv(
"筛选",
"按钮文本过滤:通过",
按钮文本=button_text,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"筛选",
"按钮文本过滤:跳过(未识别到按钮文本)",
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"筛选",
"按钮文本过滤:异常",
异常=str(e),
异常类型=type(e).__name__,
)
except Exception:
pass
# 如果有任何不符合的条件,就跳过
if skip_reasons:
elapsed = time.time() - start_time
try:
analyser._log_kv(
"筛选",
"should_skip_fudai_by_config完成(不符合条件,跳过)",
不符合原因=skip_reasons,
总原因数=len(skip_reasons),
elapsed_seconds=round(elapsed, 2),
)
except Exception:
pass
# 返回第一个原因作为主要原因
return True, skip_reasons[0]
# 所有条件都通过
try:
analyser._log_kv(
"筛选",
"should_skip_fudai_by_config 通过(所有检查项均通过)",
content=content[:60] if content else "",
participants=participants,
copies=copies,
value_yuan=prize_value_yuan,
remain_seconds=int(remain_seconds) if remain_seconds is not None else None,
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"筛选",
"should_skip_fudai_by_config完成(通过)",
elapsed_seconds=round(elapsed, 2),
)
return False, "ok"
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,43 @@
"""douyin_fudai_core_pkg - 福袋核心薄壳子包。
原 douyin/fudai/douyin_fudai_core.py 的工具/兼容部分搬到本子包:
- ocr_executor _FudaiOcrExecutorState / _get_fudai_ocr_executor / _fudai_ocr_executor_state
- thin_wrappers 11 个 [兼容] 薄壳 forwarding 函数
巨型 get_fudai_contain (2062 行) 留在原文件 douyin_fudai_core.py 不变。
外部 ``from douyin.fudai.douyin_fudai_core import attend_choujiang`` 等
完全兼容(原文件 from 子包 import 后自动暴露)。
"""
from .ocr_executor import (
_FudaiOcrExecutorState,
_fudai_ocr_executor_state,
_get_fudai_ocr_executor,
)
from .thin_wrappers import (
attend_choujiang,
basic_join_decision,
check_have_reward_notice_confirm,
check_in_order_confirm_page,
check_lucky_draw_result,
get_reward,
is_watch_task_fudai,
should_skip_fudai_by_config,
_is_short_countdown_text,
)
__all__ = [
"_FudaiOcrExecutorState",
"_fudai_ocr_executor_state",
"_get_fudai_ocr_executor",
"attend_choujiang",
"check_lucky_draw_result",
"check_have_reward_notice_confirm",
"check_in_order_confirm_page",
"get_reward",
"is_watch_task_fudai",
"_is_short_countdown_text",
"should_skip_fudai_by_config",
"basic_join_decision",
]
@@ -0,0 +1,46 @@
"""douyin_fudai_core_pkg.ocr_executor - OCR 线程池复用。
避免每次 OCR 都创建/销毁 ThreadPoolExecutor 的开销。
线程数变化时安全销毁旧池并新建。
"""
from __future__ import annotations
import threading
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
class _FudaiOcrExecutorState:
def __init__(self) -> None:
self.executor: Optional[ThreadPoolExecutor] = None
self.workers: int = 0
self.lock = threading.Lock()
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
def _get_fudai_ocr_executor(optimal_workers: int) -> ThreadPoolExecutor:
"""获取复用的 OCR 线程池;如线程数变化则重建。"""
state = _fudai_ocr_executor_state
with state.lock:
if state.executor and state.workers == optimal_workers:
return state.executor
# 若线程数变化,安全关闭旧池
if state.executor:
try:
state.executor.shutdown(wait=False, cancel_futures=True)
except RuntimeError:
pass
state.executor = None
executor = ThreadPoolExecutor(max_workers=optimal_workers)
state.executor = executor
state.workers = optimal_workers
return executor
@@ -0,0 +1,65 @@
"""douyin_fudai_core_pkg.thin_wrappers - 11 个兼容性薄壳。
原 douyin/fudai/douyin_fudai_core.py 末尾 11 个 forwarding 函数全是
``[兼容] 已迁移到 douyin.fudai.core.X`` 风格。本子模块集中存放,
保持外部 ``from douyin.fudai.douyin_fudai_core import attend_choujiang``
等仍然可用。
"""
from __future__ import annotations
def attend_choujiang(analyser) -> bool: # noqa: F811 — 兼容性 re-export
"""[兼容] 已迁移到 douyin.fudai.core.fudai_attend。"""
from douyin.fudai.core.fudai_attend import attend_choujiang as _impl
return _impl(analyser)
def check_lucky_draw_result(analyser): # noqa: F811 — 兼容性 re-export
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
from douyin.fudai.core.fudai_result_checker import (
check_lucky_draw_result as _impl,
)
return _impl(analyser)
def check_have_reward_notice_confirm(analyser) -> bool: # noqa: F811
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
from douyin.fudai.core.fudai_result_checker import (
check_have_reward_notice_confirm as _impl,
)
return _impl(analyser)
def check_in_order_confirm_page(analyser) -> bool: # noqa: F811
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
from douyin.fudai.core.fudai_result_checker import (
check_in_order_confirm_page as _impl,
)
return _impl(analyser)
def get_reward(analyser, reward_y: int = 0) -> None: # noqa: F811
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
from douyin.fudai.core.fudai_result_checker import get_reward as _impl
return _impl(analyser, reward_y=reward_y)
def is_watch_task_fudai(content: str) -> bool: # noqa: F811 — 兼容性 re-export
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
from douyin.fudai.core.fudai_filter import is_watch_task_fudai as _impl
return _impl(content)
def _is_short_countdown_text(time_text: str) -> bool: # noqa: F811
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
from douyin.fudai.core.fudai_filter import (
_is_short_countdown_text as _impl,
)
return _impl(time_text)
def should_skip_fudai_by_config(analyser, detail): # noqa: F811 — 兼容性 re-export
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
from douyin.fudai.core.fudai_filter import (
should_skip_fudai_by_config as _impl,
)
return _impl(analyser, detail)
def basic_join_decision(analyser, detail): # noqa: F811 — 兼容性 re-export
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
from douyin.fudai.core.fudai_filter import basic_join_decision as _impl
return _impl(analyser, detail)
+6 -6
View File
@@ -16,29 +16,29 @@ Exports:
"""
# 从各子模块导入所有公共API
from fudai_detail_modules.fudai_detail_operations import (
from douyin.fudai.core.fudai_detail_operations import (
close_fudai_detail,
ensure_fudai_detail_open,
)
from fudai_detail_modules.fudai_detail_room_title import (
from douyin.fudai.core.fudai_detail_room_title import (
read_live_room_title_core,
)
from fudai_detail_modules.fudai_detail_reader import (
from douyin.fudai.core.fudai_detail_orchestrator import (
read_fudai_detail_once,
read_fudai_detail_with_retries,
)
from fudai_detail_modules.fudai_detail_validator import (
from douyin.fudai.core.fudai_detail_validator import (
validate_fudai_detail,
)
from fudai_detail_modules.fudai_detail_utils import (
from douyin.fudai.core.fudai_detail_utils import (
is_abnormal_time_value,
)
from fudai_detail_modules.fudai_detail_coupon_detection import (
from douyin.fudai.core.fudai_detail_coupon_detection import (
is_wrong_coupon_popup,
)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,31 @@
"""douyin_fudai_finder_pkg - 福袋查找器子包。
原 douyin/fudai/douyin_fudai_finder.py 拆成 6 个子模块:
- image_acquirer FudaiImageAcquirer(图像获取与预处理)
- detector FudaiDetector(多算法识别,最大头 930 行)
- click_executor FudaiClickExecutor(点击执行)
- detail_verifier FudaiDetailVerifier(详情页打开验证)
- finder FudaiFinder(4 个组件的组合入口)
- optimized_entry check_have_fudai_with_ready_screenshot_optimized(顶层函数)
外部 import 路径不变:
``from douyin.fudai.douyin_fudai_finder import FudaiFinder`` 仍可用
(原文件改成 re-export shim)。
"""
from .image_acquirer import FudaiImageAcquirer
from .detector import FudaiDetector
from .click_executor import FudaiClickExecutor
from .detail_verifier import FudaiDetailVerifier
from .finder import FudaiFinder
from .optimized_entry import check_have_fudai_with_ready_screenshot_optimized
__all__ = [
"FudaiImageAcquirer",
"FudaiDetector",
"FudaiClickExecutor",
"FudaiDetailVerifier",
"FudaiFinder",
"check_have_fudai_with_ready_screenshot_optimized",
]
@@ -0,0 +1,220 @@
"""douyin_fudai_finder_pkg.click_executor - 点击执行器。
FudaiClickExecutor:根据 detector 给出的坐标执行点击,
带 Y 偏移、防抖、重试等业务策略。
"""
from __future__ import annotations
# pylint: disable=E1101
import os
import time
from typing import Any, Dict, Optional, Tuple
from PIL import Image
from douyin.core import path_config
# OCR 预处理接口
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
# 调试图像管理器(用于保存调试截图)
try:
from douyin.handlers import douyin_screenshot_manager
except ImportError:
douyin_screenshot_manager = None
class FudaiClickExecutor:
"""福袋点击执行器:负责点击福袋图标"""
def __init__(self, analyser: Any):
self.analyser = analyser
self._init_resolution()
def _init_resolution(self):
"""初始化分辨率信息"""
try:
self.rx = int(getattr(self.analyser, "resolution_ratio_x", 1080) or 1080)
self.ry = int(getattr(self.analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
self.rx, self.ry = 1080, 2400
def click(self, fudai_x: int) -> bool:
"""点击福袋图标(点击前会检查是否是红包,避免误点)
参数:
fudai_x: 福袋图标的X坐标(1080基准)
返回:
是否点击成功
"""
start_time = time.time()
# 计算点击坐标
base_y = 403 # 与检测时使用的同一水平线
click_x = int(fudai_x * self.rx / 1080)
click_y = int(base_y * self.ry / 2400)
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"开始",
fudai_x=fudai_x,
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 点击前检查:避免误点红包
try:
# 检查是否有红包弹窗
from douyin.other import douyin_popups
has_redpacket = douyin_popups.check_shopping_redpacket_popup(self.analyser)
if has_redpacket:
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"跳过(检测到红包弹窗)",
fudai_x=fudai_x,
note="检测到红包弹窗,避免误点红包",
)
except Exception:
pass
return False
# 快速检查点击位置附近是否有红包特征(通过OCR)
# 检查点击位置上方和下方的区域,看是否有红包关键词
try:
# 截图点击位置附近的区域(扩大范围以包含可能的红包文字)
check_x1 = max(0, click_x - 150)
check_x2 = min(self.rx, click_x + 150)
check_y1 = max(0, click_y - 200)
check_y2 = min(self.ry, click_y + 200)
# 转换为1080基准坐标
check_x1_base = int(check_x1 * 1080 / self.rx)
check_y1_base = int(check_y1 * 2400 / self.ry)
check_x2_base = int(check_x2 * 1080 / self.rx)
check_y2_base = int(check_y2 * 2400 / self.ry)
# 截图检查区域
self.analyser.cut_pic(
check_x1_base,
check_y1_base,
check_x2_base,
check_y2_base,
"",
"檢查紅包特徵",
)
# OCR识别
name_chk = preprocess_for_ocr(self.analyser, "檢查紅包特徵")
check_text = str(
self.analyser.operation.analyse_pic_word(name_chk, 0) or ""
).strip()
# 检查是否包含红包关键词
redpacket_keywords = (
"最高金额",
"开抢",
"邀你抢",
"抢红包",
"购物红包",
"手气红包",
)
if check_text and any(kw in check_text for kw in redpacket_keywords):
matched_keywords = [
kw for kw in redpacket_keywords if kw in check_text
]
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"跳过(检测到红包特征)",
fudai_x=fudai_x,
matched_keywords=matched_keywords,
check_text_preview=check_text[:50],
note="点击位置附近检测到红包特征文字,避免误点红包",
)
except Exception:
pass
return False
except Exception as e:
# OCR检查失败不影响点击,继续执行
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"红包特征检查异常,继续点击",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
except Exception:
# 红包检查失败不影响点击,继续执行
pass
# 执行点击
try:
device_id = getattr(self.analyser, "device_id", "")
self.analyser.operation.click(device_id, click_x, click_y)
# 点击后等待足够时间让详情页加载(避免连续点击导致详情页被关闭)
# 默认等待1.0秒,可通过 GUI 配置
click_wait_time = float(
getattr(self.analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
if click_wait_time < 1.0:
click_wait_time = 1.0 # 最小1.0秒
self.analyser.operation.delay(click_wait_time)
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"成功",
elapsed_ms=round(elapsed, 2),
wait_seconds=click_wait_time,
)
except Exception:
pass
return True
except Exception:
# 回退到analyser.click
try:
self.analyser.click(fudai_x, base_y)
# 回退模式也需要等待
click_wait_time = float(
getattr(self.analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
if click_wait_time < 1.0:
click_wait_time = 1.0
self.analyser.operation.delay(click_wait_time)
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"成功(回退模式)",
elapsed_ms=round(elapsed, 2),
wait_seconds=click_wait_time,
)
except Exception:
pass
return True
except Exception:
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 点击",
"失败",
elapsed_ms=round(elapsed, 2),
error="点击异常",
)
except Exception:
pass
return False
@@ -0,0 +1,237 @@
"""douyin_fudai_finder_pkg.detail_verifier - 详情页打开验证。
FudaiDetailVerifier:点击后验证是否成功进入福袋详情页,
失败时反馈给上层重试或换策略。
"""
from __future__ import annotations
# pylint: disable=E1101
import os
import time
from typing import Any, Dict, Optional, Tuple
from PIL import Image
from douyin.core import path_config
# OCR 预处理接口
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
# 调试图像管理器(用于保存调试截图)
try:
from douyin.handlers import douyin_screenshot_manager
except ImportError:
douyin_screenshot_manager = None
class FudaiDetailVerifier:
"""福袋详情页验证器:验证是否成功打开详情页"""
def __init__(self, analyser: Any):
self.analyser = analyser
def verify(self, max_wait_seconds: float = 2.0) -> bool:
"""验证是否成功打开福袋详情页
参数:
max_wait_seconds: 最大等待时间(秒)
返回:
是否成功打开详情页
"""
start_time = time.time()
try:
# 等待界面加载(增加等待时间,确保详情页完全加载)
# 点击后已经等待了2.5秒,这里再等待0.8秒,总共约3.3秒
verify_initial_wait = float(
getattr(self.analyser, "fudai_verify_initial_wait_seconds", 0.8) or 0.8
)
if verify_initial_wait < 0.5:
verify_initial_wait = 0.5 # 最小0.5秒
self.analyser.operation.delay(verify_initial_wait)
# 多次检查,直到超时或检测到详情页
check_interval = 0.3
checks = 0
max_checks = int(max_wait_seconds / check_interval) + 1
while checks < max_checks:
# 刷新截图
try:
self.analyser.operation.get_screenshot(
self.analyser.device_id, use_service=False
)
except Exception:
pass
# 检查是否在详情页(已移除任务数量检测,仅使用OCR检测)
# 额外检测:在指定区域检测"邀你抢红包"文字
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
try:
y_pianyi = int(getattr(self.analyser, "y_pianyi", 0) or 0)
# 保存完整截图并标注OCR区域
try:
from douyin.handlers import douyin_screenshot_manager
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(self.analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(self.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:
self.analyser._log_kv(
"[调试图像]",
"OCR识别前保存完整截图(验证邀你抢红包区域)",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
# cut_pic 方法内部会根据分辨率自动缩放,所以直接传入基准坐标
self.analyser.cut_pic(
238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi
)
name_invite = preprocess_for_ocr(
self.analyser, "验证邀你抢红包区域"
)
ocr_text = str(
self.analyser.operation.analyse_pic_word(name_invite, 0) or ""
)
# 如果模式0未识别到,尝试模式1
enable_ocr_mode1 = bool(
getattr(self.analyser, "enable_ocr_mode1", False)
)
if enable_ocr_mode1 and (
not ocr_text
or not any(
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
)
):
name_invite1 = preprocess_for_ocr(
self.analyser, "验证邀你抢红包区域"
)
ocr_text = str(
self.analyser.operation.analyse_pic_word(name_invite1, 1)
or ""
)
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
# 关键词包括:"邀你抢红包"、"邀你抢手气红包"、"邀你抢"等
redpacket_keywords = (
"邀你抢红包",
"邀你抢手气红包",
"邀你抢",
"抢红包",
"抢手气",
)
if ocr_text and any(kw in ocr_text for kw in redpacket_keywords):
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 验证",
"成功打开详情页(检测到邀你抢红包)",
elapsed_ms=round(elapsed, 2),
checks=checks + 1,
ocr_text=ocr_text[:50],
)
except Exception:
pass
# 额外等待,确保参与按钮加载完成
# 验证时只检测了详情页是否打开,但参与按钮可能需要额外时间加载
button_wait_time = float(
getattr(
self.analyser, "fudai_button_load_wait_seconds", 0.5
)
or 0.5
)
if button_wait_time > 0:
try:
self.analyser.operation.delay(button_wait_time)
except Exception:
time.sleep(button_wait_time)
# 设置标志,表示详情页已经验证过,后续读取详情时可以缩短等待时间
# 同时设置重试标志,如果任务数为0可以重试一次
try:
self.analyser._fudai_detail_verified = True
self.analyser._fudai_detail_verified_retry = True
except Exception:
pass
return True
except Exception:
# OCR检测失败不影响其他检测方式
pass
checks += 1
if checks < max_checks:
self.analyser.operation.delay(check_interval)
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 验证",
"未检测到详情页",
elapsed_ms=round(elapsed, 2),
checks=checks,
)
except Exception:
pass
return False
except Exception as e:
elapsed = (time.time() - start_time) * 1000
try:
self.analyser._log_kv(
"[福袋查找] 验证",
"异常",
elapsed_ms=round(elapsed, 2),
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return False
Loaded 100 of 297 files, more files were not shown because too many files have changed in this diff. Show more