Compare commits

...
327 Commits
Author SHA1 Message Date
Your Name ec2f044d8c docs(webui): 制定大文件拆分计划 2026-05-31 10:32:56 +08:00
Your Name 18b75ceda4 refactor(gui): 合并顶部 Y 偏移到设备栏组件 2026-05-31 10:08:02 +08:00
Your Name e9b003f906 refactor(gui): save_logging_config 内置到 left_config_area (169 → 159) 2026-05-30 20:13:22 +08:00
Your Name 95459607dc refactor(gui): format_gui_log_line 内置到 log_pipeline,主文件保留兼容 re-export (178 → 169) 2026-05-30 20:08:35 +08:00
Your Name 0d4796744d docs(specs): gui_app 拆分最终成果(5476 → 178, -96.7%) 2026-05-30 20:04:15 +08:00
Your Name 1cd94e9705 refactor(gui): 删除已不用的 logging/re/_LOGGER + RIGHT/Y 常量 (183 → 178) 2026-05-30 20:01:36 +08:00
Your Name 8c2d93a79f refactor(gui): 删除已不再被 main 使用的 log_color_config fallback 段 (201 → 183) 2026-05-30 19:49:37 +08:00
Your Name 92d60f9931 refactor(gui): 清理 16 个未使用的 _impl 别名 import (223 → 201) 2026-05-30 19:45:27 +08:00
Your Name 29b9788371 refactor(gui): 清理 12 个未使用的 import (239 → 223) 2026-05-30 19:41:14 +08:00
Your Name 7eeaab9a6e refactor(gui): 抽右侧主区域(notebook + 9 tabs + actions + pump_logs)到 components/right_main_area (348 → 239) 2026-05-30 19:30:11 +08:00
Your Name 089cb32e1c refactor(gui): 抽左侧配置区(PanedWindow + 7 Tabs + load/save IO)到 components/left_config_area (389 → 348) 2026-05-30 19:18:43 +08:00
Your Name a06ece4e15 refactor(gui): _open_realtime_viewer 直接定义,删除 forward-declare 模式 (396 → 389) 2026-05-30 19:13:52 +08:00
Your Name 6cebed599d refactor(gui): _async_refresh_preview 闭包内联到 periodic_refreshers (398 → 396) 2026-05-30 19:09:37 +08:00
Your Name da5e000006 refactor(gui): 抽 root window + ttkbootstrap fallback 到 components/root_window (415 → 398) 2026-05-30 19:04:50 +08:00
Your Name 065d73ff9a refactor(gui): _open_realtime_viewer lambda 去重(2 处 → 1 个本地变量) (419 → 415) 2026-05-30 19:00:35 +08:00
Your Name adbd8a2d6e refactor(gui): theme_getter lambda 去重(3 处 → 1 个本地变量) (418 → 419) 2026-05-30 18:54:20 +08:00
Your Name 1235c5910f docs(specs): gui_app 拆分最终成果(5476 → 418, -92%) 2026-05-30 18:49:55 +08:00
Your Name 84c5731cc3 refactor(gui): 抽 on_line + Runner + log_writer 到 components/log_pipeline (440 → 418) 2026-05-30 18:47:36 +08:00
Your Name 8e0ae9396d refactor(gui): actions_log + ocr_results 内置到 simple_tabs (450 → 440) 2026-05-30 18:42:26 +08:00
Your Name a6648c5ce8 refactor(gui): reservation/high_value 用 setup_text_tab_with_refresh 复用 (452 → 450) 2026-05-30 18:37:12 +08:00
Your Name f75d3ae368 refactor(gui): refresh_stats 内置到 setup_stats_tab (470 → 452) 2026-05-30 18:33:21 +08:00
Your Name d9920f1cee refactor(gui): 抽运行日志 Tab UI 到 components/log_tab (487 → 470) 2026-05-30 18:29:00 +08:00
Your Name e763cdc302 refactor(gui): 删除已不用的 BOTTOM/W 兜底常量 (492 → 487) 2026-05-30 18:24:34 +08:00
Your Name fd694f8ce5 refactor(gui): 清理 6 个未使用的 _impl 别名 import (498 → 492) 2026-05-30 18:17:58 +08:00
Your Name 547228fa2d refactor(gui): 清理未使用的 gui_core_pkg + wifi_adb_scan import (508 → 498) 2026-05-30 18:03:30 +08:00
Your Name e7d848023c refactor(gui): 清理 gui_core 中已不再直接用的 8 个 import (518 → 508) 2026-05-30 17:59:46 +08:00
Your Name a1562a513d refactor(gui): 抽顶部常驻按钮区到 components/top_buttons (527 → 518) 2026-05-30 17:55:20 +08:00
Your Name b8f2806ffc refactor(gui): _main_nb 直接引用 show_actions_var 等,删除 3 行 unpack (530 → 527) 2026-05-30 17:48:34 +08:00
Your Name 9642b7b0f8 refactor(gui): 抽顶部设备栏到 components/top_device_bar (607 → 530) 2026-05-30 17:45:01 +08:00
Your Name 9896eb676a refactor(gui): 抽周期性刷新+关闭处理到 components/periodic_refreshers (630 → 607) 2026-05-30 17:40:58 +08:00
Your Name e0c68883dd refactor(gui): 清理 4 个未使用的 stdlib import (634 → 630) 2026-05-30 17:37:12 +08:00
Your Name e0cad29daf refactor(gui): 清理已抽走 var 后的死注释段 (677 → 634) 2026-05-30 17:33:14 +08:00
Your Name 6a8296cab1 refactor(gui): 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var) (802 → 677) 2026-05-30 17:30:05 +08:00
Your Name 3626e9cf6f refactor(gui): save_logging_config 复用 _vars_,删除子集 dict (825 → 802) 2026-05-30 17:26:31 +08:00
Your Name 29d930b1de refactor(gui): get_params 复用 _vars_ + device_var,删除子集 dict (855 → 825) 2026-05-30 17:23:43 +08:00
Your Name df758cf224 refactor(gui): config_io 复用 _vars_ 全集,删除 _config_io_vars 子集字典 (982 → 855) 2026-05-30 17:20:52 +08:00
Your Name 47865f5dfa refactor(gui): setup_*_tab 调用直接传 _vars_ 全集 (1110 → 982) 2026-05-30 17:17:55 +08:00
Your Name 9744b75878 refactor(gui): 抽 127 个 Var 声明到 components/config_vars 工厂 (1373 → 1110) 2026-05-30 17:14:39 +08:00
Your Name 200f3a53fc docs(specs): 更新 gui_app 拆分最终成果(5476 → 1373, -75%) 2026-05-30 17:09:08 +08:00
Your Name 7a840120b3 refactor(gui): 抽底部操作按钮区到 components/action_buttons (1417 → 1373) 2026-05-30 17:06:36 +08:00
Your Name e314161b6c refactor(gui): 抽右侧主 Notebook + 实时工具栏到 components/main_notebook (1444 → 1417) 2026-05-30 17:02:35 +08:00
Your Name 3a7a7a3b75 refactor(gui): 抽 keywords_tab UI 到 components/keywords_tab (1461 → 1444) 2026-05-30 16:58:53 +08:00
Your Name 8575f04ab9 refactor(gui): 抽截图预览 Tab 整段 UI 到 components/preview_tab (1537 → 1461) 2026-05-30 16:54:53 +08:00
Your Name 728ef3cd79 refactor(gui): 5 个简单文本 Tab 用 simple_tabs 模板复用 (1571 → 1537) 2026-05-30 16:49:01 +08:00
Your Name 32e374e2c2 refactor(gui): 抽行为日志工具栏到 components/actions_log_toolbar (1649 → 1571) 2026-05-30 16:45:02 +08:00
Your Name aa0f4e05f2 refactor(gui): 抽中奖记录 Tab 整段 UI 到 components/win_record_tab (1739 → 1649) 2026-05-30 16:40:49 +08:00
Your Name 5e3015f59b refactor(gui): 抽日志搜索工具栏到 components/log_search_toolbar (1813 → 1739) 2026-05-30 16:36:43 +08:00
Your Name dc1744a93f refactor(gui): 重排 log_text 创建到搜索栏之前(为下一步抽搜索栏铺路) 2026-05-30 16:33:00 +08:00
Your Name b686a4e3d5 refactor(gui): 抽 log_text 颜色配置到 components/log_text_colors (1878 → 1813) 2026-05-30 16:29:27 +08:00
Your Name 29cef2c578 refactor(gui): 抽 realtime_tab UI 创建到 components/realtime_tab (2037 → 1878) 2026-05-30 16:25:51 +08:00
Your Name e784efd5f8 refactor(gui): 抽 filter_tab UI 创建到 components/filter_tab (2122 → 2037) 2026-05-30 16:18:29 +08:00
Your Name 6c7bbf0945 refactor(gui): 抽 run_tab UI 创建到 components/run_tab (2192 → 2122) 2026-05-30 16:15:24 +08:00
Your Name fe27063913 refactor(gui): 抽 reservation_tab UI 创建到 components/reservation_tab (2334 → 2192) 2026-05-30 16:11:47 +08:00
Your Name 3f04bb23c2 refactor(gui): 抽 yanghao_tab UI 创建到 components/yanghao_tab (2456 → 2334) 2026-05-30 16:06:40 +08:00
Your Name bcb0e363d1 refactor(gui): 抽 logging_tab UI 创建到 components/logging_tab (2656 → 2456) 2026-05-30 15:54:46 +08:00
Your Name b447b6a6a4 refactor(gui): 抽 debug_tab UI 创建到 components/debug_tab (3052 → 2656) 2026-05-30 15:50:58 +08:00
Your Name 3ac8664817 docs(specs): 更新 gui_app 拆分最终成果(5476 → 3052, -44.3%) 2026-05-30 15:42:56 +08:00
Your Name 6bac014c3d refactor(gui): 抽 load_config_to_ui + save_ui_to_config 到 components/config_io (3538 → 3052) 2026-05-30 15:41:27 +08:00
Your Name 3d433080c2 docs(specs): 更新 gui_app 拆分最终成果(5476 → 3538, -35.4%) 2026-05-30 15:27:44 +08:00
Your Name f6d382b0e7 refactor(gui): 抽 get_params 到 components/run_params_builder (3563 → 3538) 2026-05-30 15:26:17 +08:00
Your Name 2a05be2319 refactor(gui): 抽 save_logging_config 到 components/logging_config_io (3590 → 3563) 2026-05-30 15:22:29 +08:00
Your Name f9839f3dee docs(specs): 补充 gui_app 拆分实际成果(5476 → 3590, -34%) 2026-05-30 15:18:13 +08:00
Your Name 97935d9c48 refactor(gui): 抽 _generic_search_widget 到 components/text_search (3669 → 3590) 2026-05-30 15:16:42 +08:00
Your Name 64c210dd5a refactor(gui): 抽 refresh_run_log 到 components/run_log_view (3715 → 3669) 2026-05-30 15:12:38 +08:00
Your Name 68d1224b53 refactor(gui): 抽 _on_scan_one_click + _handle_scan_result 到 components/wifi_adb_one_click_scan (3775 → 3715) 2026-05-30 15:08:35 +08:00
Your Name 92d524297b refactor(gui): 抽预览 Tab 全部 8 个动作到 components/preview_view (3891 → 3775) 2026-05-30 15:03:45 +08:00
Your Name 59ebe8c1e7 refactor(gui): 抽 win_record Tab 全部 7 个动作到 components/win_record_view (4044 → 3891) 2026-05-30 14:53:11 +08:00
Your Name a7ef92fc7c refactor(gui): 抽 pump_logs 到 components/log_pump (4117 → 4044) 2026-05-30 14:37:03 +08:00
Your Name c5df7a05d2 refactor(gui): 抽 update_ocr_results 到 components/ocr_results_view (4148 → 4117) 2026-05-30 14:30:42 +08:00
Your Name b3380042b8 refactor(gui): 抽 _try_reconnect_last_wifi 到 components/wifi_adb_reconnect (4268 → 4148) 2026-05-30 14:24:19 +08:00
Your Name 4993fad004 refactor(gui): 抽 _open_scan_pick_dialog 到 components/wifi_adb_pick_dialog (4337 → 4268) 2026-05-30 14:18:19 +08:00
Your Name 44b091466d refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (4463 → 4337) 2026-05-30 14:10:30 +08:00
Your Name 8ea676562c refactor(gui): 抽 do_screenshot + OCR_REGIONS 到 components/screenshot_action (4635 → 4463) 2026-05-30 14:03:31 +08:00
Your Name a07ef00b5e refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (4656 → 4635) 2026-05-30 13:56:36 +08:00
Your Name 5329561b3a refactor(gui): 抽 refresh_reservations 到 components/reservations_view (4913 → 4656) 2026-05-30 13:52:39 +08:00
Your Name 6bffcae2de refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (5274 → 4913) 2026-05-30 13:48:22 +08:00
Your Name ac464788e1 refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → 5274) 2026-05-30 13:43:17 +08:00
Your Name 8dace383ec docs(plans): 添加 gui/gui_app.py 拆分实施计划 2026-05-30 13:26:42 +08:00
Your Name 26f9e5a553 docs(specs): 添加 gui/gui_app.py 拆分设计文档 2026-05-30 13:24:07 +08:00
CodexandClaude Sonnet 4.5 bb90e2983f fix(pil): 补充修复剩余 PIL Image 资源泄漏
覆盖 14 个文件中的 Image.open() 未正确关闭问题:
- fansclub_handler: 5 处(pic/pic_rgb/img 未 close)
- image_ops: 2 处(crop 后 pic 未 close)
- douyin_popups: 2 处(pic.convert 重赋值泄漏原始句柄)
- douyin_fudai: 1 处(open().convert() 链式调用泄漏)
- douyin_robot: 2 处(同上)
- save_files/direct_attend/finder/stage/find_open/detail/_common/ocr_preprocess: 各 1-2 处

统一修复模式:分离 open 与 convert,try/finally 确保原始句柄关闭。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 22:49:50 +08:00
CodexandClaude Sonnet 4.5 c3746b0207 fix(pil): 修复 PIL Image 资源泄漏
Image.open() 后未 close() 导致文件句柄泄漏,用 _raw + try/finally 模式修复。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 22:42:22 +08:00
CodexandClaude Sonnet 4.5 b1fa6af9ce fix(gui): 修复启动后 GUI 卡死约 1.2 秒
delayed_refresh_preview 在 mainloop 启动 300ms 后同步加载大图(PIL
Image.open + load + convert),阻塞主线程。改为:
1. 延迟到 3 秒后再触发预览(GUI 已完全初始化)
2. 图片加载放到后台线程,完成后通过 root.after 回主线程更新

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:58:50 +08:00
CodexandClaude Sonnet 4.5 96fdc96f24 refactor(cleanup): 移除剩余死代码模块
- 删除 douyin/utils/douyin_text_utils.py 及其测试
- 移除 performance_tracker.py 中未使用的 track_function 方法
- 移除 param_usage_tracer.py 中未使用的 stop_tracing / is_enabled
- 清理 bin/run_cli.py 和 tests/test_imports.py 中的残留引用

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:58:41 +08:00
CodexandClaude Sonnet 4.5 c4544489ac refactor(coords): 提取点击坐标常量,消除硬编码
在 coords.py 添加 DETAIL_OUTSIDE_CLICK、PARTICIPATE_BTN_CLICK、
FANSCLUB_JOIN_CLICK、FANSCLUB_JOIN_FALLBACK_CLICK 常量,
替换 fudai_attend/fansclub_handler/join_decision 中的硬编码坐标。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:20:17 +08:00
CodexandClaude Sonnet 4.5 d19d5bfc56 refactor(cleanup): 移除 logging 模块死代码
- unified_logger.py: 删除 5 个从未使用的装饰器/函数
- internal_loggers.py: 删除 3 个未使用方法和工厂函数
- action_logger.py: 删除 3 个未使用方法
- log_formatter.py: 删除 6 个未使用格式化函数(保留 GUI 依赖的 4 个)
- 同步更新 __init__.py 和测试文件

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:04:35 +08:00
CodexandClaude Sonnet 4.5 703da834fb fix(security): 修复 shell 注入风险和类型转换未捕获问题
- path_config.py: find_executable Unix 回退路径使用 shlex.quote 防注入
- underlying_operations.py: try_set_ime IME ID 使用 shlex.quote 防注入
- screenshot_direct.py: 环境变量 float/int 转换添加 try/except 容错
- device_select.py: 用户输入 int() 转换添加 try/except 容错
- read_once.py / image_acquirer.py / detail_verifier.py: PIL Image 添加 close()
- detector.py: 移除 return 后不可达死代码
- optimized_entry.py: 统一返回值类型 int,失败时返回 0
- read_once.py: 移除 try/except 中重复的相同代码

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 20:50:26 +08:00
CodexandClaude Sonnet 4.5 4908df19d4 refactor(cleanup): 移除死代码和冗余导入
- douyin_fudai_core.py: 移除未使用的 ThreadPoolExecutor/check_contain 导入
  和被覆盖的 fudai_result_checker 导入
- ocr_executor.py: 移除重复的 _fudai_ocr_executor_state 初始化
- flow_control_pkg: 移除 stage_handler/no_fudai/find_open 中未使用的导入

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 20:27:41 +08:00
CodexandClaude Sonnet 4.5 ca00258bf3 fix(code-quality): 修复 NameError 风险和死代码清理
- detect_by_template.py: 添加缺失的 os 和 path_config 导入
- join_decision.py: 添加缺失的 is_watch_task_fudai 导入
- read_once.py: 添加缺失的 Optional 类型导入
- fudai_detail_validator.py: 使用 extract_2digits 做更健壮的数字解析
- screenshot_manager: 移除未使用的导入和死代码

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 20:22:52 +08:00
CodexandClaude Sonnet 4.5 e62314fa25 fix(import): 修复 fudai_attend 相对导入路径错误
join_decision.py 在 fudai_filter_pkg 子包内,用 .fudai_attend 会查找
fudai_filter_pkg.fudai_attend(不存在),实际模块在上层 core 包。
改为 ..fudai_attend。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:26:58 +08:00
CodexandClaude Sonnet 4.5 df69c6ab67 fix(countdown): 修复长倒计时被截断到15分钟的bug
check_countdown 中 >900s 的上限过于激进,将实际的58分钟福袋截断到14:50。
改为 >3600s(1小时)上限,兼容抖音的60分钟福袋。

同时修复 _extract_digits 取后N位的问题,改为取前N位,
避免当子图意外捕获额外数字时(如 "1458")被误提取为 "58"。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:22:20 +08:00
CodexandClaude Sonnet 4.5 a50f08de5a fix(fudai): 验证失败时按钮可操作则继续参与
验证失败(如内容识别被禁用导致内容为空)时,若按钮状态为
"可以参与"/"需要加入粉丝团"等可操作状态,继续走参与流程而非
直接返回,避免漏参与有效福袋。同时修正 basic_join_decision 调用签名。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:03:51 +08:00
CodexandClaude Sonnet 4.5 8fd38dd30b fix(fudai): validator 内容检查正确尊重 disable 配置
当 config.json 中 fudai_disable_content_recognition=true 时,
跳过内容为空的检查。原实现在 except 块中丢失 disable_content
状态,导致配置生效时仍误判内容为空为验证失败。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:00:32 +08:00
CodexandClaude Sonnet 4.5 d850af2c44 fix(fudai): 验证器不再因内容为空而拒绝有效福袋
当奖品价值>0且倒计时合理时,内容为空是正常的(部分福袋无文字
内容),不应判定验证失败导致跳过参与。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 18:39:13 +08:00
Codex 2fab3f238e fix: entry-point scripts douyin.* import 失败 — sys.path 在 import 之后才设置
bin/run_cli.py 的 _BASE_DIR+sys.path.insert 原在 logging import 之后,
导致 No module named 'douyin' 警告。tools/ 下 5 个脚本完全缺失 sys.path
设置,auto_connect_wifi_adb.py 层级算错只跳到 tools/ 而非项目根。
2026-05-23 18:11:18 +08:00
Codex f750969df3 fix(deps): pin protobuf==3.20.3 修复 PaddleOCR 初始化失败回退到慢速 EasyOCR 2026-05-23 17:43:01 +08:00
Codex 842dd254e3 fix: correct import path for check_detail_height in detect_fudai_detail_page
The relative import from .douyin_detection was looking in the
douyin/detection/pixel/ package, but douyin_detection.py lives
at douyin/detection/douyin_detection.py. This caused every fudai
detail page detection to fail with detection_exception, making the
system always treat successful detail page opens as misclicks.
2026-05-23 17:05:43 +08:00
CodexandClaude Sonnet 4.5 6f38907119 fix(fudai/reservation): 修 3 处拆模块遗留 NameError
- douyin_fudai_core.py: get_fudai_contain 引用 TASK_LIST / PARTICIPATE_BUTTON
  但只导入了 LIVE_ROOM_TITLE,运行时必触发 NameError
- douyin_reservation_verify.py: match_reservation 末尾日志引用
  current_title,但该变量仅在 if expected_title 块内赋值,
  expected_title 为空时 NameError(被 try/except 吞掉但丢失日志)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 13:28:54 +08:00
CodexandClaude Sonnet 4.5 470c68a252 fix(fudai/stage): 修 reservation_check_start NameError + ocr_detection 缩进 + stage 默认值
- douyin_fudai.py: 补回 reservation_check_start 初始化(ffd048f 拆 helper 时丢失)
- ocr_detection.py: 修 _confirm_live_list 中 OCR 变量在 if 块外赋值的缩进 bug
- ocr_detection.py: shopping_redpacket_ocr_confidence_threshold 改 getattr 兜底 0.35
- douyin_stage.py: enable_ocr_mode1 默认值 False→True;像素检测未命中补 return
- config.json: 同步 enable_ocr_mode1 默认值

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 11:22:03 +08:00
CodexandClaude Opus 4.7 fe97e82104 fix(gui): 实时查看器/状态 Tab 的耗时解析支持 ms 单位
问题:实际 actions.log 写的是 `耗时=10.00ms`(毫秒),但 _parse_minimal
和 parse_action_duration 的正则只匹配 `s`,导致:
- 实时查看弹窗永远显示"暂无动作"
- 实时状态 Tab 同样空白

同时存在的副 bug:兜底正则在整行匹配,前缀里的 `192.168.5.2:5555` /
日志时间戳 `2026-05-21` 都可能被误识别成耗时。

修复:
- 解析窗口限定到 line.find("耗时") 之后的子串 (tail)
- 优先匹配 ms(顺序很重要:\s*s 会先吃掉 "10ms" 的 m)
- s 单位加 (?![a-zA-Z]) 负向后顾,避免匹配 "ms" / "second" 之类
- 同步修复 gui_app.py:3685 的 parse_action_duration(实时状态 Tab)

测试:
- _parse_minimal 加 4 个新测试覆盖 ms / 整数 ms / 优先级 / 前缀干扰
- 全量 1426 passed (+5)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 09:08:58 +08:00
CodexandClaude Opus 4.7 9f330572cc test(gui): 加 gui_app.main() 启动冒烟测试
背景:d759921 抽 _open_realtime_viewer_impl 时误删 16 行搜索工具栏定义,
gui_app 启动时报 NameError,但 pytest 1421 passed 没抓住——def main()
里的 NameError 只有真正调用 main() 才触发,单纯 import 不会执行函数体。

新测试通过 patch tk.Misc.mainloop 让 GUI 创建完所有控件后立刻 quit,
覆盖 def main() 内部所有顶层语句,能抓住 NameError / AttributeError /
ImportError 这类启动期失败。

已验证:临时 revert ca6c2e4 后该测试 FAIL(精确指向 L3994 NameError),
恢复 ca6c2e4 后 PASS。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:59:30 +08:00
CodexandClaude Opus 4.7 4277bf7fa4 fix(gui): WiFi 扫描显示 adb 真实返回,state=failed 不再误导为"请授权"
问题:扫描提示 "192.168.5.2:5555 当前状态=failed,请先在手机上授权后重试",
但 failed 表示 adb connect 既不成功也不是 unauthorized(通常是 adb 服务异常 /
设备短暂不可达),不是授权问题。手机不会弹窗,用户照提示去手机上找授权窗
口,永远不会成功。

修复:
- _handle_scan_result: 区分 failed 分支,逐项打印 adb 真实返回(去掉换行
  方便单行显示),并提示用户排查 adb 服务而非"请授权"。
- _open_scan_pick_dialog: 表格新增 "adb 返回" 列(截断 200 字符);
  Toplevel 拓宽到 680x320 容纳新列。
- use_selected: 根据 state 给出针对性提示——unauthorized 让用户授权,
  failed 显示对应 message,其他状态保持通用提示。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:55:15 +08:00
CodexandClaude Opus 4.7 ca6c2e4d20 fix(gui): 恢复运行日志 Tab 搜索工具栏定义
d759921 抽 _open_realtime_viewer_impl 时误删了紧随其后的 16 行
"搜索工具栏"块(log_search_frame / log_filter_var / log_search_var /
log_search_entry),导致 gui_app 启动时在 L3964 报
NameError: name 'log_search_entry' is not defined。

恢复这 16 行到原位置,gui_app 可正常启动。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:37:30 +08:00
CodexandClaude Opus 4.7 7884132743 test(pkg): 补充 _pkg 子模块单元测试
覆盖 screenshot_manager.save_files / reservation_logic._common /
logging_wrapper_pkg._common 共 14 个测试。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 07:05:23 +08:00
CodexandClaude Opus 4.7 9fbfcb5ed2 chore(gitignore): 忽略 output/ 测试与诊断产物
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 07:05:11 +08:00
CodexandClaude Opus 4.7 87bac9e548 chore(config): 补充新增功能默认配置
新增 GUI realtime_status / swipe_down_back / log_unified 默认值,
与代码中 cfg.get(..., default) 兜底保持一致。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 07:04:59 +08:00
CodexandClaude Opus 4.7 d759921442 refactor(gui): 抽 _open_realtime_viewer_impl 到 components/realtime_viewer (5539 → 5370)
gui_app.py 嵌套函数 _open_realtime_viewer_impl 是 170 行的"实时查看"对话框:
弹 Toplevel 显示当前 pic/screenshot.png + 列表展示 actions.log 中含"耗时"的
最近 80 行,每秒刷新。

抽到 gui/components/realtime_viewer.py:
- open_realtime_viewer(root) 主入口
- _tail_read(path, max_bytes) 末尾字节读取
- _parse_minimal(line) 提取 (动作名, 耗时) 二元组
- 全局单例 _active_win 替代原嵌套 def 的属性式 _win

gui_app.py 中嵌套 def 缩成 4 行委托。

新增 13 个单元测试覆盖 _tail_read 4 种情况 + _parse_minimal 8 种格式。

1421 passed (+13)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:47:58 +08:00
CodexandClaude Opus 4.7 be1eb6eda7 refactor(web_gui): 抽 ProcRunner._update_stats_from_line 解析逻辑到 stats_log_parser (2429 → 1806)
ProcRunner._update_stats_from_line 是 624 行的"日志行 → 计数器更新"方法,与
gui_core.Runner 同名方法行为接近但有差异:
- web_gui 解析 traceId / MDC 信息(gui_core 没有)
- web_gui 没有 _lock / _last_log_ts 字段(不需要锁保护)
- web_gui 没有 unique_keys_* / *_room_pos 这些去重数据结构
- web_gui 有"进入直播间到识别福袋耗时"事件解析

抽到独立的 gui/web_gui_pkg/stats_log_parser.py(不与 gui_core_pkg 版本共享,
避免在两边各加缺失字段,行为差异显式保留在两个文件中):
- update_stats_from_line(runner, line) 主入口
- 16 个 _parse_* 子函数(含 traceId/MDC、enter_to_fudai_seen 等 web_gui 专属段)

ProcRunner._update_stats_from_line 从 624 行变成 4 行委托。

1408 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:41:52 +08:00
CodexandClaude Opus 4.7 3b8f85b9cb refactor(gui_core): 抽 _update_stats_from_line 解析逻辑到 stats_log_parser (1207 → 541)
Runner._update_stats_from_line 是 666 行的"日志行 → 计数器更新"巨型方法。
按业务事件分类 14 个独立段(福袋字段 / 打开-参与计数器 / 跳过原因 /
错误统计 / 粉丝团 / 预约 / 开奖结果 / 直播间切换 / 阶段诊断 / OCR / 性能 /
详情识别 / 福袋查找 / 回退操作)。

抽到 gui/gui_core_pkg/stats_log_parser.py:
- update_stats_from_line(runner, line) 主入口
- 14 个 _parse_* 子函数按事件分组
- 通过 runner.* 调用保持与原 Runner 方法/状态一致

Runner._update_stats_from_line 从 666 行变成 4 行委托。模块级测试更易于
单独覆盖各分类的解析逻辑。

1408 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:35:04 +08:00
CodexandClaude Opus 4.7 fb35670032 refactor(gui): 抽 ThreadSafeLogWriter 到 components/log_writer (5649 → 5537)
gui_app.py 的 ThreadSafeLogWriter 类(109 行)是自包含的日志文件写入器:
threading.Lock 保护、按日期分割、配置开关、PermissionError/Exception 兜底。

抽到 gui/components/log_writer.py,原 gui_app 中的 109 行类定义 + 1 行实例化
替换为 3 行导入 + 实例化。read_config 通过 staticmethod _read_config 延迟导入,
避免循环依赖。

新增 15 个单元测试覆盖:
- __init__:默认 log_dir / 配置开关 / dated_logs / 相对路径解析 / 配置异常兜底
- write:正常写 / 禁用跳过 / 空行跳过 / 时间戳前缀 / 已格式化行原样写
- 100 线程 × 10 行的并发安全测试(确认 1000 行无丢失)
- PermissionError / 通用异常下不抛 + warn 一次

1408 passed (+15)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:29:25 +08:00
CodexandClaude Opus 4.7 230c0d4049 refactor(gui): 抽 refresh_stats 字符串格式化到 stats_formatter (6339 → 5634)
gui_app.py 的 refresh_stats 闭包是 705 行纯字符串构建:把 runner.get_stats()
的字典格式化成多个分段(基本信息/快速汇总/核心统计/跳过/OCR/详情/福袋查找/
性能/粉丝团/切换/预约/错误/价值/最近福袋/中奖记录)。

抽到 gui/components/stats_formatter.py:
- format_stats(stats: Dict) -> List[str] 主入口
- 14 个 _append_* 子段构建器(每段一个,按需追加)
- _section_lines(title, body) 标题包装

闭包改为 16 行委托:调 format_stats + 写入 ScrolledText。

新增 32 个单元测试覆盖:
- 空 dict / 缺字段时的兜底
- 基本运行状态(uptime / pid / exit_code 各种格式)
- 各分段的"有数据 / 无数据"条件
- 关键率计算(打开成功率/点击率/参与成功率/中奖率/跳过率/错误频率)
- 边界情况(attend_ok > clicks 检测到已参与,结果未开奖警告,wins 截断到 10 条)

1393 passed (+32)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:23:53 +08:00
CodexandClaude Opus 4.7 a864f6e23a refactor(fudai): 抽 __init__ 配置默认值到 init_helpers (1559 → 1323)
fudai_analyse.__init__ L119-354 是 236 行配置字段默认值 + 运行时状态初始化:
- ~80 个 self.X = <default_value> 配置字段
- 30+ 个运行时状态字段
- _reservations_state_path 解析 + room_pos_map 旧文件清理

抽到 douyin/core/fudai_modules/init_helpers.py:
- apply_fudai_defaults(self): 主入口
- _apply_yanghao_defaults(self): 推荐页养号子段
- _resolve_reservations_state_path(self): 解析路径,path_config 失败时
  兜底用 ".." 回退(不再用 dirname(__file__) + "state")
- _cleanup_old_room_pos_map_files(self): 清理上次运行的 JSON/CSV/MD 导出

__init__ 中保留:
- L57-117 设备/分辨率/operation/日志系统初始化(依赖较深,难抽)
- L356-357 self.load_config()

行为完全保留:所有字段值、解析顺序、异常兜底全部不变。
test_runtime_path_anchors.test_reservations_state_path_uses_path_config 已更新
为同时检查 douyin_fudai.py 和 init_helpers.py。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:13:46 +08:00
CodexandClaude Opus 4.7 3a9f01ad74 refactor(fudai_modules): 抽 swipe 兜底重复逻辑到 fudai_device_control (1238 → 1147)
handle_detail_helpers.py 中 _handle_error_status 内联段(L266-318,53 行)
和 _fallback_swipe_up 顶层函数(L1187-1239,53 行)做的是完全一样的事:
没有 swipe_up_to_next_live 时直接 ADB shell input swipe,失败再回退到
operation.swipe。重复 1:1。

新增 douyin/core/fudai_modules/fudai_device_control.py:
- fallback_swipe_up_via_adb(self): 纯 ADB 兜底 swipe
- swipe_up_or_fallback(self): 优先 swipe_up_to_next_live,否则 fallback

handle_detail_helpers 两处都改成 4 行委托。原文件去掉 os/subprocess
import,仅保留 time。

行为完全保留:分辨率换算公式、ADB 路径解析、subprocess 超时 5s、operation.swipe
最终兜底全部不变。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:07:41 +08:00
CodexandClaude Opus 4.7 8ecd2783db refactor(reservation): 抽 _write_state 闭包到顶层 _write_reservations_state
_run_reservation_attend_window 内嵌的 _write_state 闭包是 75 行 JSON 状态文件
写盘逻辑(含 1s 节流),独立性强,纯写文件无副作用。

抽到顶层 _write_reservations_state(self) helper,原闭包改为单行委托。
内部用到的 import json/os/datetime 移到 helper 内部,主函数顶部去掉。

行为完全保留:
- 1s 节流(避免高频写盘)
- 缺路径时 makedirs
- 异常时通过 self._log_kv 记录 + 不抛

文件总行数 1492 → 1495(+3):闭包变成委托后总行数略增 3,但消除了
1 层嵌套,给后续测试 _write_reservations_state 留出空间(可独立测试)。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:03:19 +08:00
CodexandClaude Opus 4.7 e737002b1e refactor(stage): 抽 "不在直播间" OCR 检测分支到 ocr_detection (1245 → 807)
diagnose_stage_from_current_screen L336-774 是 438 行 "if not in_live_room:"
分支:
- 步骤 2.5:购物红包 OCR 复查(像素命中红包背景时再用 OCR 二次确认)
- 步骤 3:OCR 推荐页/关注列表/直播列表标签栏(含两次精确确认子流程)

抽到 douyin_stage_handler_pkg/ocr_detection.py:
- detect_pages_via_ocr(...) 入口,内部化 in_live_room 检查
- _check_redpacket_ocr_when_not_in_live_room 步骤 2.5
- _confirm_follow_list 关注列表精确截图 + OCR 模式 0/1
- _confirm_live_list 直播列表精确截图 + OCR 模式 0/1

返回 Optional[Tuple[str, str]]:
- ("RECOMMEND_PAGE"/"FOLLOW_LIST"/"LIVE_LIST"/"SHOPPING_REDPACKET_POPUP"
   /"IN_LIVE_ROOM", reason) → caller 立即 return
- None → in_live_room=True,caller 继续后续逻辑

主函数对应位置替换为 17 行委托,_log/_log_summary/_log_separator 通过
参数传入,保持日志格式完全一致。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:59:02 +08:00
CodexandClaude Opus 4.7 df273ab231 refactor(stage): 抽 OCR 弹窗确认段到 popup_verification (1385 → 1230)
diagnose_stage_from_current_screen L1203-1358 是 156 行"未命中任何阶段
但像素检测到弹窗背景"段,用 OCR 二次确认避免直播间背景色误判:
- 优惠券弹窗:OCR "参与按钮" 区域找"开心收下"(支持模式 0+1 并行)
- 购物红包弹窗:OCR "診斷購物紅包" 区域找"购物红包/邀你抢/抢红包"

抽到 douyin_stage_handler_pkg/popup_verification.py:
- verify_popup_via_ocr(...) 入口,返回 Optional[Tuple[str, str]]
  - ("COUPON_POPUP", reason) / ("SHOPPING_REDPACKET_POPUP", reason)
    → caller 立即 return 该元组
  - None → 没有可疑弹窗或 OCR 确认失败,caller 继续后续逻辑

主函数对应位置替换为 17 行委托,保留原 _log / _log_summary 嵌套闭包通过参数传入,
保持日志格式完全一致。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:54:00 +08:00
CodexandClaude Opus 4.7 d60b83af68 refactor(reservation): 抽回退校验+二次回退到 attend_window_verify (1437 → 898)
attend_window.process_reservation_attend_window 中 L754-1293 是 540 行
"if ok:"分支:回退操作成功后等待直播间加载 → 调
douyin_reservation_verify.validate_back_to_reservation 校验 → 校验失败时
通过映射表重定位 + 二次回退。

抽到 reservation_logic/attend_window_verify.py:
- handle_back_verify(...) 入口,返回 Optional[bool]
  - True/False  → 主函数应立即返回该值
  - None        → 校验通过/禁用/异常,主函数继续设置锁定期
- _handle_verify_failure: 校验失败的处理流程
- _remap_target_via_room_titles: 映射表重定位(target + 当前直播间位置)
- _retry_seek_with_mapped_diff: 根据 mapped_pos_diff 决定是否二次回退
  - diff=0 + room_pos_before_map 不一致 → 设置 _seek_direction_hint 重试
  - diff=0 + 一致 → 跳过二次回退

主函数对应位置替换为 14 行委托。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:49:37 +08:00
CodexandClaude Opus 4.7 e46497ea80 refactor(underlying): 抽 cut_pic 图片裁剪到 image_ops (1574 → 1327)
underlying_operations.cut_pic L474-721 是 248 行图片裁剪管道:
- 默认/命名两个分支共享重试 3 次的截图加载验证
- 默认分支裁出 cut.png 或 ocr/<name>.png;命名分支裁出 pic/<target>/<name>.png
- 写入 _ocr_coords_cache 供 analyse_pic_word 调试图像引用
- SAVE_CUT_PIC_DEBUG_IMAGES=1 时保存 cut_pic 调试图

抽到 underlying_operations_pkg/image_ops.py:
- cut_pic(self, left_up, right_down, target, name) -> bool
- _ensure_parent_dir / _validate_coords / _save_cut_debug_images 内部 helper

主类方法替换为 4 行委托。

更新两个旧的源码断言测试以适配抽离:
- test_cut_pic_path:从 inspect.getsource(op.cut_pic) 改为读 image_ops.py 文件源码
- test_runtime_path_anchors:把 path_config.get_pic_dir() 检查范围从单一文件
  扩展到 underlying_operations.py + image_ops.py + ocr_pipeline.py 三处

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:43:36 +08:00
CodexandClaude Opus 4.7 8457219241 refactor(underlying): 抽 analyse_pic_word OCR 管道到 ocr_pipeline (1939 → 1560)
underlying_operations.analyse_pic_word L723-1102 是 380 行 OCR 主管道:
路径解析 + 字节缓存 + PIL 加载 + change_color 预处理 + 调试图像保存
+ EasyOCR/PaddleOCR 调用 + 置信度提取 + 缓存写回 + 成功识别落盘。

抽到 underlying_operations_pkg/ocr_pipeline.py:
- analyse_pic_word(self, picname, change_color, pic_path, return_confidence)
- _save_debug_preprocessed: 预处理后的调试图保存(仅 SAVE_OCR_DEBUG_IMAGES=1)
- _save_debug_after_ocr: 含 OCR 文本预览 + 置信度的 after_ocr 调试图
- _save_success_pic: 成功识别落盘到 ocr/<category>/<picname>_success.png

主类方法替换为 4 行委托。原行为完全保留:缓存 / 二值化 / EasyOCR vs Paddle
predict/ocr 兜底 / [None] 短路 / 异常返回空 / picname 失败诊断日志。

新增 16 个单元测试覆盖:
- 早出 4 种(pic_path 空/不存在/带 confidence/OCR 未初始化)
- OCR 调用路径(EasyOCR / Paddle predict / Paddle ocr 兜底 / [None] 短路 / 异常)
- 缓存命中跳过 OCR / 缓存未命中写回
- change_color 0/1/2 三种模式
- return_confidence True/False 返回类型
- autouse fixture 清 OCR 模块级缓存防止测试污染

1361 passed (+16)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:36:47 +08:00
CodexandClaude Opus 4.7 b200002a00 refactor(finder): 抽 OpenCV 模板匹配兜底到 finder_template_match (635 → 417)
check_have_fudai_with_ready_screenshot L288-513 是像素检测都失败时的最后
兜底(226 行):cv2.matchTemplate(TM_CCOEFF_NORMED) + minMaxLoc 在
156..269 × 351..451 搜索区域里找 fudai.png 模板。

抽到 douyin/detection/detection_pkg/finder_template_match.py:
- match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) → (det, x)
- _resolve_template_path 从 path_config / 项目根 assets 解析模板路径
  (兜底走 .. 回退,避免推到 detection_pkg/assets)
- _save_search_roi 提取 last_match.png 的保存逻辑

主 finder.py 替换为 7 行委托,从 635 → 417 行。

新增 9 个单元测试覆盖:
- _resolve_template_path:用 path_config / 兜底
- 早出条件:模板路径不存在 / cv2.imread 返回 None / 搜索区域无效
- 命中:max_val>=threshold 时 detected_x 是 1080 基准
- 不命中:max_val<threshold 时返回 False
- 模板太大:cv2.resize 被调用
- cv2 不可用时安全返回 False

1345 passed (+9)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:26:49 +08:00
CodexandClaude Opus 4.7 ab846dae0f refactor(finder): 抽逐像素兜底扫描到 finder_pixel_scan (817 → 635)
check_have_fudai_with_ready_screenshot L279-461 是 numpy 失败时的逐像素
兜底(183 行):optimal_x 从历史 / 默认热区中心选起 → 检查 5 个 y 偏移
(0/±1/±2)→ 每行从 optimal 向两侧交替搜索 → 最后从左到右兜底。

抽到 douyin/detection/detection_pkg/finder_pixel_scan.py:
- scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val) → (detected, x)
- _is_target_pixel / _safe_check_pixel / _pick_optimal_x / _search_along_y
  4 个独立纯函数,每个职责单一

颜色范围常量与 finder_numpy_scan 对齐(_R_MIN/_MAX 等)。

主 finder.py 替换为 8 行委托。

新增 15 个单元测试覆盖:
- _is_target_pixel 边界 / _safe_check_pixel 异常兜底
- _pick_optimal_x 历史命中/越界/无历史 3 种路径
- scan_pixel_by_pixel 主路径成功 / y 偏移 / 越界失败 / pic 异常兜底

1336 passed (+15)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:20:25 +08:00
CodexandClaude Opus 4.7 07cdd662c2 refactor(finder): 抽 numpy 加速扫描段到 finder_numpy_scan (937 → 811)
check_have_fudai_with_ready_screenshot L271-397 是"numpy 加速水平带扫描"
逻辑(126 行):ROI 裁剪 → RGB 颜色掩码 → 列聚合 → 从最优起始列向两侧
交替搜索第一个匹配列 → 写回 last_fudai_x。

抽到 douyin/detection/detection_pkg/finder_numpy_scan.py:
- scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
  → (detected, detected_x)
- numpy ImportError / 异常时返回 (False, None),让 caller 走逐像素兜底

主 finder.py 替换为 7 行委托。

新增 8 个单元测试(用真实 PIL.Image + numpy 构造小图):
- 空图返回 False
- 整图目标色命中 + last_fudai_x 写回
- 仅在某段列有目标色,命中位置在该段
- y_pianyi_val 偏移正确传递到扫描带
- ROI 越界返回 False
- optimal_x_scaled 在命中区时优先返回该位置

1321 passed (+8)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:15:43 +08:00
CodexandClaude Opus 4.7 1514122981 chore(finder): 删 check_have_fudai_with_ready_screenshot 末尾 501 行死代码 (1438 → 937)
L938-1438 全部位于 L936 `return False` 之后,永远不会执行:
- 旧版重复参数初始化(retry_delay_s / max_wait_s 等)
- 已被弃用的模板匹配兜底代码块
- 末尾的"以下为旧的像素检测代码"注释块

文件大小直接砍 35%,无任何行为变化。

1313 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:09:36 +08:00
CodexandClaude Opus 4.7 f718dfe2e4 refactor(fudai_attend): 抽 1057 行粉丝团门槛分支到 fansclub_handler (1629 → 573)
attend_choujiang 中"加入粉丝团/粉丝团"按钮分支占 1057 行,含一个 751 行的
内嵌闭包 _recover_to_fudai_detail_after_fansclub 处理"加入页"恢复。该分支
是文件中最大的单一逻辑块,独立性高(没有共享主流程的局部变量,全靠 analyser
属性传递状态)。

新建 fudai_attend_pkg/fansclub_handler.py(1070 行)作为整段抽出后的目的地。
导出顶层函数 handle_fansclub_branch(analyser, attend_button_text) -> bool。

attend_choujiang 中原 elif 块替换为 4 行委托:
    elif attend_button_text and (
        "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text
    ):
        return handle_fansclub_branch(analyser, attend_button_text)

行为完全保留:
- 设置 analyser.last_attend_fail_reason = "fansclub_required"
- 第一步点参与按钮 (543, 2070)
- 第二步 OCR 找加入粉丝团按钮 + bbox 中心点击(fallback 区域中心)
- 第三步关闭详情页 (500, 470)
- 第四步根据 auto_join_fansclub 等待
- 第五步 _recover_to_fudai_detail_after_fansclub 在加入页再点击 + 返回直播间

新增 9 个单元测试覆盖:
- 总返回 True
- 设置 fail_reason = "fansclub_required"
- 必经的两次坐标点击 (543,2070) / (500,470)
- 截图缺失/OCR 抛异常时的兜底
- auto_join 启用/禁用分支

1313 passed (+9)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:05:38 +08:00
CodexandClaude Opus 4.7 2f0eb90d98 refactor(fudai_core): 抽 6 个 fallback OCR 闭包到 OcrTaskRunnerFallback (1350 → 1194)
主并行 OCR 失败时走的备用路径里有 6 个 ocr_*_fallback 闭包,结构与
OcrTaskRunner 类似但更简单(不计耗时、countdown 不做数字提取、日志
tag 改为"备用OCR..."),共 156 行。

复用 ocr_tasks.py 模块新增 OcrTaskRunnerFallback 类,与 OcrTaskRunner
共享 _safe_preprocess / _BUTTON_KEYWORDS / _read_disable_flag。

主流程 6 个闭包定义换成 14 行 runner 实例化 + 方法绑定。

新增 10 个单元测试覆盖 Fallback 的所有方法(disable 跳过 / 异常 /
countdown 不提取数字 / button 关键词短路 + retry)。

1304 passed (+10)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:58:13 +08:00
CodexandClaude Opus 4.7 f38b373636 refactor(fudai_core): 抽 7 个并行 OCR 闭包到 ocr_tasks 模块 (1659 → 1328)
get_fudai_contain L222-553 有 7 个 ocr_* 闭包:task_list / content /
countdown_mm / countdown_ss / value / button / live_room_title。每个都遵循
同样的模板(计时 + analyse_pic_word/digits + perf 字典 + 异常日志),共 330 行。

抽到 douyin_fudai_core_pkg/ocr_tasks.py 的 OcrTaskRunner 类:
- 7 个方法对应 7 个并行任务
- 共享耗时 dict + lock 在构造器传入
- _record_duration / _log_warn 提取出共有的 finally + except 模板
- _BUTTON_KEYWORDS 关键词常量化(原本是闭包里硬编码 tuple)
- _safe_preprocess 顶层 helper

主流程从 7 个闭包定义 + 配置开关重复读取(330 行)变成 22 行 runner 实例化 +
方法绑定,并保留 ocr_task_list / ocr_content / ... 名字给后续 executor.submit
当作 Callable 传入,行为完全不变。

新增 22 个单元测试覆盖:
- _safe_preprocess 兜底
- 7 个方法的成功 / disable 跳过 / 异常 / 边界
- ocr_button 关键词短路 + 重试逻辑
- 所有方法都正确记录耗时到 perf_durations

1294 passed (+22)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:52:22 +08:00
CodexandClaude Opus 4.7 457edcfdc8 refactor(fudai_core): 合并 4 个 renwu 分支截图准备到 cut_regions (1825 → 1651)
get_fudai_contain L160-334 按 renwu (1/2/3/其他) 重复 4 次相似的 175 行
分支,每个分支都做"内容/倒计时(切两段)/价值"4 次 cut_pic + 可选调试截图,
唯一差异只是 countdown_box 常量。

抽到 douyin_fudai_core_pkg/cut_regions.py:
- _select_countdown_box(renwu) 选坐标
- cut_detail_regions(analyser, renwu, save_debug_images) 统一切割

原 175 行 4 个重复分支替换为 8 行调用,净减 167 行。

新增 12 个单元测试覆盖:
- _select_countdown_box 4 种 renwu
- cut_detail_regions 调 cut_pic 4 次 / 名称顺序 / 30%-30% 分割比例
- save_debug_images 开关效果

1272 passed (+12)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:47:36 +08:00
CodexandClaude Opus 4.7 03b471513d refactor(fudai_core): 抽 _run_heavy_ocr 闭包到 heavy_ocr 模块 (1953 → 1822)
_run_heavy_ocr 是 get_fudai_contain 中的 142 行闭包,按需对 6 个字段
(task_list / content / countdown_mm / countdown_ss / value / button)
跑较重的 OCR 模型补齐轻量 OCR 漏掉的字段。

抽到 douyin_fudai_core_pkg/heavy_ocr.py:
- run_heavy_ocr(analyser, fields) 顶层主函数
- _read_disable_flag(analyser, attr, cfg_key) 提取重复的 attr→config.json
  fallback 配置开关读取(原闭包里 task_list 和 content 各重复一次)
- _ocr_digits_with_fallback(analyser, picname) 提取 mm/ss 分支共有的
  digits→word 兜底数字提取逻辑

原闭包改为 4 行委托。配置开关、日志和异常兜底行为完全一致。

新增 18 个单元测试覆盖:
- _read_disable_flag 4 种状态(attr 优先 / config 兜底 / 都缺 / 文件不存在)
- _ocr_digits_with_fallback 5 个分支
- run_heavy_ocr 9 个字段组合 + disable 跳过路径

1260 passed (+18)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:39:24 +08:00
CodexandClaude Opus 4.7 2707773b15 refactor(fudai_core): 抽 _read_countdown_split 闭包到 countdown_split 模块 (2124 → 1953)
douyin_fudai_core.py 的 get_fudai_contain 函数体只有 1 个,但里面嵌了
多个闭包做 OCR 子任务。最大的 _read_countdown_split (172 行) 把倒计时
区域分割成"分钟"+"秒"两段分别识别再组合 mm:ss。

抽到 douyin_fudai_core_pkg/countdown_split.py 的 read_countdown_split
顶层函数(203 行,含独立的 _extract_digits 纯函数)。原闭包改为薄壳委托,
保留 box 默认绑定 analyser/save_debug_images 闭包变量的语义。

新增 16 个单元测试覆盖:
- _extract_digits 纯函数(前导零 / 非数字 / 边界)
- read_countdown_split 主路径 + OCR 失败 + 秒>=60 警告 + 切图失败
- 切割比例(30% / 30%)正确性
- save_debug_images 开关效果

1242 passed (+16)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:30:35 +08:00
CodexandClaude Opus 4.7 07eee6da52 fix(paths): 修同类型 5 处路径推导 bug + 加回归测试
cut_pic 路径 bug 之后再做地毯式排查,发现 5 处类似潜在 bug:
fallback 分支用 dirname(__file__) 推根级目录,path_config 不可用时
会指向错误位置(推到 douyin/core/pic 等子目录而非项目根 pic/)。

修复:
- underlying_operations.py: screenshot_calls.jsonl 路径 + OCR category 目录
  改用 path_config.get_logs_dir() / get_pic_dir()
- douyin_fudai.py: 2 处 actions.log 兜底路径
  优先 path_config.get_actions_log_path(),兜底加 ".." 回到项目根
- fudai_detail_room_title.py: 截图复用 fallback 路径加 ".." 回退
- fudai_detail_orchestrator_pkg/read_once.py: 同上 2 处 fallback

新增 11 个回归测试覆盖:
- 关键文件不再用单步 dirname/__file__/pic 写法
- path_config 仍把所有路径锚到 PROJECT_ROOT
- 兜底分支必须含 ".." 表示回退

注:douyin_fudai.py:299 的 reservations.json 因 dirname 恰好等于
PROJECT_ROOT/douyin/core,跟 path_config.get_reservations_path() 一致,
不是 bug,未改动。

1226 passed (+11 新增)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:21:27 +08:00
CodexandClaude Opus 4.7 52b811d0cb feat(scan): WiFi-ADB 扫描支持自定义/多端口(覆盖 Android 11+ 随机端口)
之前只扫 5555。Android 11+ "无线调试" 用 37000-44999 随机端口,
固定的 adb tcpip 也可改端口。新接口让扫描适配任意端口规格。

新增 parse_port_spec:解析端口规格字符串
  - 5555            单端口
  - "5555,5556"     逗号分隔
  - "37000-37010"   范围(最大 1024 个)
  - 混合格式与序列输入
  - 非法/越界 → 退化为默认 5555
  - 单个范围 > 1024 端口直接忽略,避免误扫整个端口段

scan_open_ports 重构:
  - 接受 ports 参数(list[int]),传 ports 时优先于旧 port=int
  - 返回 list[(ip, port)] 而不是 list[ip],按 (IP 数值序, port 升序) 稳定排序

discover_adb_devices 支持 ports 参数,按 (ip, port) 逐个 verify_adb_target

接入 GUI 与 webui:
  - gui_app.py 扫描对话框新增"端口"输入框 + 提示
  - gui_app.py 启动重连:上次端口非 5555 时把它一并扫描
  - web_gui.py /api/wifi/scan 接受 ports;/api/wifi/auto-reconnect 同上次端口逻辑

新增 13 个 parse_port_spec 单测 + 4 个 scan_open_ports 多端口测试 +
2 个 discover_adb_devices 多端口集成测试。
真机验证:6 端口 (5555 + 37000-37005) × 254 IP,~8.5s 扫完,
正确发现 192.168.5.2:5555 (PEPM00)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:02:48 +08:00
CodexandClaude Opus 4.7 4ab4504425 fix(cut_pic): 修截图路径错位 — pic 目录从 douyin/core/pic 改回项目根 pic
cut_pic 历史 bug:用 os.path.dirname(__file__) + "/pic" 推路径,
误指向 douyin/core/pic/(不存在),实际截图保存在 <project_root>/pic/。
日志中频繁出现"截图文件不存在: .../douyin/core/pic/screenshot.png"。

改为:
- 默认分支用 path_config.get_pic_dir() / get_screenshot_path()
- target 分支用 os.path.join(path_config.get_pic_dir(), target)

补 5 个回归测试覆盖:
- 源码不再含旧的 dirname-based 路径
- path_config 路径解析到 <project_root>/pic
- 截图缺失时 cut_pic 返回 False(重试 3 次后兜底)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 00:47:02 +08:00
CodexandClaude Opus 4.7 fb82213d53 refactor(underlying): 抽 _get_screenshot_direct 到 underlying_operations_pkg/screenshot_direct (2416 → 1930)
497 行的 ADB 截图实现(含 exec-out 主路径 + 多重兜底 + watchdog)整段抽到
underlying_operations_pkg/screenshot_direct.capture_screenshot_direct,
原方法保留 9 行 thin shim:

    def _get_screenshot_direct(self, device_id, path="pic"):
        from douyin.core.underlying_operations_pkg.screenshot_direct import (
            capture_screenshot_direct,
        )
        return capture_screenshot_direct(self, device_id, path)

净减 486 行。函数体过深的两层嵌套截图逻辑现在独立成模块,方便单独测试与改进。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:55:34 +08:00
CodexandClaude Opus 4.7 ffd048ffa5 refactor(fudai): 抽 run_once_basic 0.1 高价值预约检查到 helper (2079 → 1541)
新增 5 个 helper 到 run_once_basic_helpers.py:
- handle_reservation_check          0.1 预约检查主入口
- _maybe_clear_reservations_on_first_run  首次运行清空队列 + 状态文件
- _log_reservation_check_trigger    调试日志:检查触发条件
- _run_reservation_attend_window    队列满处理 / 抢占逻辑
- _log_reservation_attend_check     调试日志:第一个预约信息

净减 538 行重复嵌套样板。新增 7 个单元测试覆盖:
- 高价值未启用 / 队列空 → return False
- 首次运行清空队列
- 正常路径调 process_reservation_attend_window
- 队列满 → return True
- needswitch=False 走单间模式 + cleanup
- 等待开奖标志不阻断流程

至此 run_once_basic 总长 612 → 88 行(-86%),douyin_fudai.py
累计 4121 → 1541(-2580 行 / -63%),不再是项目最大文件。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:45:51 +08:00
CodexandClaude Opus 4.7 61cdf7b445 refactor(fudai): 抽 _handle_in_fudai_detail 步骤1 第二次打开分支 (2216 → 2079)
新增 handle_second_open_branch helper:
- 取 _last_fudai_detail_tuple;缺失/无效则重新读取(兜底)
- 有效缓存:从 countdown_tuple 提取 future_ts/原始秒数 + 设到 self
- 调 attend_choujiang:成功清标志 / 失败累加计数 / 异常 fall through

顺手修了一个 latent bug:first-open 抽出后 caller 还在用 step3_start /
skip / skip_reason 这些已不在作用域里的变量。改成从 self._last_fudai_detail_tuple
重新取 detail,去掉无意义的 step3_elapsed 日志,step4 的 skip 参数
直接传 (False, "") —— skip 已在 first-open 内部处理完。

净减 146 行嵌套样板。新增 6 个 second-open 单元测试覆盖:
- 缓存缺失重读 + fall through
- 短 tuple 触发重读
- attend 成功清标志清失败计数
- attend 失败累加计数
- attend 异常 fall through
- 缓存有效时正确设置 _current_fudai_future_ts

至此 _handle_in_fudai_detail 总长 506 → 215 行(-58%),
douyin_fudai.py 累计 4121 → 2079(-2042 行 / -50%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:18:33 +08:00
CodexandClaude Opus 4.7 ca953cb4ba refactor(fudai): 抽 _handle_in_fudai_detail 步骤2+3 第一次打开分支 (2568 → 2216)
新增 5 个 helper 到 handle_detail_helpers.py:
- handle_first_open_branch       第一次打开主入口
- _validate_first_open_detail    数据验证失败处理
- _check_skip_and_handle         筛选检查 + 高价值预约 + 切房
- _try_high_value_reservation    高价值倒计时阈值判断(return/continue/still_skip)
- _handle_skip_filter            普通筛选不通过:关详情 + 切房
- _fallback_swipe_up             swipe_up_to_next_live 不存在时的兜底

净减 354 行嵌套样板代码。新增 8 个单元测试覆盖:
- detail 无效 / 短 tuple
- 数据验证失败
- 筛选通过保存数据
- 普通筛选不通过 + needswitch true/false
- 高价值阈值内立即参与
- 高价值阈值外记预约

至此 _handle_in_fudai_detail 总长 1010 → 506 行(-50%),
douyin_fudai.py 累计 4121 → 2216(-1905 行 / -46%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:00:24 +08:00
CodexandClaude Opus 4.7 aeb51f73c7 chore(fudai): 清理 _handle_in_fudai_detail 死代码 + 4 处重复 cleanup
- 1 处 dead code:is_second_open 重复赋值(同一变量连读两次)
- 4 处内联"清除任务数量标志 + 嵌套 try"块用 _hd_helpers._clear_task_count_flag 替换

净减 50 行重复样板,2614 → 2568 行。
全套 1172 个测试通过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:35:38 +08:00
CodexandClaude Opus 4.7 0540610c75 refactor(fudai): 抽 _handle_in_fudai_detail last_status 检查到 helper (2872 → 2614)
新增 3 个 helper:
- check_last_status_branch:根据 _last_fudai_detail_status 路由 4 个状态
  (coupon_popup / watch_task / validation_failed / error)
- _clear_task_count_flag:清除 _fudai_detail_task_count_from_stage(多分支共用)
- _handle_error_status:error + reason=task_count_zero 时连续 3 次切直播间

净减 260 行重复样板代码。新增 9 个单元测试覆盖:
- 4 种已知 status 各自分支
- 未知/空 status 不触发
- task_count_zero 第 1 次仅累计、第 3 次强制切房 / needswitch=False 不切

至此 _handle_in_fudai_detail 总长 1010 → 752 行,
douyin_fudai.py 累计 4121 → 2614(-1507 行 / -37%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:23:26 +08:00
CodexandClaude Opus 4.7 7b6dec820b refactor(fudai): 抽 _handle_in_fudai_detail 步骤3末尾两个小段 (2926 → 2872)
新增 2 个 helper:
- check_invalid_detail_fallback:兜底检查(content="" + value=0 → 视为无效详情)
- prepare_for_attend:记 attend_before_ts + 提取 future_ts + 重置 _detail_closed_by_attend

净减 54 行重复样板代码。新增 9 个单元测试覆盖:
- 空内容+0价值识别为无效
- 正常内容不触发兜底
- detail tuple 短或非 tuple 不抛
- prepare_for_attend 正确返回 attend_before_ts 和写入 future_ts

至此 _handle_in_fudai_detail 总长 1872 → 1010 行(-862 行 / -46%),
douyin_fudai.py 4121 → 2872(累计 -1249 行 / -30%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:16:06 +08:00
CodexandClaude Opus 4.7 8a975f2bf6 refactor(fudai): 抽 _handle_in_fudai_detail 步骤4 到 handle_detail_helpers (3174 → 2926)
新增 3 个 helper:
- step4_make_join_decision:参与决策入口(detail=None 短路 + 调 basic_join_decision)
- _handle_reservation_completion:参与成功是预约福袋时的锁定期处理 + 队列清理
- _close_detail_after_attend:根据 _detail_closed_by_attend 决定是否点 click_back

净减 251 行重复代码。新增 7 个 step4 单元测试覆盖:
- detail=None 短路
- join_decision 失败不设标志
- countdown 有效设标志 + 关详情
- attend 已关详情时跳过 click_back
- 预约福袋无其他预约 → 清锁定期
- 预约福袋有其他预约 → 设保护期
- countdown 已过期不设标志

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:09:24 +08:00
CodexandClaude Opus 4.7 cea3aced73 feat(web_gui): WebUI 启动时自动重连上次 WiFi 设备 + 智能匹配
新增 /api/wifi/auto-reconnect 端点,把桌面 GUI 的 _try_reconnect_last_wifi
逻辑搬到服务端:先 verify_adb_target 上次的 target → 失败则 discover_adb_devices
扫描 + pick_best_match 智能匹配。返回结构化 JSON 让前端渲染:

  action: noop | already_online | reconnected | matched | failed
  target / model / message / devices

webui/app.js DOMContentLoaded 末尾调用 tryAutoReconnectLastWifi(),
不阻塞页面加载。命中后自动刷新设备下拉并选中。

至此桌面 GUI 和 WebUI 在 WiFi 重连体验上完全对齐:换网段也能找回手机。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:53:23 +08:00
CodexandClaude Opus 4.7 5966f461c3 feat(wifi_adb): 启动重连失败时自动扫描子网 + 智能匹配
新增 pick_best_match(devs, last) 纯函数,按优先级匹配上次设备:
1. target 完全一致(IP 没换)
2. 同 model + 同 port(换 IP 但同一台手机)—— 多台同型号时返回 None 让用户选
3. 同主机段 + 同 port(弱兜底,仅唯一时返回)
4. 唯一一台 connected(扫到就一台时认定)

GUI _try_reconnect_last_wifi 流程升级:
- verify_adb_target 失败(不可达)→ 自动 discover_adb_devices 扫子网
- pick_best_match 命中 → 选中 + 更新 last_wifi_target
- 命中且 IP 已变 → 日志写"上次目标 X 已变 → 智能匹配到 Y(已更新记忆)"
- 没命中 → 列出候选 + 提示点'扫描 WiFi'手选

实际场景:换 WiFi 网段(家里 → 公司 / 192.168.1 → 192.168.5)后
GUI 启动时自动找回同一台手机,无需任何手动操作。

新增 15 个 pick_best_match 单元测试覆盖所有规则 + 边界。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:46:23 +08:00
CodexandClaude Opus 4.7 3d91764f56 feat(webui): WebUI 加"扫描 WiFi"按钮,对齐桌面 GUI
- index.html:WiFi ADB 操作行加"扫描 WiFi"按钮 + 扫描结果区域
- app.js:wifiScan() 调 /api/wifi/scan
  - 单个 connected:自动填回 IP,刷新设备
  - 多个候选:渲染列表,点击就填回 IP
  - unauthorized:提示需手机端授权
- 单击列表项 → 填 wifi_ip 输入框 + 刷新设备下拉

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:40:54 +08:00
CodexandClaude Opus 4.7 8c3a162deb feat(web_gui): WebGUI 对齐桌面 GUI 的 WiFi 扫描和 last_wifi_target 能力
新增 4 个端点:
- POST /api/wifi/scan       扫描局域网 ADB 设备
- GET  /api/wifi/last       查询上次连接记录
- POST /api/wifi/last       同上(POST 方便 fetch)
- POST /api/wifi/last/clear 清除记录

同步 connect / disconnect 路径行为:
- /api/wifi/connect 成功后写入 last_wifi_target(取设备型号)
- /api/wifi/disconnect 如果断的就是上次记住的设备 → 自动清除记录

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:33:22 +08:00
CodexandClaude Opus 4.7 b3a41db029 feat(wifi_adb): WiFi-ADB 设置对话框三个连接路径都记 last_wifi_target
补齐之前 main commit a71f6fa 漏的几处:
- "连接"按钮:成功后保存 ip:port + 设备型号到 last_wifi_target
- "自动连接"按钮:从 USB → WiFi 切换成功后保存
- "断开连接"按钮:如果断开的就是上次记住的 IP,清掉记录避免下次启动徒劳重试

行为现在统一:所有"连上一台 WiFi 设备"的入口都会更新记忆,所有"主动断开"
的入口都会清除记忆。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:21:24 +08:00
CodexandClaude Opus 4.7 a71f6faed0 feat(wifi_adb): 记住上次成功的 WiFi 设备,GUI 启动时自动重连
新增 gui/gui_core_pkg/config.py 三个 helper:
- get_last_wifi_target  / set_last_wifi_target / clear_last_wifi_target
配置以 last_wifi_target = {target, model, saved_at} 形式存在 config.json 顶层。

GUI 行为:
- "扫描 WiFi" 选中或自动连上一台 connected 设备 → 写入 last_wifi_target
- WiFi 选择对话框"使用选中"也写入
- 主窗口启动后延迟 300ms 后台尝试 verify_adb_target(last.target)
  - 已有设备:不打扰
  - 重连成功:自动设为当前设备
  - unauthorized:提示需手机端授权
  - 不可达:提示换网了,引导点'扫描 WiFi'

新增 12 个 last_wifi_target 单元测试覆盖读写/清除/损坏值/缺文件等场景。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:16:37 +08:00
CodexandClaude Opus 4.7 db7a78876b feat(gui): 主窗口加"扫描 WiFi"一键按钮
主窗口设备行的"刷新设备"按钮旁加"扫描 WiFi"按钮。后台线程扫描局域网,
按结果数智能处理:

- 0 个发现     → 日志提示
- 1 个 connected → 自动设为当前设备
- N 个 unauthorized → 提示需手机端授权
- 多个候选     → 弹简化版列表对话框让用户选

省去打开 WiFi-ADB 设置对话框的步骤,常见单机场景一键完成。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:09:01 +08:00
CodexandClaude Opus 4.7 e89393693b feat(wifi_adb): 加局域网 ADB 设备扫描发现
新增 gui/gui_core_pkg/wifi_adb_scan.py(356 行):
- get_local_subnet:从本机 WLAN 出口 IP 推 /24 子网
- parse_subnet_spec:解析 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5 / 逗号组合
- probe_adb_port:并发 TCP 探测(默认 0.3s 超时,64 线程并发)
- verify_adb_target:对每个开放端口的 IP 调 adb connect 区分 connected / unauthorized / failed
- discover_adb_devices:主入口,端到端只需 1.5 秒扫完 /24

GUI(gui/gui_app.py)"扫描局域网"按钮加在 WiFi 设备操作区:
- 自动推子网(默认)+ 手动输入支持 CIDR / 范围 / 单 IP / 逗号
- 后台线程扫描,进度条 + 阶段提示
- 列表展示 IP / 状态 / 设备型号 / adb connect 输出,列表中手动选
- 选中已 connected 的设备 → 回填 IP 到主对话框
- unauthorized 设备明确提示需手机端授权

新增 25 个 wifi_adb_scan 单元测试。真机端到端验证通过:1.5s 扫完
192.168.5.0/24 子网,发现 192.168.5.2:5555(PEPM00)connected。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:59:19 +08:00
CodexandClaude Opus 4.7 23d370ae22 fix(wifi_adb): 修 3 处导致 WiFi-ADB 自动连接失败的解析 bug
1) get_device_ip 把 ip route 输出里的网段当 IP 返回
   原代码看到 "192.168.5.0/24 ... src 192.168.5.2" 时,扫到的第一个含 3 个点的字段是
   "192.168.5.0/24",结果用 0/24 当 IP 调 adb connect 必然失败。
   改成显式从 "src <ip>" 取,并优先 wlan 接口;加 ip addr show / ifconfig 兜底。

2) auto_connect_wifi_adb 顺序错误
   原代码先 tcpip 5555(让设备 adbd 重启、USB 链路断开)再 get_device_ip(需要 USB),
   USB 已断必然取不到 IP。改成先 get_device_ip 再 enable_wifi_adb 再 connect。

3) connect_wifi_adb 把"未授权 / 连接被拒"当成功
   adb connect 在 unauthorized / cannot connect / failed to authenticate 等场景下
   returncode 也是 0;以前只看 returncode + "connected" 子串,未授权也判成功。
   改成显式列出失败关键词,并对未授权给清晰的中文提示。

新增 20 个 wifi_adb 单元测试覆盖 3 处回归场景。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:32:04 +08:00
CodexandClaude Opus 4.7 a92cec4ff9 refactor(recovery): 抽 3 处桌面自救重复逻辑到 douyin/core/recovery 共享模块
新增 douyin/core/recovery.py(113 行):
- is_douyin_foreground(top_pkg): 统一判断前台是否抖音相关包
- recover_to_douyin(analyser, log=...): 桌面自救主入口(先 launch_package,失败回退点击)
- fallback_click_recovery(analyser, log=...): 旧的点击坐标自救兜底

3 处调用点收敛:
- fudai_modules/run_once_basic_helpers.handle_desktop_recovery:80 行 → 18 行
- douyin/other/douyin_yanghao.py: 3 段重复块(原 ~80 行 each)→ 单行调用

总计净减 -269 行重复代码。新增 13 个 recovery 单元测试 + 修测试 mock。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:20:29 +08:00
CodexandClaude Opus 4.7 4c1d95d4b5 feat(recovery): 桌面自救改用包名启动抖音,点击坐标降为兜底
当检测到不在抖音前台时,原先点击桌面图标 + 直播 + 进入直播间 3 步坐标的方式
依赖图标位置和分辨率,不同设备/桌面常常失败。改为优先调用 ADB 包名启动:

- underlying_operations 新增 launch_package(device_id, pkg):
  monkey -p <pkg> -c android.intent.category.LAUNCHER 1(主路径)
  失败回退到 am start -n <pkg>/<MainActivity>(多个常见 activity 兜底)
  默认按 com.ss.android.ugc.aweme / .lite / TikTok 顺序尝试

- 新增 is_douyin_foreground 便捷方法

- 改造 3 处自救点:
  fudai_modules/run_once_basic_helpers.py:handle_desktop_recovery
  douyin/other/douyin_yanghao.py(养号循环 + _yanghao_check_and_recover_from_desktop ×2)
  包名启动失败时仍走旧的点击逻辑作为兜底,向后兼容

新增 12 个单元测试覆盖 launch_package 主路径/兜底/失败和自救新行为。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:08:09 +08:00
CodexandClaude Opus 4.7 3aca02fae4 refactor(fudai): 抽 run_once_basic 2 段独立逻辑到 run_once_basic_helpers (3233 → 3174)
新增 2 个 helper:
- handle_just_recorded_reservation:刚记录预约后强制切换直播间
- handle_skip_stage_diagnosis:0.5 跳过阶段检测分支

新增 5 个单元测试。行为保持不变。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:37:18 +08:00
CodexandClaude Opus 4.7 695a84d8b5 refactor(fudai): 抽 _handle_in_fudai_detail 入口检查到 handle_detail_helpers (3294 → 3233)
抽出 2 个独立函数到 fudai_modules/handle_detail_helpers.py:
- log_entry_flags:进入方法时记录关键 flags
- handle_consecutive_failures_check:连续参与失败次数检查

新增 5 个单元测试覆盖阈值、needswitch 分支。行为保持不变。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:31:43 +08:00
CodexandClaude Opus 4.7 5802586b20 refactor(fudai): 拆 run_once_basic 6 段独立逻辑到 run_once_basic_helpers (4121 → 3294)
抽出 6 个独立函数到 fudai_modules/run_once_basic_helpers.py:
- handle_waiting_for_lottery_result:等待开奖期间持续 OCR 检测
- handle_no_attend_timeout:30 分钟未参与回到推荐页
- handle_desktop_recovery:桌面检测自救
- screenshot_and_diagnose:截图 + 阶段诊断
- handle_high_value_room_revisit:高价值房间重访
- dispatch_stage_branch:弹窗/详情/直播间/推荐页/开奖结果分发

新增 15 个单元测试覆盖各分支。run_once_basic 体积大幅瘦身但行为保持不变。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:22:17 +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: simgreek/douyi_guaji_main#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: simgreek/douyi_guaji_main#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: simgreek/douyi_guaji_main#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: simgreek/douyi_guaji_main#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
CodexandClaude Opus 4.5 77e797ae1c chore: 清理根目录散落文件
- 删除 restore_screenshot_service.py:一次性恢复脚本,已完成使命
- 取消追踪 .stats_test_cache.json、.web_stats_cache.json:
  运行时缓存文件,.gitignore 已忽略,本次清除历史误提交

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:33:13 +08:00
CodexandClaude Opus 4.5 a19fa35a0f chore: 整理 tools/ 47 个脚本按功能分组
- diagnostics/ 11 个:环境/配置/依赖诊断
- logs/ 7 个:日志分析与查看
- coords/ 6 个:坐标拾取与区域选择
- cleanup/ 3 个:代码清理工具
- adb/ 2 个:ADB / 输入法相关
- windows/ 4 个:Windows 系统修复(备份)
- dev/ 9 个:开发辅助 / 运行时探测

并更新 tools/README.md 描述新结构。
删除 3 个明显的临时调试脚本 (_dump_lines.py / tmp_*.py)。

tools/ 不被业务代码 import,分组仅为人工浏览方便。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:25:28 +08:00
CodexandClaude Opus 4.5 a2d6bd2cc3 chore: 归档过时迭代报告到 docs/archive/
将 15 份历史性的修复/审查/优化迭代报告归档:
- *_REPORT.md / *_FIXES.md(一次性修复总结)
- 多线程优化/日志系统优化等迭代说明(已被新版替代)
- 真机测试报告(具体某次测试的快照)

保留在 docs/ 下的是仍然有用的当前文档:
使用指南、技术文档、规范、功能说明等。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:14:30 +08:00
CodexandClaude Opus 4.5 31d4102696 chore: 删除 docs/reports 中的临时文件
config.json.bak / git_lsremote_trace.txt / log_filter_result.txt /
time_analysis_result.txt 都是运行/调试产生的临时输出,
已在 .gitignore 中忽略,本次将历史误提交的版本一并清理。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:12:50 +08:00
CodexandClaude Opus 4.5 da0c4ca3dc chore: 取消追踪运行时状态文件 .web_gui_pid
.gitignore 已忽略此文件,但历史上误提交了一次。
此处仅取消 git 追踪,本地文件保留。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:11:40 +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: simgreek/douyi_guaji_main#1
2026-05-20 23:07:29 +08:00
CodexandClaude Opus 4.5 92718a7cb4 fix: douyin_fudai 关键路径异常添加日志
- run_id 生成失败时记录 logging.debug
- 日志系统初始化失败时记录 logging.warning,便于排查

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:03:27 +08:00
CodexandClaude Opus 4.5 9bd10277b2 fix: 前端 apiPost 添加 CSRF token
配合后端 /api/csrf-token 接口获取并自动附加 X-CSRF-Token 请求头,
避免 CSRF 防护启用后所有 POST 请求被 403 拒绝。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:01:31 +08:00
CodexandClaude Opus 4.5 92753c51a5 chore: 删除已废弃的 deleted_tests_backup 目录
22 个备份测试文件已废弃多月,从代码库中移除以减少干扰。
如需历史,仍可从 git 历史中恢复。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:56:51 +08:00
CodexandClaude Opus 4.5 6b22939c7e fix: 改善 fudai_detail_validator 异常处理
- 收紧 except 类型为 ValueError/TypeError
- 添加 logging.debug 替代静默 pass,便于排查 OCR 识别错误

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:54:44 +08:00
CodexandClaude Opus 4.5 68a2ab73ba refactor: 抽取倒计时解析工具到 time_utils 模块
将散落在三处的重复 _parse_mm_ss / _extract_2digits 实现集中到
douyin/utils/time_utils.py,便于复用与单元测试。

不修改既有调用点(保持向后兼容),后续可按需迁移。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:54:01 +08:00
CodexandClaude Opus 4.5 61d72b2b8d perf: 优化 np.array 为 np.asarray 减少内存拷贝
np.array() 默认会复制数据,而 np.asarray() 只在必要时才复制。
对于只读用途,asarray() 性能更好。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:50:33 +08:00
CodexandClaude Opus 4.5 1dea80d5be fix: 截图服务添加 atexit 优雅关闭
ScreenshotService 在进程退出时通过 atexit 钩子停止后台线程,
避免 daemon 线程被强杀导致的资源泄漏。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:48:43 +08:00
CodexandClaude Opus 4.5 5ce314b41c chore: 清理死文件和裸 except
- 删除空文件 sitecustomize.py
- 修复 tools/simple_region_selector.py 中的裸 except:

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:46:02 +08:00
CodexandClaude Opus 4.5 84e8d0c46d fix: Web GUI 安全加固
1. PID 操作添加专用锁保护,防止 force_stop 并发问题
2. POST 接口添加 CSRF token 验证
3. 新增 /api/csrf-token 接口供前端获取 token

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:39:47 +08:00
CodexandClaude Opus 4.5 ff8de2c9b8 fix: 修复7个Critical并发安全和异常处理问题
1. OCR 单例无锁保护 - 添加 _ocr_lock 和 _ocr_coords_lock
2. ADB 文本广播命令注入 - 使用 shlex.quote() 转义
3. 截图文件 Race Condition - 添加 PNG 完整性验证
4. JSON 持久化无锁 - 添加文件级锁字典
5. 双检查锁不完整 - 修复 _ensure_debug_save_worker_started
6. Daemon 线程无 Graceful Shutdown - 添加 shutdown event 和 atexit
7. 关键路径异常处理 - 添加 logging.debug 替代 pass

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 22:25:35 +08:00
Codex 1fdec7a548 整理项目文件分类 2026-05-20 20:49:19 +08:00
Codex 38e2b399d4 增加Web和桌面参数自动同步清单 2026-05-20 20:35:58 +08:00
Codex caa24ea8ca 保持Web端和桌面端参数同步 2026-05-20 20:32:23 +08:00
Codex 6c73f6e414 优化Web端日志导航与GUI配置 2026-05-20 20:23:32 +08:00
Codex 674ede76ee Add project git automation instructions 2026-05-20 19:24:27 +08:00
Codex 13b1f2150c Fix launcher paths and remove local hardcoding 2026-05-20 19:18:34 +08:00
Codex e7a7d3f888 Fix device selection and adb command safety 2026-05-20 18:43:58 +08:00
Your Name 89128deb0f Complete missing Web GUI controls 2026-05-20 17:54:40 +08:00
480 changed files with 63638 additions and 51610 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
# Copilot 指令(douyin_guaji-main)
# Copilot 指令(本仓库)
## 来自 `docs/完整技术文档.md` 的补充(要点)
- 版本:V4.5(2026-01-18)。本文件为实现细节与验证命令的权威来源,agent 在执行重大改动前请核对文档中的“验证要点”。
+127 -56
View File
@@ -1,22 +1,105 @@
# Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Virtual env
# Python build artifacts
build/
dist/
downloads/
eggs/
.eggs/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual environments
.venv/
venv/
env/
ENV/
.env
.env/
.env.*
!.env.example
# Runtime artifacts
# Python tooling caches
.pytest_cache/
.mypy_cache/
.ruff_cache/
.pyre/
.pytype/
.tox/
.nox/
.coverage
.coverage.*
coverage.xml
htmlcov/
pip-wheel-metadata/
# Type check / lint reports
pylint_report.txt
pyright_report.txt
*.report
*.lint
# Logs and runtime traces
logs/
*.log
pic/
*.log.*
*.trace
*.pid
.web_gui_pid
git_lsremote_trace.txt
log_filter_result.txt
time_analysis_result.txt
# Tools generated reports
# Tools generated reports (ignore any large/temporary csv reports)
# Test/diagnostic outputs
output/
# Local runtime state and generated caches
state/
pic/
screenshots/
captures/
tmp/
temp/
.tmp/
*.tmp
*.temp
*.cache
*.sqlite
*.sqlite3
*.db
*.db-journal
*.db-shm
*.db-wal
*.jsonl
.stats_test_cache.json
.web_stats_cache.json
# Local configuration and backups
config/*.json
!config/README.md
*.bak
*.bak_*
*.backup
*.orig
*.swp
*.swo
*~
# Generated tool reports and samples
tools/coords_report*.csv
tools/*_report*.csv
tools/*_report*.csv.gz
tools/*.csv
# Tools sample/ocr artifacts
tools/ocr_failures*
tools/ocr_failures/
tools/samples/
@@ -24,55 +107,43 @@ tools/*.zip
tools/*.tar.gz
tools/*.bundle
# Logs (keep local logs out of VCS)
logs/
*.log*
logs/*.gz
*.log
# Archive and backup files
*.zip
*.tar.gz
*.tgz
*.bak
*.bundle
# Large DB / cache files
*.sqlite
*.db
*.db-journal
# Editor/project user files
.idea/
*.suo
*.user
*.sln.docstates
# Code analysis reports
pylint_report.txt
pyright_report.txt
*.report
*.lint
# Test coverage
.coverage
.coverage.*
htmlcov/
.tox/
.pytest_cache/
# VS Code
.vscode/
# Cursor IDE
.cursor/
.specstory/
# OS
.DS_Store
Thumbs.db
# Project-specific generated state
douyin/core/state/reservations.json
state/high_value_rooms.json
douyin/core/state/room_pos_map.csv
douyin/core/state/room_pos_map.json
douyin/core/state/room_pos_map.md
state/high_value_rooms.json
# Archives and bundles
*.zip
*.tar.gz
*.tgz
*.rar
*.7z
*.bundle
# Node / frontend caches
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.parcel-cache/
.next/
.vite/
# IDE and editor files
.vscode/
.idea/
.cursor/
.specstory/
*.suo
*.user
*.userosscache
*.sln.docstates
# OS files
.DS_Store
Thumbs.db
ehthumbs.db
Desktop.ini
-1
View File
@@ -1 +0,0 @@
{"ts": 1765641063.2151546, "counters": {"fudai_seen": 1, "fudai_open_detail": 1, "fudai_click_attend": 1, "fudai_attend_ok": 1, "fudai_result_win": 1}, "fudai_last": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0, "updated_ts": 1765641063.1966858}, "events": [{"ts": 1765641063.1946857, "type": "fudai_seen", "meta": {"content": "测试内容A", "countdown": "", "participants": null, "copies": null, "prize_value_yuan": null}}, {"ts": 1765641063.1966858, "type": "fudai_open_detail", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}, {"ts": 1765641063.1966858, "type": "fudai_click_attend", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}, {"ts": 1765641063.1966858, "type": "fudai_attend_ok", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}, {"ts": 1765641063.1966858, "type": "fudai_result_win", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}], "wins": [{"ts": 1765641063.1966858, "content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}]}
-1
View File
@@ -1 +0,0 @@
21948
-1
View File
@@ -1 +0,0 @@
{"ts": 1765685532.6116447, "counters": {"fudai_open_detail": 74, "fudai_seen": 80, "fudai_skip_value_low": 28, "fudai_open_error": 8, "switch_room": 40, "switch_room_no_fudai": 28, "fudai_skip_countdown_short": 3, "switch_room_countdown": 3, "switch_room_value": 8, "fudai_click_attend": 2, "fudai_result_no_win": 2}, "fudai_last": {"content": "【粉丝专属】iPhone17手机256G颜色随机", "countdown": "14:29后开奖", "participants": 2132, "copies": 1, "prize_value_yuan": 5999.0, "updated_ts": 1765684579.3024325}, "events": [{"ts": 1765641806.1646142, "type": "fudai_open_detail", "meta": {"content": "", "countdown": "", "participants": null, "copies": null, "prize_value_yuan": null}}, {"ts": 1765641813.7004516, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "", "participants": null, "copies": null, "prize_value_yuan": null}}, {"ts": 1765641815.2687662, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "07:19后开奖", "participants": 32, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641819.8364112, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "07:19后开奖", "participants": 32, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641826.9612343, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "07:19后开奖", "participants": 32, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641829.2069504, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "04:07", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641833.980556, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "04:07", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641841.1970615, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "04:07", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641842.785327, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:50后开奖", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641848.7064586, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:50后开奖", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641857.2592785, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:50后开奖", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641858.9027817, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:35后开奖", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641863.3506944, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:35后开奖", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641869.6957817, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:35后开奖", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641871.0666997, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:21", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641875.5607815, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:21", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641882.6100206, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:21", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641883.8911793, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:09", "participants": 36, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641888.1028545, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:09", "participants": 36, "copies": 1, "prize_value_yuan": 1Line truncated
+9
View File
@@ -0,0 +1,9 @@
# 项目级 Codex 指南
## Git 自动提交
- 本项目每次完成文件修改后,都要自动执行 Git 提交并推送到远端。
- 提交前必须先检查工作区状态,只 stage 本次任务实际修改的文件。
- 不要把用户已有的未提交改动、无关生成物或临时输出混入提交。
- 提交前运行与改动相关的最小验证;无法验证时,在最终回复里说明原因。
- 推送失败时,保留本地提交并明确说明失败原因和下一步处理建议。
+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
+436 -1264
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Compatibility launcher for the desktop GUI."""
from __future__ import annotations
import os
import runpy
import sys
from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parent.parent
TARGET = ROOT_DIR / "gui" / "gui_app.py"
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
def _reexec_with_venv() -> None:
if not VENV_PYTHON.exists():
return
if Path(sys.executable).resolve() == VENV_PYTHON.resolve():
return
os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), str(TARGET), *sys.argv[1:]])
def main() -> None:
_reexec_with_venv()
sys.argv = [str(TARGET), *sys.argv[1:]]
runpy.run_path(str(TARGET), run_name="__main__")
if __name__ == "__main__":
main()
+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("状态: 运行中")
+27 -29
View File
@@ -1,27 +1,36 @@
import argparse
import importlib.util
import logging
import os
import shutil
import sys
# ==== 将项目根目录加入 sys.path,确保后续所有 douyin.* 导入正常 ================
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
if os.environ.get("PARAM_TRACK_ALL") == "1":
try:
from douyin.utils.param_usage_tracer import start_tracing
start_tracing()
except Exception:
# 启用失败不影响主流程
pass
except Exception as e:
logging.debug("参数追踪启用失败: %s", e)
# ==== 首先配置日志系统,确保日志文件能正常写入 ==============================
try:
from douyin.logging import douyin_logging
douyin_logging.configure_logging()
except Exception:
# 日志配置失败不影响主流程,但会缺少文件日志
pass
except Exception as e:
# 日志配置失败,使用基础配置作为兜底
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - [%(levelname)s] - %(message)s'
)
logging.warning("日志系统配置失败,使用基础配置: %s", e)
# 尝试确保行为日志的异步 listener 在进程启动时就被启动,
# 以避免某些运行环境中模块未完整初始化导致日志未落盘的问题。
@@ -33,25 +42,17 @@ try:
action_logger_mod = importlib.import_module("douyin.logging.action_logger")
try:
action_logger_mod._start_queue_listener_if_needed()
except Exception:
except Exception as e:
# 启动失败时不影响主流程,action_logger 有回退到同步 file handler 的逻辑
pass
except Exception:
pass
logging.debug("action_logger 启动失败: %s", e)
except Exception as e:
logging.debug("action_logger 模块导入失败: %s", e)
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
# 当前 WebGUI 目录中没有完整版 douyin_fudai.py,而是在 Cursor 的工作树中存在完整实现。
# 同时,我们在本目录下放置了一些 shim 模块(如 douyin_text_utils、douyin_swipe_ops 等),
# 需要优先加载这些本地实现,再去加载完整逻辑模块。
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
_BASE_DIR = os.path.dirname(__file__)
# 使用环境变量或默认路径,避免硬编码用户路径
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get(
"EXTERNAL_DOUYIN_FUDAI_DIR",
os.path.join(
os.path.expanduser("~"), ".cursor", "worktrees", "douyin_guaji-main", "axf"
),
)
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
def _load_local_shim(mod_name: str, rel_path: str) -> None:
@@ -68,17 +69,14 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[mod_name] = module
except Exception:
except Exception as e:
# shim 加载失败不影响主流程,后续仍可尝试外部模块
logging.debug("shim 模块加载失败 %s: %s", mod_name, e)
return
# 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:
@@ -87,9 +85,9 @@ try:
and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path
):
sys.path.append(_EXTERNAL_DOUYIN_FUDAI_DIR)
except Exception:
except Exception as e:
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
pass
logging.debug("外部模块路径配置失败: %s", e)
# 在导入 PaddleOCR 之前设置,避免每次启动都做连通性检查提示并抑制底层 glog/oneDNN 等噪音
# DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR 的主机连通性检查(国内网络环境常卡)
@@ -630,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:
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Compatibility launcher for the Web GUI launcher window."""
from __future__ import annotations
import os
import runpy
import sys
from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parent.parent
TARGET = ROOT_DIR / "gui" / "webgui_launcher.py"
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
def _reexec_with_venv() -> None:
if not VENV_PYTHON.exists():
return
if Path(sys.executable).resolve() == VENV_PYTHON.resolve():
return
os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), str(TARGET), *sys.argv[1:]])
def main() -> None:
_reexec_with_venv()
sys.argv = [str(TARGET), *sys.argv[1:]]
runpy.run_path(str(TARGET), run_name="__main__")
if __name__ == "__main__":
main()
-102
View File
@@ -1,102 +0,0 @@
{
"needswitch": true,
"infinite_loop_enabled": true,
"wait_minutes": 5,
"y_pianyi": 0,
"contains_not_want": [
"首饰盒"
],
"min_prize_value_yuan": 200.0,
"min_participants": 0,
"max_participants": 0,
"skip_if_countdown_gt_seconds": 120,
"reset_after_swipes_enabled": true,
"reset_after_swipes": 50,
"auto_join_fansclub": true,
"fansclub_fail_action": "switch",
"lucky_draw_red_ratio_threshold": 0.8,
"high_value_fudai_enabled": true,
"high_value_fudai_threshold_yuan": 500.0,
"high_value_fudai_join_ahead_seconds": 300,
"high_value_fudai_max_swipe_back": 50,
"high_value_fudai_max_reservations": 9999,
"high_value_fudai_after_action": "continue",
"high_value_room_revisit_enabled": true,
"high_value_room_revisit_only_current_run": true,
"reservation_back_verify_enabled": true,
"reservation_back_swipe_delay": 0.5,
"record_room_title_mapping_enabled": true,
"reservation_preempt_min_value": 0.0,
"fudai_find_max_attempts": 99999,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_icon_max_wait_seconds": 8.5,
"fudai_click_wait_seconds": 1.7,
"switch_room_wait_after_stage_diag_seconds": 4.0,
"live_room_match_threshold": 0.6,
"fudai_quiet_hours_enabled": true,
"fudai_quiet_start_hour": 2,
"fudai_quiet_end_hour": 9,
"stage_diag_max_time": 5.0,
"stage_diag_max_step_time": 2.0,
"enable_ocr_mode1": false,
"fudai_template_match_enabled": false,
"fudai_template_match_threshold": 0.7,
"fudai_detail_template_threshold": 0.54,
"coupon_template_match_threshold": 0.4,
"attend_button_red_ratio_threshold": 0.25,
"fansclub_join_red_ratio_threshold": 0.25,
"skip_if_countdown_lt_seconds": 5,
"debug_captures": {
"enabled": true,
"auto_cleanup": true,
"keep_days": 3,
"max_files": 2000
},
"yanghao_enabled": false,
"yanghao_enable_actions": false,
"yanghao_recommend_duration_seconds": 206,
"yanghao_recommend_interval_seconds": 570,
"yanghao_like_prob": 1.0,
"yanghao_fav_prob": 0.85,
"yanghao_comment_prob": 1.0,
"yanghao_icon_roi_size": 240,
"yanghao_icon_match_threshold": 0.70,
"yanghao_step_screenshot": false,
"yanghao_like_roi_offset_x": 0,
"yanghao_like_roi_offset_y": -50,
"yanghao_fav_roi_offset_x": 40,
"yanghao_fav_roi_offset_y": 0,
"yanghao_like_icon_x": 0,
"yanghao_like_icon_y": -1,
"yanghao_fav_icon_x": -1,
"yanghao_fav_icon_y": 0,
"yanghao_like_template_path": "assets/like.png",
"yanghao_fav_template_path": "assets/fav.png",
"yanghao_after_dwell_swipe_direction": "up",
"yanghao_after_dwell_swipe_distance_px": 900,
"yanghao_comment_btn_x": 0,
"yanghao_comment_btn_y": -1,
"yanghao_comment_input_x": 0,
"yanghao_comment_input_y": 0,
"yanghao_comment_send_x": 0,
"yanghao_comment_send_y": -1,
"yanghao_comment_close_x": 0,
"yanghao_comment_close_y": 0,
"yanghao_comment_texts": [],
"yanghao_like_keywords": [],
"yanghao_fav_keywords": [],
"logging": {
"level": "INFO",
"file_path": "logs/unified.log",
"keep_days": 30,
"use_dated_logs": true,
"compress_logs": true,
"max_total_size_gb": 10.0,
"compress_after_days": 7,
"max_bytes": 104857600,
"backup_count": 10,
"enable_monitor": true,
"monitor_warning_mb": 500.0,
"monitor_critical_mb": 2000.0
}
}
+17 -4
View File
@@ -194,12 +194,12 @@
"monitor_critical_mb": 200.0
},
"debug_captures": {
"enabled": false,
"enabled": true,
"keep_days": 1,
"max_files": 1000,
"auto_cleanup": true,
"async_save": false,
"log_on_complete": false
"log_on_complete": true
},
"fudai_detail_template_threshold": 0.52,
"switch_room_wait_after_stage_diag_seconds": 7.5,
@@ -210,7 +210,11 @@
"reservation_test_mode": false,
"swipe_duration_ms": 250,
"gui": {
"theme": "litera"
"theme": "litera",
"realtime_status": {
"refresh_interval_ms": 1000,
"tail_items": 50
}
},
"fansclub_click_delay": 0.6,
"fansclub_auto_join_wait_seconds": 5.0,
@@ -224,5 +228,14 @@
"high_value_room_revisit_min_prize_value": 1000.0,
"high_value_room_revisit_max_age_days": 1,
"swipe_up_start_y": 1200,
"swipe_up_end_y": 600
"swipe_up_end_y": 600,
"swipe_down_back_enabled": false,
"swipe_down_back_count": 3,
"log_unified_enabled": true,
"log_unified_path": "logs/unified.log",
"last_wifi_target": {
"target": "192.168.5.2:5555",
"model": "PEPM00",
"saved_at": 1779501066
}
}
@@ -1,222 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ADB 截图基准测试脚本
用于测试 ADB exec-out screencap 的实际耗时,帮助诊断截图慢的问题。
使用方法:
1. 确保设备已连接: adb devices
2. 运行: python test_adb_screenshot_timing.py [device_id]
如果不提供 device_id,将使用第一个设备
"""
import subprocess
import sys
import time
import os
from typing import Optional
def get_adb_path() -> str:
"""获取 ADB 路径"""
# 尝试从环境变量获取
adb = os.environ.get("ADB_PATH", "adb")
# 尝试常见路径
if not os.path.exists(adb):
common_paths = [
"adb",
r"C:\Users\{}\AppData\Local\Android\Sdk\platform-tools\adb.exe".format(os.environ.get("USERNAME", "")),
r"C:\Android\platform-tools\adb.exe",
]
for path in common_paths:
try:
result = subprocess.run([path, "version"], capture_output=True, timeout=5)
if result.returncode == 0:
return path
except Exception:
continue
return adb
def get_device_id() -> Optional[str]:
"""获取第一个连接的设备ID"""
adb = get_adb_path()
try:
result = subprocess.run([adb, "devices"], capture_output=True, text=True, timeout=10)
if result.returncode != 0:
print(f"[错误] adb devices 失败: {result.stderr}")
return None
lines = result.stdout.strip().split("\n")[1:] # 跳过第一行 "List of devices attached"
devices = []
for line in lines:
if line.strip() and "\t" in line:
device_id = line.split("\t")[0].strip()
if device_id:
devices.append(device_id)
if not devices:
print("[错误] 未找到连接的设备")
return None
if len(devices) > 1:
print(f"[提示] 找到多个设备: {devices},使用第一个: {devices[0]}")
return devices[0]
except Exception as e:
print(f"[错误] 获取设备列表失败: {e}")
return None
def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None:
"""测试 exec-out screencap 耗时"""
adb = get_adb_path()
print(f"\n{'='*60}")
print(f"测试 ADB exec-out screencap")
print(f"设备: {device_id}")
print(f"迭代次数: {iterations}")
print(f"{'='*60}\n")
times = []
sizes = []
for i in range(iterations):
try:
start = time.time()
result = subprocess.run(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
capture_output=True,
timeout=15,
)
elapsed = (time.time() - start) * 1000.0 # 转换为毫秒
if result.returncode == 0:
size = len(result.stdout)
times.append(elapsed)
sizes.append(size)
print(f" 迭代 {i+1}: {elapsed:.1f}ms, 大小: {size/1024:.1f}KB")
else:
print(f" 迭代 {i+1}: 失败 (返回码: {result.returncode})")
except subprocess.TimeoutExpired:
print(f" 迭代 {i+1}: 超时 (>15秒)")
except Exception as e:
print(f" 迭代 {i+1}: 异常: {e}")
if times:
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
avg_size = sum(sizes) / len(sizes) if sizes else 0
print(f"\n{'='*60}")
print(f"统计结果:")
print(f" 平均耗时: {avg_time:.1f}ms")
print(f" 最小耗时: {min_time:.1f}ms")
print(f" 最大耗时: {max_time:.1f}ms")
print(f" 平均大小: {avg_size/1024:.1f}KB")
print(f"{'='*60}\n")
if avg_time > 3000:
print("[警告] 平均耗时超过3秒,可能存在问题:")
print(" - 检查 USB 连接是否稳定")
print(" - 检查是否使用 Wi-Fi ADB(通常较慢)")
print(" - 检查设备性能是否正常")
elif avg_time > 2000:
print("[提示] 平均耗时超过2秒,建议:")
print(" - 考虑使用 USB 连接而非 Wi-Fi")
print(" - 检查设备性能")
def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None:
"""测试 shell screencap + pull 耗时(回退方案)"""
adb = get_adb_path()
print(f"\n{'='*60}")
print(f"测试 ADB shell screencap + pull (回退方案)")
print(f"设备: {device_id}")
print(f"迭代次数: {iterations}")
print(f"{'='*60}\n")
times = []
for i in range(iterations):
try:
# 清理旧文件
subprocess.run([adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"],
capture_output=True, timeout=5)
start = time.time()
# Step 1: shell screencap
step1_start = time.time()
result1 = subprocess.run(
[adb, "-s", device_id, "shell", "screencap", "-p", "/sdcard/DCIM/screenshot.png"],
capture_output=True,
timeout=10,
)
step1_dur = (time.time() - step1_start) * 1000.0
if result1.returncode != 0:
print(f" 迭代 {i+1}: shell screencap 失败")
continue
# Step 2: pull
step2_start = time.time()
result2 = subprocess.run(
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", "test_screenshot.png"],
capture_output=True,
timeout=10,
)
step2_dur = (time.time() - step2_start) * 1000.0
elapsed = (time.time() - start) * 1000.0
if result2.returncode == 0 and os.path.exists("test_screenshot.png"):
size = os.path.getsize("test_screenshot.png")
times.append(elapsed)
print(f" 迭代 {i+1}: 总耗时 {elapsed:.1f}ms (screencap: {step1_dur:.1f}ms, pull: {step2_dur:.1f}ms), 大小: {size/1024:.1f}KB")
try:
os.remove("test_screenshot.png")
except Exception:
pass
else:
print(f" 迭代 {i+1}: pull 失败")
except Exception as e:
print(f" 迭代 {i+1}: 异常: {e}")
if times:
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f"\n{'='*60}")
print(f"统计结果 (回退方案):")
print(f" 平均耗时: {avg_time:.1f}ms")
print(f" 最小耗时: {min_time:.1f}ms")
print(f" 最大耗时: {max_time:.1f}ms")
print(f"{'='*60}\n")
def main():
device_id = None
if len(sys.argv) > 1:
device_id = sys.argv[1]
else:
device_id = get_device_id()
if not device_id:
print("[错误] 无法获取设备ID")
sys.exit(1)
print(f"使用设备: {device_id}")
print(f"ADB 路径: {get_adb_path()}")
# 测试 exec-out(主要方案)
test_exec_out_screencap(device_id, iterations=5)
# 测试 shell + pull(回退方案,较少迭代)
test_shell_screencap_pull(device_id, iterations=3)
if __name__ == "__main__":
main()
@@ -1,106 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试完全禁用截图服务功能
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_completely_disable_screenshot_service():
"""测试完全禁用截图服务"""
print("测试完全禁用截图服务功能...")
print("=" * 50)
# 1. 测试截图服务的get_screenshot方法
print("\n1. 测试截图服务的get_screenshot方法")
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
# 调用get_screenshot,应该直接返回False
result = service.get_screenshot("test_device")
print(f"service.get_screenshot() 返回: {result}")
if result == False:
print("[OK] 截图服务正确返回False,不启动后台服务")
else:
print("[ERROR] 截图服务返回了非False值")
return False
# 2. 测试服务状态
print("\n2. 检查服务状态")
if service.is_running():
print("[WARN] 服务正在运行,但应该已被禁用")
else:
print("[OK] 服务未运行")
print(f"当前设备ID: {service._current_device_id}")
# 3. 测试直接截图调用
print("\n3. 测试直接截图调用")
from operations.screenshot_operations import ScreenshotOperations
ops = ScreenshotOperations()
# 检查默认参数
import inspect
sig = inspect.signature(ops.get_screenshot)
params = sig.parameters
use_service_default = params['use_service'].default
print(f"直接截图方法use_service默认值: {use_service_default}")
if use_service_default == False:
print("[OK] 直接截图方法默认不使用服务")
else:
print("[WARN] 直接截图方法仍可能使用服务")
# 4. 验证所有修改
print("\n4. 验证所有修改")
modified_files = [
"operations/screenshot_operations.py",
"operations/screenshot_service.py",
"douyin/core/douyin_fudai.py",
"douyin/core/douyin_main_flow.py",
"fudai_detail_modules/fudai_detail_reader.py"
]
for file_path in modified_files:
if os.path.exists(file_path):
print(f"[OK] {file_path} 存在")
else:
print(f"[ERROR] {file_path} 不存在")
return False
# 5. 总结禁用状态
print("\n5. 截图服务禁用总结")
print("-" * 40)
print("已完成的禁用:")
print("1. [DONE] 修改 get_screenshot() 默认 use_service=False")
print("2. [DONE] 让 ScreenshotService.get_screenshot() 直接返回False")
print("3. [DONE] 移除所有后台服务启动代码")
print("4. [DONE] 移除设备ID变更时的自动服务启动")
print("5. [DONE] 移除OCR操作后的服务重启")
print("\n预期效果:")
print("- 所有截图调用都会使用直接ADB命令")
print("- 后台截图服务完全不会启动")
print("- 每次截图都是独立的,不会复用缓存")
print("- 系统更加稳定,但响应稍慢")
return True
if __name__ == "__main__":
success = test_completely_disable_screenshot_service()
print(f"\n{'='*50}")
print(f"测试结果: {'PASS' if success else 'FAIL'}")
print("后台截图服务已完全禁用,使用原始直接截图模式")
print(f"{'='*50}")
@@ -1,287 +0,0 @@
#!/usr/bin/env python3
"""
测试直接截图功能
验证所有截图调用都使用直接模式(use_service=False)
"""
import os
import sys
import time
from datetime import datetime
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_screenshot_operations():
"""测试 operations.screenshot_operations 模块"""
print("=" * 80)
print("测试 1: operations.screenshot_operations.get_screenshot()")
print("=" * 80)
try:
from operations.screenshot_operations import get_screenshot, ScreenshotOperations
# 获取设备ID
device_id = os.environ.get("DEVICE_ID", "")
if not device_id:
print("[WARN] 未设置 DEVICE_ID 环境变量,尝试从配置读取...")
try:
import json
import path_config
config_path = path_config.get_config_path()
# 尝试从常见位置读取
device_id = "MB75DEFQZHZTGMLJ" # 从日志中看到的设备ID
except Exception:
print("[ERROR] 无法获取设备ID,请设置环境变量 DEVICE_ID")
return False
print(f"设备ID: {device_id}")
print(f"测试模式: 直接截图 (use_service=False)")
print()
# 测试1: 使用默认参数(应该是 False)
print("测试 1.1: 使用默认参数调用 get_screenshot()")
start = time.time()
try:
result = get_screenshot(device_id)
elapsed = (time.time() - start) * 1000
status = "[OK] 成功" if result else "[FAIL] 失败"
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
except Exception as e:
elapsed = (time.time() - start) * 1000
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
print()
# 测试2: 显式传递 use_service=False
print("测试 1.2: 显式传递 use_service=False")
start = time.time()
try:
ops = ScreenshotOperations()
result = ops.get_screenshot(device_id, use_service=False)
elapsed = (time.time() - start) * 1000
status = "[OK] 成功" if result else "[FAIL] 失败"
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
except Exception as e:
elapsed = (time.time() - start) * 1000
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
print()
# 测试3: 验证不会使用服务模式
print("测试 1.3: 验证不会调用后台服务")
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
service_running_before = service.is_running()
print(f" 服务运行状态(测试前): {service_running_before}")
# 调用截图(应该不会启动服务)
get_screenshot(device_id)
service_running_after = service.is_running()
print(f" 服务运行状态(测试后): {service_running_after}")
if not service_running_after:
print(" [OK] 确认:服务未被启动(符合预期)")
else:
print(" [WARN] 警告:服务仍在运行(可能之前已启动)")
except Exception as e:
print(f" [WARN] 无法检查服务状态: {e}")
return True
except ImportError as e:
print(f"[ERROR] 导入错误: {e}")
return False
except Exception as e:
print(f"[ERROR] 测试失败: {e}")
import traceback
traceback.print_exc()
return False
def test_underlying_operations():
"""测试 Underlying_Operations 模块"""
print()
print("=" * 80)
print("测试 2: Underlying_Operations.get_screenshot()")
print("=" * 80)
try:
from Underlying_Operations import underlying_operations
device_id = os.environ.get("DEVICE_ID", "MB75DEFQZHZTGMLJ")
print(f"设备ID: {device_id}")
print()
ops = underlying_operations()
# 测试默认参数
print("测试 2.1: 使用默认参数(应该是 False)")
start = time.time()
try:
result = ops.get_screenshot(device_id)
elapsed = (time.time() - start) * 1000
status = "[OK] 成功" if result else "[FAIL] 失败"
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
if elapsed > 2000:
print(f" [WARN] 警告:耗时较长 ({elapsed:.1f}ms),但应该 < 2秒")
elif elapsed > 6000:
print(f" [ERROR] 错误:耗时过长 ({elapsed:.1f}ms),可能仍在使用服务模式")
else:
print(f" [OK] 正常:耗时在预期范围内")
except Exception as e:
elapsed = (time.time() - start) * 1000
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
import traceback
traceback.print_exc()
return True
except Exception as e:
print(f"[ERROR] 测试失败: {e}")
import traceback
traceback.print_exc()
return False
def test_stage_diagnosis_screenshot():
"""测试阶段诊断中的截图调用"""
print()
print("=" * 80)
print("测试 3: 阶段诊断截图调用(模拟)")
print("=" * 80)
try:
# 检查关键文件中的调用
import inspect
from douyin.core import douyin_fudai
# 查找 get_screenshot 调用
source_file = inspect.getfile(douyin_fudai.fudai_analyse)
with open(source_file, 'r', encoding='utf-8') as f:
content = f.read()
# 检查是否包含 use_service=False
if 'get_screenshot(self.device_id, use_service=False)' in content:
print(" [OK] 确认:douyin_fudai.py 中已使用 use_service=False")
elif 'get_screenshot(self.device_id)' in content:
print(" [WARN] 警告:douyin_fudai.py 中未显式传递 use_service=False")
print(" (但默认值应该是 False)")
else:
print(" [WARN] 未找到 get_screenshot 调用")
return True
except Exception as e:
print(f" [WARN] 无法检查: {e}")
return False
def check_logs_for_timeouts():
"""检查日志中是否有超时记录"""
print()
print("=" * 80)
print("测试 4: 检查日志中的超时记录")
print("=" * 80)
try:
import glob
log_files = glob.glob("logs/unified_*.log")
if not log_files:
print(" [WARN] 未找到日志文件")
return True
# 读取最新的日志文件
latest_log = max(log_files, key=os.path.getmtime)
print(f" 检查日志文件: {latest_log}")
timeout_count = 0
screenshot_count = 0
with open(latest_log, 'r', encoding='utf-8', errors='ignore') as f:
# 只读取最后 1000 行
lines = f.readlines()[-1000:]
for line in lines:
if '[TIMEOUT] 等待超时' in line or '等待超时' in line:
timeout_count += 1
if 'screenshot_elapsed_seconds' in line:
screenshot_count += 1
# 提取耗时
try:
import re
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if match:
elapsed = float(match.group(1))
if elapsed > 5.0:
print(f" [WARN] 发现耗时过长的截图: {elapsed:.2f}秒")
except Exception:
pass
print(f" 超时记录数(最近1000行): {timeout_count}")
print(f" 截图耗时记录数: {screenshot_count}")
if timeout_count == 0:
print(" [OK] 未发现超时记录(符合预期)")
else:
print(f" [WARN] 发现 {timeout_count} 条超时记录")
return True
except Exception as e:
print(f" [WARN] 无法检查日志: {e}")
return False
def main():
"""主测试函数"""
print()
print("=" * 80)
print("直接截图功能测试")
print("=" * 80)
print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
results = []
# 测试1: screenshot_operations
results.append(("screenshot_operations", test_screenshot_operations()))
# 测试2: underlying_operations
results.append(("underlying_operations", test_underlying_operations()))
# 测试3: 代码检查
results.append(("stage_diagnosis", test_stage_diagnosis_screenshot()))
# 测试4: 日志检查
results.append(("log_check", check_logs_for_timeouts()))
# 总结
print()
print("=" * 80)
print("测试总结")
print("=" * 80)
passed = sum(1 for _, result in results if result)
total = len(results)
for name, result in results:
status = "[PASS] 通过" if result else "[FAIL] 失败"
print(f" {name}: {status}")
print()
print(f"总计: {passed}/{total} 测试通过")
if passed == total:
print("[SUCCESS] 所有测试通过!")
return 0
else:
print("[WARN] 部分测试未通过,请检查上述输出")
return 1
if __name__ == "__main__":
exit(main())
@@ -1,118 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试禁用流式截图功能
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_disable_streaming_screenshots():
"""测试禁用流式截图功能"""
print("测试禁用流式截图功能...")
print("=" * 50)
# 1. 检查截图服务的默认行为
print("\n1. 检查截图服务默认行为")
from operations.screenshot_operations import ScreenshotOperations
ops = ScreenshotOperations()
# 检查get_screenshot方法的默认参数
import inspect
sig = inspect.signature(ops.get_screenshot)
params = sig.parameters
use_service_default = params['use_service'].default
print(f"get_screenshot use_service 默认值: {use_service_default}")
if use_service_default == False:
print("[OK] 默认禁用后台服务,使用直接截图")
else:
print("[FAIL] 仍然使用后台服务")
# 2. 模拟截图调用
print("\n2. 模拟截图调用测试")
# 创建模拟的analyser
class MockAnalyser:
def __init__(self):
self.device_id = "test_device_123"
self.operation = ops
def _log_kv(self, key, value, **kwargs):
print(f"[{key}] {value}")
analyser = MockAnalyser()
# 测试调用(这里不会实际执行截图,因为没有真实设备)
try:
# 这里只是检查方法调用路径,不会实际截图
print("截图方法调用路径:")
print("- get_screenshot(use_service=False) -> 直接截图")
print("- 跳过后台服务检查")
print("[OK] 确认使用直接截图模式")
except Exception as e:
print(f"[ERROR] 测试失败: {e}")
# 3. 检查后台服务状态
print("\n3. 检查后台服务状态")
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
if service.is_running():
print("[WARN] 后台服务正在运行(可能有其他地方启动)")
else:
print("[OK] 后台服务未运行")
print(f"服务状态: running={service.is_running()}")
print(f"当前设备ID: {service._current_device_id}")
except Exception as e:
print(f"检查服务状态失败: {e}")
# 4. 验证修改的文件
print("\n4. 验证修改的文件")
modified_files = [
"operations/screenshot_operations.py",
"douyin/core/douyin_fudai.py",
"douyin/core/douyin_main_flow.py"
]
for file_path in modified_files:
if os.path.exists(file_path):
print(f"[OK] {file_path} 存在")
else:
print(f"[ERROR] {file_path} 不存在")
# 5. 总结
print("\n5. 修改总结")
print("-" * 30)
print("已完成的修改:")
print("1. [DONE] 修改 get_screenshot() 默认 use_service=False")
print("2. [DONE] 移除 douyin_fudai.py 中的后台服务启动")
print("3. [DONE] 移除 douyin_main_flow.py 中的后台服务启动")
print("4. [DONE] 所有截图调用将使用直接截图模式")
print("\n预期效果:")
print("- 每次截图都会直接调用ADB命令")
print("- 不再有后台截图服务持续运行")
print("- 截图响应时间会变慢,但更稳定")
print("- 消除了后台服务的复杂性")
return True
if __name__ == "__main__":
success = test_disable_streaming_screenshots()
print(f"\n{'='*50}")
print(f"测试结果: {'PASS' if success else 'FAIL'}")
print("流式截图已暂时禁用,使用直接截图模式")
print(f"{'='*50}")
@@ -1,95 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试循环期间停止后台截图服务的功能
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_loop_screenshot_service_stop():
"""测试循环期间后台截图服务是否被停止"""
print("测试循环期间停止后台截图服务功能...")
# 1. 启动截图服务(模拟正常启动)
print("\n1. 启动后台截图服务...")
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
device_id = "emulator-5554"
if not service.is_running():
service.start(device_id, interval=1.5)
time.sleep(0.5)
if service.is_running():
print("[OK] 后台截图服务已启动")
else:
print("[FAIL] 后台截图服务启动失败")
return False
# 2. 模拟fudai_choujiang的逻辑
print("\n2. 模拟循环开始前的截图服务停止...")
# 这部分代码模拟fudai_choujiang中的逻辑
screenshot_service_stopped = False
try:
service_inner = ScreenshotService.get_instance()
if service_inner.is_running():
service_inner.stop()
screenshot_service_stopped = True
print("[OK] 循环开始前停止后台截图服务")
except Exception as e:
print(f"[FAIL] 停止后台截图服务失败: {e}")
return False
# 检查服务是否已停止
if service.is_running():
print("[FAIL] 后台截图服务仍然在运行")
return False
else:
print("[OK] 后台截图服务已停止")
# 3. 模拟循环中的操作(这里不会触发截图服务)
print("\n3. 模拟循环中的阶段诊断...")
time.sleep(2) # 模拟一些操作
# 4. 模拟程序结束(atexit会重新启动服务)
print("\n4. 模拟程序结束,检查服务重新启动...")
# 手动调用atexit函数(在实际运行中会自动调用)
if screenshot_service_stopped:
try:
service_restart = ScreenshotService.get_instance()
if device_id:
service_restart.start(device_id, interval=1.5)
print("[OK] 循环结束后重新启动后台截图服务")
except Exception as e:
print(f"[FAIL] 重新启动后台截图服务失败: {e}")
return False
# 检查服务是否重新启动
time.sleep(0.5)
if service.is_running():
print("[OK] 后台截图服务已重新启动")
success = True
else:
print("[FAIL] 后台截图服务未重新启动")
success = False
# 5. 清理
if service.is_running():
service.stop()
print("\n5. 测试完成,停止后台截图服务")
print(f"\n测试结果: {'PASS' if success else 'FAIL'}")
return success
if __name__ == "__main__":
success = test_loop_screenshot_service_stop()
sys.exit(0 if success else 1)
@@ -1,100 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR多线程优化效果
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from operations.screenshot_service import get_optimal_workers
def test_ocr_multithread_config():
"""测试OCR多线程配置"""
print("=" * 70)
print("OCR多线程配置检查")
print("=" * 70)
print()
# 1. CPU信息
cpu_count = os.cpu_count() or 4
print(f"1. CPU信息")
print("-" * 70)
print(f" CPU核心数: {cpu_count}")
print()
# 2. OMP线程数配置
print("2. OMP线程数配置(底层库多线程)")
print("-" * 70)
omp_threads = os.environ.get("OMP_NUM_THREADS", "未设置")
print(f" OMP_NUM_THREADS: {omp_threads}")
# 计算推荐的OMP线程数
optimal_omp_threads = min(4, max(2, cpu_count // 3))
print(f" 推荐值: {optimal_omp_threads} (根据CPU核心数动态计算)")
print()
# 3. 线程池大小配置
print("3. 线程池大小配置(任务级多线程)")
print("-" * 70)
optimal_workers = get_optimal_workers()
print(f" 推荐线程池大小: {optimal_workers} (根据CPU核心数动态计算)")
print(f" 说明: 用于并行执行多个OCR任务")
print()
# 4. 优化说明
print("4. 优化说明")
print("-" * 70)
print(" 优化前:")
print(" - OMP_NUM_THREADS=1 (限制底层库只能使用1个线程)")
print(" - 线程池大小固定为6 (未充分利用多核CPU)")
print()
print(" 优化后:")
print(f" - OMP_NUM_THREADS={optimal_omp_threads} (允许底层库使用多线程)")
print(f" - 线程池大小={optimal_workers} (根据CPU核心数动态调整)")
print()
print(" 预期效果:")
print(" - 底层库(PaddleOCR/EasyOCR)可以并行处理图像")
print(" - 多个OCR任务可以并行执行")
print(" - 充分利用多核CPU资源")
print(" - 预计性能提升: 30-50% (取决于任务数量和CPU核心数)")
print()
# 5. 验证OCR引擎是否已初始化
print("5. OCR引擎状态")
print("-" * 70)
try:
from operations.ocr_operations import _ocr_processor
if _ocr_processor.ocr is not None:
print(f" OCR引擎: {_ocr_processor.ocr_type}")
print(" 状态: 已初始化")
else:
print(" 状态: 未初始化(延迟初始化)")
except Exception as e:
print(f" 状态: 检查失败 - {e}")
print()
print("=" * 70)
print("检查完成")
print("=" * 70)
def test_ocr_performance():
"""测试OCR性能(需要实际运行OCR)"""
print()
print("=" * 70)
print("OCR性能测试")
print("=" * 70)
print()
print("提示: 此测试需要实际运行OCR任务")
print(" 可以在实际使用中观察OCR耗时变化")
print()
print("测试方法:")
print("1. 运行程序,观察OCR任务的耗时")
print("2. 对比优化前后的性能差异")
print("3. 查看日志中的OCR耗时信息")
print()
if __name__ == "__main__":
test_ocr_multithread_config()
test_ocr_performance()
@@ -1,325 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OCR多线程性能测试
测试优化前后的性能差异
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import numpy as np
import tempfile
def test_ocr_single(image_path, ocr_processor, omp_threads):
"""测试单个OCR任务的性能"""
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
start_time = time.time()
if ocr_processor.ocr_type == "easyocr":
result = ocr_processor.ocr.readtext(img_np)
else:
result = ocr_processor.ocr.ocr(img_np)
elapsed = (time.time() - start_time) * 1000
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
return {
'time': elapsed,
'text': text,
'success': True
}
except Exception as e:
return {
'time': 0,
'text': '',
'success': False,
'error': str(e)
}
finally:
os.environ['OMP_NUM_THREADS'] = old_omp
def test_ocr_config(image_path, config_name, omp_threads, num_iterations=5):
"""测试特定配置下的OCR性能"""
print(f"\n{'='*70}")
print(f"测试配置: {config_name}")
print(f"{'='*70}")
print(f"OMP_NUM_THREADS: {omp_threads}")
print(f"迭代次数: {num_iterations}")
print()
# 初始化OCR
try:
from operations.ocr_operations import OCRProcessor
ocr_processor = OCRProcessor()
ensure_ocr = getattr(ocr_processor, '_ensure_ocr')
ensure_ocr()
if ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return None
print(f"OCR引擎: {ocr_processor.ocr_type}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
return None
# 执行多次测试
times = []
for i in range(num_iterations):
result = test_ocr_single(image_path, ocr_processor, omp_threads)
if result['success']:
times.append(result['time'])
print(f" 第{i+1}次: {result['time']:.0f}ms - {result['text'][:30] if result['text'] else '(空)'}")
else:
print(f" 第{i+1}次: 失败 - {result.get('error', 'Unknown')}")
if not times:
print("[ERROR] 所有测试都失败")
return None
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print()
print(f"平均耗时: {avg_time:.0f}ms")
print(f"最快: {min_time:.0f}ms")
print(f"最慢: {max_time:.0f}ms")
print()
return {
'avg_time': avg_time,
'min_time': min_time,
'max_time': max_time,
'times': times
}
def test_parallel_ocr(image_path, config_name, omp_threads, max_workers, num_tasks=6):
"""测试并行OCR性能"""
print(f"\n{'='*70}")
print(f"测试配置: {config_name}")
print(f"{'='*70}")
print(f"OMP_NUM_THREADS: {omp_threads}")
print(f"线程池大小: {max_workers}")
print(f"任务数量: {num_tasks}")
print()
# 设置OMP线程数
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
# 初始化OCR
try:
from operations.ocr_operations import OCRProcessor
ocr_processor = OCRProcessor()
ensure_ocr = getattr(ocr_processor, '_ensure_ocr')
ensure_ocr()
if ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
print(f"OCR引擎: {ocr_processor.ocr_type}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
# 创建多个相同的任务(使用同一张图片)
def ocr_task():
return test_ocr_single(image_path, ocr_processor, omp_threads)
# 并行执行
print("开始并行OCR识别...")
start_time = time.time()
results = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(ocr_task) for _ in range(num_tasks)]
for i, future in enumerate(futures):
try:
result = future.result(timeout=60)
results.append(result)
if result['success']:
print(f" 任务{i+1}: {result['time']:.0f}ms - {result['text'][:20] if result['text'] else '(空)'}")
else:
print(f" 任务{i+1}: 失败 - {result.get('error', 'Unknown')}")
except Exception as e:
print(f" 任务{i+1}: 异常 - {e}")
results.append({'success': False, 'error': str(e)})
total_elapsed = (time.time() - start_time) * 1000
# 恢复OMP设置
os.environ['OMP_NUM_THREADS'] = old_omp
# 统计结果
successful_results = [r for r in results if r.get('success', False)]
efficiency = 0 # 初始化效率变量
if successful_results:
task_times = [r['time'] for r in successful_results]
total_task_time = sum(task_times)
avg_task_time = total_task_time / len(task_times)
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
print(f"任务总耗时: {total_task_time:.0f}ms")
print(f"平均每个任务: {avg_task_time:.0f}ms")
if total_task_time > 0:
efficiency = total_task_time / total_elapsed
print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)")
print()
return {
'total_time': total_elapsed,
'avg_task_time': avg_task_time,
'task_times': task_times,
'efficiency': efficiency if total_task_time > 0 else 0
}
else:
print("[ERROR] 所有任务都失败")
return None
def main():
"""主函数"""
# 默认图片路径
default_image = "pic/debug_captures/2025-12-31/20251231_152118_ocr_福袋倒计时_分钟_识别后_(390,1110)-(480,1230)_模式_1_文本长度_2_数字_14_类型_digits_平均置信度_0.9991_最小置信度_0.9991_最大置信度_0.9991_置信度项数_1_有完整截图_是_有坐标_是.png"
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
if not os.path.isabs(image_path):
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
print("=" * 70)
print("OCR多线程性能测试")
print("=" * 70)
print()
print(f"测试图片: {os.path.basename(image_path)}")
# 获取系统信息
cpu_count = os.cpu_count() or 4
print(f"CPU核心数: {cpu_count}")
try:
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
print(f"推荐线程池大小: {optimal_workers}")
except (ImportError, AttributeError):
optimal_workers = 6
print()
# 测试1: 单次OCR - 优化前
print("\n" + "="*70)
print("测试1: 单次OCR性能对比")
print("="*70)
result_single_old = test_ocr_config(
image_path,
"优化前 (OMP_NUM_THREADS=1)",
omp_threads=1,
num_iterations=5
)
time.sleep(1)
# 测试2: 单次OCR - 优化后
result_single_new = test_ocr_config(
image_path,
"优化后 (OMP_NUM_THREADS=6)",
omp_threads=6,
num_iterations=5
)
# 测试3: 并行OCR - 优化前
print("\n" + "="*70)
print("测试2: 并行OCR性能对比")
print("="*70)
result_parallel_old = test_parallel_ocr(
image_path,
"优化前 (OMP=1, workers=6)",
omp_threads=1,
max_workers=6,
num_tasks=6
)
time.sleep(1)
# 测试4: 并行OCR - 优化后
result_parallel_new = test_parallel_ocr(
image_path,
"优化后 (OMP=6, workers=10)",
omp_threads=6,
max_workers=optimal_workers,
num_tasks=6
)
# 性能对比总结
print()
print("=" * 70)
print("性能对比总结")
print("=" * 70)
print()
if result_single_old and result_single_new:
old_avg = result_single_old['avg_time']
new_avg = result_single_new['avg_time']
speedup = old_avg / new_avg if new_avg > 0 else 0
print("单次OCR性能:")
print(f" 优化前平均: {old_avg:.0f}ms")
print(f" 优化后平均: {new_avg:.0f}ms")
print(f" 性能提升: {speedup:.2f}x")
print(f" 时间减少: {(1 - new_avg/old_avg)*100:.1f}%")
print()
if result_parallel_old and result_parallel_new:
old_total = result_parallel_old['total_time']
new_total = result_parallel_new['total_time']
speedup = old_total / new_total if new_total > 0 else 0
print("并行OCR性能:")
print(f" 优化前总耗时: {old_total:.0f}ms ({old_total/1000:.2f}秒)")
print(f" 优化后总耗时: {new_total:.0f}ms ({new_total/1000:.2f}秒)")
print(f" 性能提升: {speedup:.2f}x")
print(f" 时间减少: {(1 - new_total/old_total)*100:.1f}%")
print()
old_avg = result_parallel_old['avg_task_time']
new_avg = result_parallel_new['avg_task_time']
print("单任务性能:")
print(f" 优化前平均任务: {old_avg:.0f}ms")
print(f" 优化后平均任务: {new_avg:.0f}ms")
print(f" 单任务性能提升: {old_avg/new_avg:.2f}x" if new_avg > 0 else " 单任务性能提升: N/A")
print()
print("=" * 70)
print("测试完成")
print("=" * 70)
if __name__ == "__main__":
main()
-196
View File
@@ -1,196 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR识别速度
"""
import os
import sys
import time
from pathlib import Path
def test_ocr_speed(image_path: str, iterations: int = 5):
"""测试OCR识别速度"""
print("=" * 70)
print("OCR速度测试")
print("=" * 70)
print()
# 检查图片文件是否存在
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
file_size = os.path.getsize(image_path) / 1024 # KB
print(f"测试图片: {image_path}")
print(f"文件大小: {file_size:.2f} KB")
print(f"测试次数: {iterations} 次")
print()
# 获取图片信息
try:
from PIL import Image
img = Image.open(image_path)
width, height = img.size
print(f"图片尺寸: {width}x{height}")
print(f"图片模式: {img.mode}")
# 计算图片像素数
total_pixels = width * height
print(f"总像素数: {total_pixels:,}")
# 判断图片大小
if total_pixels > 2000000: # 大于200万像素
print(f" [提示] 图片较大,OCR处理可能需要较长时间")
print(f" 建议: 先裁剪到目标区域(如200x200)再OCR,可以显著提升速度")
print()
except Exception as e:
print(f"[WARNING] 无法读取图片信息: {e}")
print()
# 检查OCR引擎
print("1. OCR引擎信息")
print("-" * 70)
try:
from operations.ocr_operations import _ocr_processor
_ocr_processor._ensure_ocr()
if _ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return
print(f" OCR引擎: {_ocr_processor.ocr_type}")
print(f" OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎检查失败: {e}")
return
# 测试OCR速度
print("2. OCR速度测试")
print("-" * 70)
times = []
results = []
for i in range(iterations):
try:
# 导入OCR操作
from Underlying_Operations import underlying_operations
ops = underlying_operations()
# 确保OCR已初始化
ops._ensure_ocr()
# 执行OCR(使用analyse_pic_digits,因为这是数字识别)
start_time = time.time()
# 直接使用图片路径进行OCR
# 注意:如果图片很大,OCR会处理整个图片,这可能会很慢
# 建议使用预处理后的小图片进行测试
result = ops.analyse_pic_digits(
"测试图片",
change_color=1, # 数字识别模式
pic_path=image_path
)
# 记录各个阶段的耗时(如果可能)
# 注意:analyse_pic_digits 内部会进行图像预处理和OCR识别
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
times.append(elapsed)
results.append(result)
print(f" 第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {result[:50] if result else '(空)'}")
except Exception as e:
print(f" 第 {i+1} 次: 失败 - {e}")
import traceback
traceback.print_exc()
print()
# 统计结果
if times:
print("3. 性能统计")
print("-" * 70)
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f" 平均耗时: {avg_time:.0f}ms")
print(f" 最快耗时: {min_time:.0f}ms")
print(f" 最慢耗时: {max_time:.0f}ms")
print(f" 耗时范围: {max_time - min_time:.0f}ms")
print()
# 识别结果统计
print("4. 识别结果")
print("-" * 70)
unique_results = list(set(results))
for i, result in enumerate(unique_results, 1):
count = results.count(result)
print(f" 结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)")
print()
# 性能评估
print("5. 性能评估")
print("-" * 70)
if avg_time < 500:
print(" [优秀] OCR速度很快 (< 500ms)")
elif avg_time < 1000:
print(" [良好] OCR速度良好 (500-1000ms)")
elif avg_time < 2000:
print(" [一般] OCR速度一般 (1000-2000ms)")
elif avg_time < 5000:
print(" [较慢] OCR速度较慢 (2000-5000ms)")
else:
print(" [很慢] OCR速度很慢 (> 5000ms)")
print(" 提示: 如果图片很大,建议先裁剪到目标区域再OCR")
# 多线程效果评估
cpu_count = os.cpu_count() or 4
omp_threads = int(os.environ.get('OMP_NUM_THREADS', '1'))
print(f" CPU核心数: {cpu_count}")
print(f" OMP线程数: {omp_threads}")
if omp_threads > 1:
print(f" [优化] 已启用底层多线程 (OMP_NUM_THREADS={omp_threads})")
else:
print(f" [提示] 未启用底层多线程,可以优化")
print()
else:
print("[ERROR] 所有测试都失败了")
print("=" * 70)
print("测试完成")
print("=" * 70)
def main():
"""主函数"""
# 默认图片路径
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
# 从命令行参数获取图片路径
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
# 获取测试次数
iterations = 5
if len(sys.argv) > 2:
try:
iterations = int(sys.argv[2])
except:
pass
# 转换为绝对路径
if not os.path.isabs(image_path):
# 尝试相对于项目根目录
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
test_ocr_speed(image_path, iterations)
if __name__ == "__main__":
main()
@@ -1,212 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR识别速度(优化版 - 支持裁剪区域测试)
"""
import os
import sys
import time
from typing import Optional
from PIL import Image
def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iterations: int = 5):
"""在指定区域测试OCR速度"""
print("=" * 70)
print("OCR速度测试(区域优化版)")
print("=" * 70)
print()
# 检查图片文件是否存在
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
# 加载图片
try:
img = Image.open(image_path)
original_size = img.size
print(f"原始图片: {image_path}")
print(f"原始尺寸: {original_size[0]}x{original_size[1]}")
print(f"原始像素数: {original_size[0] * original_size[1]:,}")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
return
# 如果指定了区域,裁剪图片
if region:
x1, y1, x2, y2 = region
img = img.crop((x1, y1, x2, y2))
print(f"裁剪区域: ({x1}, {y1}) - ({x2}, {y2})")
print(f"裁剪后尺寸: {img.size[0]}x{img.size[1]}")
print(f"裁剪后像素数: {img.size[0] * img.size[1]:,}")
print()
# 保存裁剪后的临时图片
import tempfile
temp_dir = tempfile.gettempdir()
temp_image = os.path.join(temp_dir, "ocr_test_crop.png")
img.save(temp_image)
test_image_path = temp_image
else:
test_image_path = image_path
# 测试OCR速度
print("开始OCR速度测试...")
print("-" * 70)
try:
from operations.ocr_operations import _ocr_processor
_ocr_processor._ensure_ocr()
if _ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return
print(f"OCR引擎: {_ocr_processor.ocr_type}")
print(f"OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎检查失败: {e}")
return
# 执行多次测试
times = []
results = []
for i in range(iterations):
try:
import numpy as np
# 准备图像
if img.mode != 'RGB':
img_rgb = img.convert('RGB')
else:
img_rgb = img
# 转换为numpy数组
img_np = np.array(img_rgb)
# 执行OCR
start_time = time.time()
if _ocr_processor.ocr_type == "easyocr":
result = _ocr_processor.ocr.readtext(img_np)
else:
result = _ocr_processor.ocr.ocr(img_np)
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
times.append(elapsed)
results.append(text)
print(f"第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {text[:50] if text else '(空)'}")
except Exception as e:
print(f"第 {i+1} 次: 失败 - {e}")
import traceback
traceback.print_exc()
print()
# 统计结果
if times:
print("性能统计")
print("-" * 70)
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f"平均耗时: {avg_time:.0f}ms ({avg_time/1000:.2f}秒)")
print(f"最快耗时: {min_time:.0f}ms ({min_time/1000:.2f}秒)")
print(f"最慢耗时: {max_time:.0f}ms ({max_time/1000:.2f}秒)")
print(f"耗时范围: {max_time - min_time:.0f}ms")
print()
# 识别结果
print("识别结果")
print("-" * 70)
unique_results = list(set(results))
for i, result in enumerate(unique_results, 1):
count = results.count(result)
print(f"结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)")
print()
# 性能对比
if region:
original_pixels = original_size[0] * original_size[1]
crop_pixels = img.size[0] * img.size[1]
reduction = (1 - crop_pixels / original_pixels) * 100
print("性能对比")
print("-" * 70)
print(f"原始图片像素: {original_pixels:,}")
print(f"裁剪后像素: {crop_pixels:,}")
print(f"像素减少: {reduction:.1f}%")
print(f"预计原始图片OCR耗时: {avg_time * (original_pixels / crop_pixels):.0f}ms")
print()
# 清理临时文件
if region and os.path.exists(test_image_path):
try:
os.remove(test_image_path)
except:
pass
print("=" * 70)
print("测试完成")
print("=" * 70)
def main():
"""主函数"""
# 默认图片路径
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
# 从命令行参数获取图片路径
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
# 转换为绝对路径
if not os.path.isabs(image_path):
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
# 从文件名提取区域信息(如果文件名包含坐标)
region = None
if "(480,1110)-(570,1230)" in image_path:
# 提取坐标
region = (480, 1110, 570, 1230)
print("[INFO] 检测到文件名中的坐标信息,将使用裁剪区域进行测试")
print()
# 获取测试次数
iterations = 5
if len(sys.argv) > 2:
try:
iterations = int(sys.argv[2])
except:
pass
# 先测试完整图片
print("=" * 70)
print("测试1: 完整图片OCR")
print("=" * 70)
test_ocr_on_region(image_path, region=None, iterations=iterations)
# 如果检测到区域信息,再测试裁剪区域
if region:
print()
print("=" * 70)
print("测试2: 裁剪区域OCR(推荐)")
print("=" * 70)
test_ocr_on_region(image_path, region=region, iterations=iterations)
if __name__ == "__main__":
main()
@@ -1,383 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试并行OCR性能,对比优化前后的提升
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import numpy as np
def test_serial_ocr(image_path: str, num_tasks: int = 3):
"""测试串行OCR(优化前的方式)"""
print("=" * 70)
print("测试1: 串行OCR(优化前)")
print("=" * 70)
print(f"任务数量: {num_tasks}")
print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
print()
# 加载图片
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
print(f"图片尺寸: {img.size[0]}x{img.size[1]}")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
return None
# 初始化OCR
try:
from operations.ocr_operations import _ocr_processor
_ocr_processor._ensure_ocr()
if _ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return None
print(f"OCR引擎: {_ocr_processor.ocr_type}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
return None
# 串行执行OCR任务
start_time = time.time()
results = []
print("开始串行OCR测试...")
for i in range(num_tasks):
task_start = time.time()
try:
if _ocr_processor.ocr_type == "easyocr":
result = _ocr_processor.ocr.readtext(img_np)
else:
result = _ocr_processor.ocr.ocr(img_np)
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
task_elapsed = (time.time() - task_start) * 1000
results.append(text)
print(f" 任务 {i+1}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {text[:30] if text else '(空)'}")
except Exception as e:
print(f" 任务 {i+1}/{num_tasks}: 失败 - {e}")
results.append(None)
total_elapsed = (time.time() - start_time) * 1000
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms")
print()
return total_elapsed
def test_parallel_ocr(image_path: str, num_tasks: int = 3):
"""测试并行OCR(优化后的方式)"""
print("=" * 70)
print("测试2: 并行OCR(优化后)")
print("=" * 70)
print(f"任务数量: {num_tasks}")
print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
# 获取最优线程数
try:
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
print(f"线程池大小: {optimal_workers}")
except:
optimal_workers = 6
print(f"线程池大小: {optimal_workers} (默认)")
print()
# 加载图片
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
print(f"图片尺寸: {img.size[0]}x{img.size[1]}")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
return None
# 初始化OCR
try:
from operations.ocr_operations import _ocr_processor
_ocr_processor._ensure_ocr()
if _ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return None
print(f"OCR引擎: {_ocr_processor.ocr_type}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
return None
# 定义OCR任务函数
def ocr_task(task_id):
"""单个OCR任务"""
try:
if _ocr_processor.ocr_type == "easyocr":
result = _ocr_processor.ocr.readtext(img_np)
else:
result = _ocr_processor.ocr.ocr(img_np)
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
return text
except Exception as e:
print(f" 任务 {task_id} 失败: {e}")
return None
# 并行执行OCR任务
start_time = time.time()
results = []
print("开始并行OCR测试...")
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
# 提交所有任务
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
# 收集结果
task_times = {}
for future in futures:
task_id = futures[future]
task_start = time.time()
try:
result = future.result()
task_elapsed = (time.time() - task_start) * 1000
task_times[task_id] = task_elapsed
results.append(result)
print(f" 任务 {task_id}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {result[:30] if result else '(空)'}")
except Exception as e:
print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}")
results.append(None)
total_elapsed = (time.time() - start_time) * 1000
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
if task_times:
avg_task_time = sum(task_times.values()) / len(task_times)
print(f"平均每个任务: {avg_task_time:.0f}ms")
print(f"并行效率: {avg_task_time * num_tasks / total_elapsed:.1f}x (理想情况下应该接近{num_tasks}x)")
print()
return total_elapsed
def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3):
"""测试并行OCR(使用旧的配置:OMP_NUM_THREADS=1, max_workers=6)"""
print("=" * 70)
print("测试3: 并行OCR(旧配置:OMP=1, 线程池=6)")
print("=" * 70)
print(f"任务数量: {num_tasks}")
# 临时设置旧配置
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
os.environ['OMP_NUM_THREADS'] = '1'
print(f"OMP_NUM_THREADS: 1 (临时设置)")
print(f"线程池大小: 6 (固定)")
print()
# 加载图片
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
print(f"图片尺寸: {img.size[0]}x{img.size[1]}")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
# 重新初始化OCR(使用新的OMP设置)
try:
from operations.ocr_operations import _ocr_processor
# 注意:OCR引擎已经初始化,OMP设置可能不会立即生效
# 但我们可以测试线程池的效果
print(f"OCR引擎: {_ocr_processor.ocr_type}")
print("注意: OMP设置可能需要重启程序才能完全生效")
print()
except Exception as e:
print(f"[ERROR] OCR引擎检查失败: {e}")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
# 定义OCR任务函数
def ocr_task(task_id):
"""单个OCR任务"""
try:
if _ocr_processor.ocr_type == "easyocr":
result = _ocr_processor.ocr.readtext(img_np)
else:
result = _ocr_processor.ocr.ocr(img_np)
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
return text
except Exception as e:
print(f" 任务 {task_id} 失败: {e}")
return None
# 并行执行OCR任务(使用旧的线程池大小)
start_time = time.time()
results = []
print("开始并行OCR测试(旧配置)...")
with ThreadPoolExecutor(max_workers=6) as executor:
# 提交所有任务
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
# 收集结果
task_times = {}
for future in futures:
task_id = futures[future]
task_start = time.time()
try:
result = future.result()
task_elapsed = (time.time() - task_start) * 1000
task_times[task_id] = task_elapsed
results.append(result)
print(f" 任务 {task_id}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {result[:30] if result else '(空)'}")
except Exception as e:
print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}")
results.append(None)
total_elapsed = (time.time() - start_time) * 1000
# 恢复OMP设置
os.environ['OMP_NUM_THREADS'] = old_omp
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
if task_times:
avg_task_time = sum(task_times.values()) / len(task_times)
print(f"平均每个任务: {avg_task_time:.0f}ms")
print()
return total_elapsed
def main():
"""主函数"""
# 默认图片路径
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
# 从命令行参数获取图片路径
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
# 转换为绝对路径
if not os.path.isabs(image_path):
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
# 检查文件是否存在
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
# 获取任务数量(默认3个,减少测试时间)
num_tasks = 3
if len(sys.argv) > 2:
try:
num_tasks = int(sys.argv[2])
except:
pass
print("=" * 70)
print("并行OCR性能对比测试")
print("=" * 70)
print()
print(f"测试图片: {os.path.basename(image_path)}")
print(f"任务数量: {num_tasks}")
print()
# 获取当前配置信息
cpu_count = os.cpu_count() or 4
omp_threads = os.environ.get('OMP_NUM_THREADS', '未设置')
print(f"系统信息:")
print(f" CPU核心数: {cpu_count}")
print(f" OMP_NUM_THREADS: {omp_threads}")
try:
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
print(f" 推荐线程池大小: {optimal_workers}")
except:
pass
print()
print()
# 测试1: 串行OCR
serial_time = test_serial_ocr(image_path, num_tasks)
print()
print()
# 测试2: 并行OCR(优化后)
parallel_time = test_parallel_ocr(image_path, num_tasks)
print()
print()
# 测试3: 并行OCR(旧配置)
parallel_old_time = test_parallel_ocr_old_config(image_path, num_tasks)
# 性能对比总结
print()
print("=" * 70)
print("性能对比总结")
print("=" * 70)
print()
if serial_time and parallel_time:
speedup = serial_time / parallel_time
print(f"串行OCR: {serial_time:.0f}ms ({serial_time/1000:.2f}秒)")
print(f"并行OCR: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)")
print(f"性能提升: {speedup:.2f}x ({(1 - parallel_time/serial_time)*100:.1f}% 时间减少)")
print()
if parallel_old_time and parallel_time:
speedup_vs_old = parallel_old_time / parallel_time
print(f"旧配置并行: {parallel_old_time:.0f}ms ({parallel_old_time/1000:.2f}秒)")
print(f"新配置并行: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)")
print(f"配置优化提升: {speedup_vs_old:.2f}x ({(1 - parallel_time/parallel_old_time)*100:.1f}% 时间减少)")
print()
if serial_time and parallel_time and parallel_old_time:
total_speedup = serial_time / parallel_time
print(f"总体优化效果:")
print(f" 串行 → 并行: {serial_time/parallel_time:.2f}x")
print(f" 旧配置 → 新配置: {parallel_old_time/parallel_time:.2f}x")
print(f" 串行 → 新配置: {total_speedup:.2f}x")
print()
print("=" * 70)
print("测试完成")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -1,141 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速测试并行OCR性能(只测试并行,不测试串行)
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import numpy as np
def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3):
"""快速测试并行OCR"""
print("=" * 70)
print("并行OCR性能测试(快速版)")
print("=" * 70)
print()
# 检查文件
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return None
# 加载图片
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
print(f"图片: {os.path.basename(image_path)}")
print(f"尺寸: {img.size[0]}x{img.size[1]}")
print(f"任务数: {num_tasks}")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
return None
# 初始化OCR
try:
from operations.ocr_operations import _ocr_processor
_ocr_processor._ensure_ocr()
if _ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
return None
print(f"OCR引擎: {_ocr_processor.ocr_type}")
print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
print(f"线程池大小: {optimal_workers}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
return None
# 定义OCR任务
def ocr_task(task_id):
try:
if _ocr_processor.ocr_type == "easyocr":
result = _ocr_processor.ocr.readtext(img_np)
else:
result = _ocr_processor.ocr.ocr(img_np)
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
return text
except Exception as e:
return f"错误: {e}"
# 执行并行OCR
print("开始并行OCR测试...")
start_time = time.time()
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
results = []
for future in futures:
task_id = futures[future]
try:
result = future.result()
results.append(result)
print(f" 任务 {task_id}: 完成, 结果: {result[:30] if result else '(空)'}")
except Exception as e:
print(f" 任务 {task_id}: 失败 - {e}")
results.append(None)
total_elapsed = (time.time() - start_time) * 1000
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms")
print()
# 估算串行时间(基于单次OCR耗时)
print("性能估算:")
print("-" * 70)
single_task_time = total_elapsed / num_tasks
estimated_serial_time = single_task_time * num_tasks
speedup = estimated_serial_time / total_elapsed if total_elapsed > 0 else 0
print(f"估算串行时间: {estimated_serial_time:.0f}ms ({estimated_serial_time/1000:.2f}秒)")
print(f"实际并行时间: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
print(f"性能提升: {speedup:.2f}x (节省 {(1 - total_elapsed/estimated_serial_time)*100:.1f}% 时间)")
print()
return total_elapsed
def main():
"""主函数"""
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
if not os.path.isabs(image_path):
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
num_tasks = 3
if len(sys.argv) > 2:
try:
num_tasks = int(sys.argv[2])
except:
pass
test_parallel_ocr_quick(image_path, num_tasks)
print("=" * 70)
print("测试完成")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -1,206 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版并行OCR性能对比测试
直接使用提供的图片进行测试
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import numpy as np
def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_tasks=6):
"""使用指定配置测试OCR"""
print(f"\n{'='*70}")
print(f"{config_name}")
print(f"{'='*70}")
print(f"OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}, 任务数={num_tasks}")
print()
# 设置OMP
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
# 加载图片
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
print(f"图片: {os.path.basename(image_path)}")
print(f"尺寸: {img.size[0]}x{img.size[1]} 像素")
print()
except Exception as e:
print(f"[ERROR] 无法加载图片: {e}")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
# 初始化OCR
try:
from operations.ocr_operations import OCRProcessor
ocr_processor = OCRProcessor()
ocr_processor._ensure_ocr()
if ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
print(f"OCR引擎: {ocr_processor.ocr_type}")
print()
except Exception as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
# OCR任务函数
def ocr_task(task_id):
try:
start = time.time()
if ocr_processor.ocr_type == "easyocr":
result = ocr_processor.ocr.readtext(img_np)
else:
result = ocr_processor.ocr.ocr(img_np)
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
elapsed = (time.time() - start) * 1000
return {'task_id': task_id, 'text': text, 'time': elapsed, 'success': True}
except Exception as e:
return {'task_id': task_id, 'text': '', 'time': 0, 'success': False, 'error': str(e)}
# 执行并行OCR
print("开始并行OCR测试...")
start_time = time.time()
results = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
for future in futures:
try:
result = future.result()
results.append(result)
status = "✓" if result['success'] else "✗"
print(f" {status} 任务{result['task_id']}: {result['time']:.0f}ms, 结果: {result['text'][:20] if result['text'] else '(空)'}")
except Exception as e:
print(f" ✗ 任务失败: {e}")
total_elapsed = (time.time() - start_time) * 1000
# 恢复OMP设置
os.environ['OMP_NUM_THREADS'] = old_omp
# 统计
successful = [r for r in results if r['success']]
total_task_time = sum(r['time'] for r in successful)
avg_task_time = total_task_time / len(successful) if successful else 0
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
print(f"任务总耗时: {total_task_time:.0f}ms")
print(f"平均每个任务: {avg_task_time:.0f}ms")
if total_task_time > 0:
efficiency = total_task_time / total_elapsed
print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)")
print()
return {
'total_time': total_elapsed,
'avg_task_time': avg_task_time,
'config': config_name
}
def main():
"""主函数"""
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
if not os.path.isabs(image_path):
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
print("=" * 70)
print("并行OCR性能对比测试(简化版)")
print("=" * 70)
print()
print(f"测试图片: {os.path.basename(image_path)}")
# 获取系统信息
cpu_count = os.cpu_count() or 4
print(f"CPU核心数: {cpu_count}")
try:
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
print(f"推荐线程池大小: {optimal_workers}")
except:
optimal_workers = 6
num_tasks = 6
print(f"测试任务数: {num_tasks}")
print()
# 测试1: 优化前
result_old = test_ocr_with_config(
image_path,
"优化前配置 (OMP=1, workers=6)",
omp_threads=1,
max_workers=6,
num_tasks=num_tasks
)
time.sleep(1) # 等待系统稳定
# 测试2: 优化后
result_new = test_ocr_with_config(
image_path,
"优化后配置 (OMP=4, workers=10)",
omp_threads=4,
max_workers=optimal_workers,
num_tasks=num_tasks
)
# 对比结果
print()
print("=" * 70)
print("性能对比总结")
print("=" * 70)
print()
if result_old and result_new:
old_time = result_old['total_time']
new_time = result_new['total_time']
speedup = old_time / new_time if new_time > 0 else 0
print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)")
print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)")
print(f"性能提升: {speedup:.2f}x")
print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%")
print()
old_avg = result_old['avg_task_time']
new_avg = result_new['avg_task_time']
print(f"优化前平均任务耗时: {old_avg:.0f}ms")
print(f"优化后平均任务耗时: {new_avg:.0f}ms")
if new_avg > 0:
print(f"单任务性能提升: {old_avg/new_avg:.2f}x")
print()
print("=" * 70)
print("测试完成")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -1,376 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
真实场景并行OCR性能对比测试
模拟实际使用中的多区域并行OCR识别
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import numpy as np
import tempfile
def create_test_regions(full_image_path):
"""从完整截图中创建多个测试区域(模拟真实OCR场景)"""
try:
img = Image.open(full_image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
width, height = img.size
# 判断是否是完整截图(1080x2400)还是裁剪区域
is_full_screenshot = width >= 1000 and height >= 2000
if is_full_screenshot:
# 完整截图:创建多个测试区域
# 模拟真实的OCR区域(基于福袋详情页的常见区域)
regions = {
"福袋倒计时_分钟": (400, 1050, 500, 1150), # 倒计时分钟区域
"福袋倒计时_秒": (480, 1110, 570, 1230), # 倒计时秒区域(用户提供的区域)
"福袋内容": (50, 800, 500, 1000), # 福袋内容区域
"福袋价值": (200, 1300, 400, 1400), # 价值区域
"任务列表": (50, 600, 500, 750), # 任务列表区域
"参与按钮": (300, 1500, 800, 1600), # 按钮状态区域
}
else:
# 裁剪区域:使用当前图片作为测试区域之一,创建其他相似大小的区域
# 从文件名提取坐标信息(如果存在)
coords_from_filename = None
if "(480,1110)-(570,1230)" in full_image_path:
coords_from_filename = (480, 1110, 570, 1230)
# 创建多个相似大小的测试区域
# 如果图片较小,创建多个相同大小的区域用于测试
# 这些区域会在完整截图的合理位置
regions = {}
# 使用当前图片作为第一个区域
if coords_from_filename:
x1, y1, x2, y2 = coords_from_filename
regions["福袋倒计时_秒"] = (x1, y1, x2, y2)
# 创建其他相邻区域
offset_x = x2 - x1
offset_y = y2 - y1
regions["福袋倒计时_分钟"] = (x1 - offset_x - 20, y1, x1 - 20, y2)
regions["福袋内容"] = (x1, y1 - offset_y - 20, x2, y1 - 20)
regions["福袋价值"] = (x1, y2 + 20, x2, y2 + offset_y + 20)
else:
# 如果无法从文件名提取坐标,使用图片本身作为唯一测试区域
# 创建多个相同大小的区域(通过复制当前图片)
regions["区域1"] = (0, 0, width, height)
regions["区域2"] = (0, 0, width, height) # 相同区域,用于测试并行
regions["区域3"] = (0, 0, width, height) # 相同区域,用于测试并行
regions["区域4"] = (0, 0, width, height) # 相同区域,用于测试并行
regions["区域5"] = (0, 0, width, height) # 相同区域,用于测试并行
regions["区域6"] = (0, 0, width, height) # 相同区域,用于测试并行
# 裁剪并保存区域图片
region_images = {}
temp_dir = tempfile.gettempdir()
for name, (x1, y1, x2, y2) in regions.items():
try:
# 确保坐标在图片范围内
x1 = max(0, min(x1, img.width))
y1 = max(0, min(y1, img.height))
x2 = max(x1, min(x2, img.width))
y2 = max(y1, min(y2, img.height))
if x2 > x1 and y2 > y1:
crop_img = img.crop((x1, y1, x2, y2))
temp_path = os.path.join(temp_dir, f"ocr_test_{name}.png")
crop_img.save(temp_path)
region_images[name] = {
'path': temp_path,
'size': crop_img.size,
'coords': (x1, y1, x2, y2)
}
except (ValueError, OSError, IOError) as e:
print(f"[WARNING] 无法裁剪区域 {name}: {e}")
return region_images, img.size
except (OSError, IOError, ValueError) as e:
print(f"[ERROR] 无法处理图片: {e}")
return {}, None
def ocr_single_region(image_path, region_name, ocr_processor):
"""对单个区域进行OCR识别"""
try:
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img_np = np.array(img)
start_time = time.time()
if ocr_processor.ocr_type == "easyocr":
result = ocr_processor.ocr.readtext(img_np)
else:
result = ocr_processor.ocr.ocr(img_np)
elapsed = (time.time() - start_time) * 1000
# 提取文本
from Underlying_Operations import underlying_operations
ops = underlying_operations()
text = ops.extract_ocr_content(result)
return {
'region': region_name,
'text': text,
'time': elapsed,
'success': True
}
except Exception as e:
import traceback
error_msg = f"{type(e).__name__}: {str(e)}"
print(f" [DEBUG] {region_name} OCR错误: {error_msg}")
return {
'region': region_name,
'text': '',
'time': 0,
'success': False,
'error': error_msg
}
def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers):
"""测试真实场景的并行OCR"""
print(f"\n{'='*70}")
print(f"测试: {config_name}")
print(f"{'='*70}")
print(f"配置: OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}")
print(f"区域数量: {len(region_images)}")
print()
# 设置OMP线程数
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
# 初始化OCR(使用新的OMP设置)
try:
from operations.ocr_operations import OCRProcessor
ocr_processor = OCRProcessor()
# 访问受保护方法以初始化OCR引擎(测试代码中需要)
# 使用 getattr 来避免 pylance 警告
ensure_ocr = getattr(ocr_processor, '_ensure_ocr')
ensure_ocr()
if ocr_processor.ocr is None:
print("[ERROR] OCR引擎未初始化")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
print(f"OCR引擎: {ocr_processor.ocr_type}")
print()
except (ImportError, AttributeError, RuntimeError) as e:
print(f"[ERROR] OCR引擎初始化失败: {e}")
os.environ['OMP_NUM_THREADS'] = old_omp
return None
# 显示区域信息
print("OCR区域信息:")
for name, info in region_images.items():
print(f" {name}: {info['size'][0]}x{info['size'][1]} 像素, 坐标: {info['coords']}")
print()
# 并行执行OCR
print("开始并行OCR识别...")
start_time = time.time()
results = []
def ocr_task(name, path):
return ocr_single_region(path, name, ocr_processor)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# 提交所有任务
futures = {
executor.submit(ocr_task, name, info['path']): name
for name, info in region_images.items()
}
# 收集结果
for future in futures:
region_name = futures[future]
try:
result = future.result(timeout=60) # 每个任务最多60秒
results.append(result)
status = "✓" if result['success'] else "✗"
print(f" {status} {region_name}: {result['time']:.0f}ms, 结果: {result['text'][:30] if result['text'] else '(空)'}")
except TimeoutError:
print(f" ✗ {region_name}: 超时(>60秒)")
results.append({
'region': region_name,
'text': '',
'time': 0,
'success': False,
'error': 'Timeout'
})
except (RuntimeError, AttributeError, KeyError) as e:
print(f" ✗ {region_name}: 失败 - {e}")
results.append({
'region': region_name,
'text': '',
'time': 0,
'success': False,
'error': str(e)
})
total_elapsed = (time.time() - start_time) * 1000
# 恢复OMP设置
os.environ['OMP_NUM_THREADS'] = old_omp
# 统计结果
successful_results = [r for r in results if r['success']]
total_task_time = sum(r['time'] for r in successful_results)
avg_task_time = total_task_time / len(successful_results) if successful_results else 0
print()
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
print(f"任务总耗时: {total_task_time:.0f}ms")
print(f"平均每个任务: {avg_task_time:.0f}ms")
if total_task_time > 0:
efficiency = total_task_time / total_elapsed
print(f"并行效率: {efficiency:.2f}x (理想值: {len(region_images):.1f}x)")
print()
return {
'total_time': total_elapsed,
'task_times': [r['time'] for r in successful_results],
'results': results,
'config': config_name
}
def main():
"""主函数"""
# 默认图片路径(完整截图)
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
if len(sys.argv) > 1:
image_path = sys.argv[1]
else:
image_path = default_image
if not os.path.isabs(image_path):
project_root = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(project_root, image_path)
if not os.path.exists(image_path):
print(f"[ERROR] 图片文件不存在: {image_path}")
return
print("=" * 70)
print("真实场景并行OCR性能对比测试")
print("=" * 70)
print()
print(f"测试图片: {os.path.basename(image_path)}")
print()
# 创建测试区域
print("准备测试区域...")
region_images, full_size = create_test_regions(image_path)
if not region_images:
print("[ERROR] 无法创建测试区域")
return
if full_size is not None:
print(f"完整截图尺寸: {full_size[0]}x{full_size[1]}")
else:
print("完整截图尺寸: 未知")
print(f"成功创建 {len(region_images)} 个测试区域")
print()
# 获取系统信息
cpu_count = os.cpu_count() or 4
print("系统信息:")
print(f" CPU核心数: {cpu_count}")
try:
from operations.screenshot_service import get_optimal_workers
optimal_workers = get_optimal_workers()
print(f" 推荐线程池大小: {optimal_workers}")
except (ImportError, AttributeError):
optimal_workers = 6
print()
# 测试1: 优化前配置(OMP=1, workers=6)
result_old = test_parallel_ocr_real(
region_images,
"优化前配置",
omp_threads=1,
max_workers=6
)
# 等待一下,让系统稳定
time.sleep(1)
# 测试2: 优化后配置(OMP=4, workers=10)
result_new = test_parallel_ocr_real(
region_images,
"优化后配置",
omp_threads=4,
max_workers=optimal_workers
)
# 性能对比总结
print()
print("=" * 70)
print("性能对比总结")
print("=" * 70)
print()
if result_old and result_new:
old_time = result_old['total_time']
new_time = result_new['total_time']
speedup = old_time / new_time if new_time > 0 else 0
print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)")
print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)")
print(f"性能提升: {speedup:.2f}x")
print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%")
print()
# 详细对比
if result_old['task_times'] and result_new['task_times']:
old_avg = sum(result_old['task_times']) / len(result_old['task_times'])
new_avg = sum(result_new['task_times']) / len(result_new['task_times'])
print("任务级性能对比:")
print(f" 优化前平均任务耗时: {old_avg:.0f}ms")
print(f" 优化后平均任务耗时: {new_avg:.0f}ms")
print(f" 单任务性能提升: {old_avg/new_avg:.2f}x")
print()
# 识别结果对比
print("识别结果对比:")
for old_result in result_old['results']:
region_name = old_result['region']
new_result = next((r for r in result_new['results'] if r['region'] == region_name), None)
if old_result['success'] and new_result and new_result['success']:
old_text = old_result['text'][:20] if old_result['text'] else '(空)'
new_text = new_result['text'][:20] if new_result['text'] else '(空)'
match = "✓" if old_text == new_text else "✗"
print(f" {match} {region_name}: 结果一致")
# 清理临时文件
print()
print("清理临时文件...")
for info in region_images.values():
try:
if os.path.exists(info['path']):
os.remove(info['path'])
except (OSError, PermissionError):
pass
print()
print("=" * 70)
print("测试完成")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -1,109 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试截图错误处理和重试机制
"""
import time
import sys
import os
import subprocess
from unittest.mock import patch, MagicMock
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_adb_error_codes():
"""测试ADB错误码处理"""
print("测试ADB错误码处理...")
print("=" * 50)
from operations.screenshot_operations import ScreenshotOperations
ops = ScreenshotOperations()
# 测试错误码4294967295的处理
print("\n1. 测试错误码4294967295 (设备连接失败)")
try:
# 模拟adb命令返回4294967295
with patch('subprocess.Popen') as mock_popen:
mock_process = MagicMock()
mock_process.wait.return_value = 4294967295
mock_process.stdout.read.side_effect = [b'', b''] # 空数据
mock_popen.return_value = mock_process
result = ops._get_screenshot_direct("test_device")
print(f"截图结果: {result}")
print("预期: False (截图失败)")
except Exception as e:
print(f"异常: {e}")
print("\n2. 测试正常截图流程")
# 这里不实际测试,因为需要真实的adb环境
print("跳过实际截图测试(需要真实设备)")
def test_retry_mechanism():
"""测试重试机制"""
print("\n3. 测试重试机制模拟")
# 模拟3次失败后成功的情况
retry_count = 0
max_retries = 3
success = False
for retry in range(max_retries):
retry_count = retry + 1
print(f"重试 {retry_count}/{max_retries}")
# 模拟前两次失败,第3次成功
if retry < 2:
print(" 截图失败")
else:
print(" 截图成功")
success = True
break
if retry < max_retries - 1:
print(" 等待1秒后重试...")
time.sleep(0.1) # 实际测试中用较短时间
print(f"\n最终结果: {'成功' if success else '失败'}")
print(f"重试次数: {retry_count}")
def test_error_messages():
"""测试错误消息"""
print("\n4. 测试错误消息")
# 模拟不同的错误情况
error_scenarios = [
(4294967295, "设备连接失败"),
(1, "ADB命令错误"),
("timeout", "操作超时"),
("unknown", "未知错误")
]
for error_code, expected_desc in error_scenarios:
print(f"错误码 {error_code}: {expected_desc}")
print("\n错误处理改进:")
print("- 添加了设备连接状态检查")
print("- 区分不同类型的ADB错误")
print("- 提供更详细的错误诊断信息")
print("- 实现截图失败时的重试机制")
if __name__ == "__main__":
test_adb_error_codes()
test_retry_mechanism()
test_error_messages()
print("\n" + "=" * 50)
print("截图错误处理测试完成")
print("修复内容:")
print("1. 添加ADB错误码4294967295的特殊处理")
print("2. 改进错误消息,提供更详细的诊断信息")
print("3. 在douyin_fudai.py中添加截图重试机制")
print("4. 当截图失败时会重试3次,而不是直接放弃")
@@ -1,92 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR期间截图文件等待逻辑
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_screenshot_file_wait():
"""测试截图文件等待逻辑"""
print("测试OCR期间截图文件等待逻辑...")
# 1. 模拟截图文件不存在的情况
print("\n1. 模拟截图文件等待...")
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")
print(f"截图文件路径: {pic_path}")
# 检查文件是否存在
if os.path.exists(pic_path):
print("截图文件已存在")
file_size = os.path.getsize(pic_path)
print(f"文件大小: {file_size} bytes")
else:
print("截图文件不存在")
# 2. 模拟等待逻辑
print("\n2. 测试等待逻辑...")
wait_start = time.time()
max_wait = 3.0
found = False
while time.time() - wait_start < max_wait:
if os.path.exists(pic_path):
file_size = os.path.getsize(pic_path)
if file_size >= 1024: # 至少1KB
found = True
break
time.sleep(0.1)
wait_time = time.time() - wait_start
if found:
print(".2f")
else:
print(f"等待{max_wait}秒后仍未找到有效截图文件")
# 3. 分析问题
print("\n3. 问题分析:")
issues = []
if not found:
issues.append("[WARN] 等待期间未找到截图文件")
else:
issues.append("[OK] 成功等到截图文件")
# 检查文件完整性
if os.path.exists(pic_path):
try:
with open(pic_path, 'rb') as f:
header = f.read(4)
if header == b'\x89PNG':
issues.append("[OK] 截图文件格式正确 (PNG)")
else:
issues.append("[WARN] 截图文件格式异常")
except Exception as e:
issues.append(f"[ERROR] 读取截图文件失败: {e}")
else:
issues.append("[ERROR] 截图文件不存在")
for issue in issues:
print(issue)
print(f"\n测试结果: {'PASS' if found else 'FAIL'}")
return found
if __name__ == "__main__":
success = test_screenshot_file_wait()
sys.exit(0 if success else 1)
@@ -1,127 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
截图性能测试脚本
测试截图性能并查看细粒度计时日志,验证优化效果。
"""
import os
import sys
import time
import logging
# 配置日志 - 使用 DEBUG 级别以查看所有详细计时信息
logging.basicConfig(
level=logging.DEBUG,
format='[%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
def test_screenshot_with_timing():
"""测试截图并显示计时信息"""
try:
from Underlying_Operations import underlying_operations
except ImportError:
print("[错误] 无法导入 Underlying_Operations")
return
# 获取设备ID
import subprocess
try:
result = subprocess.run(["adb", "devices"], capture_output=True, text=True, timeout=10)
if result.returncode != 0:
print("[错误] adb devices 失败")
return
lines = result.stdout.strip().split("\n")[1:]
devices = []
for line in lines:
if line.strip() and "\t" in line:
device_id = line.split("\t")[0].strip()
if device_id:
devices.append(device_id)
if not devices:
print("[错误] 未找到连接的设备")
return
device_id = devices[0]
print(f"[信息] 使用设备: {device_id}")
except Exception as e:
print(f"[错误] 获取设备ID失败: {e}")
return
# 创建操作对象
ops = underlying_operations()
print("\n" + "="*60)
print("测试 1: 正常截图(启用所有验证和镜像)")
print("="*60)
# 测试1: 正常截图
start = time.time()
result1 = ops.get_screenshot(device_id, use_service=False) # 禁用服务,使用直接截图以便看到详细日志
elapsed1 = (time.time() - start) * 1000.0
print(f"\n[结果] 测试1完成: 成功={result1}, 总耗时={elapsed1:.1f}ms")
time.sleep(1)
print("\n" + "="*60)
print("测试 2: 禁用 PNG 验证 (SKIP_SCREENSHOT_VERIFY=1)")
print("="*60)
# 测试2: 禁用验证
os.environ["SKIP_SCREENSHOT_VERIFY"] = "1"
start = time.time()
result2 = ops.get_screenshot(device_id, use_service=False)
elapsed2 = (time.time() - start) * 1000.0
print(f"\n[结果] 测试2完成: 成功={result2}, 总耗时={elapsed2:.1f}ms")
if elapsed1 > 0:
improvement = ((elapsed1 - elapsed2) / elapsed1) * 100
print(f"[对比] 相比测试1: {improvement:+.1f}% ({elapsed1 - elapsed2:+.1f}ms)")
time.sleep(1)
print("\n" + "="*60)
print("测试 3: 禁用 PNG 验证 + 禁用镜像 (SKIP_SCREENSHOT_VERIFY=1, DISABLE_SCREENSHOT_MIRROR=1)")
print("="*60)
# 测试3: 禁用验证和镜像
os.environ["DISABLE_SCREENSHOT_MIRROR"] = "1"
start = time.time()
result3 = ops.get_screenshot(device_id, use_service=False)
elapsed3 = (time.time() - start) * 1000.0
print(f"\n[结果] 测试3完成: 成功={result3}, 总耗时={elapsed3:.1f}ms")
if elapsed1 > 0:
improvement = ((elapsed1 - elapsed3) / elapsed1) * 100
print(f"[对比] 相比测试1: {improvement:+.1f}% ({elapsed1 - elapsed3:+.1f}ms)")
# 恢复环境变量
if "SKIP_SCREENSHOT_VERIFY" in os.environ:
del os.environ["SKIP_SCREENSHOT_VERIFY"]
if "DISABLE_SCREENSHOT_MIRROR" in os.environ:
del os.environ["DISABLE_SCREENSHOT_MIRROR"]
print("\n" + "="*60)
print("测试总结")
print("="*60)
print(f"测试1 (正常): {elapsed1:.1f}ms")
print(f"测试2 (禁用验证): {elapsed2:.1f}ms")
print(f"测试3 (禁用全部): {elapsed3:.1f}ms")
if elapsed1 > 0 and elapsed3 > 0:
total_improvement = ((elapsed1 - elapsed3) / elapsed1) * 100
print(f"\n最大优化效果: {total_improvement:+.1f}% ({elapsed1 - elapsed3:+.1f}ms)")
if total_improvement > 10:
print("\n[建议] 如果优化效果明显,可以考虑:")
print(" 1. 在生产环境谨慎使用 SKIP_SCREENSHOT_VERIFY(可能影响数据完整性)")
print(" 2. 如果不需要外部镜像,可以设置 DISABLE_SCREENSHOT_MIRROR=1")
print(" 3. 检查外部镜像路径是否是网络路径(可能很慢)")
if __name__ == "__main__":
test_screenshot_with_timing()
@@ -1,129 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试点击福袋后阶段识别与OCR共用截图的优化
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_screenshot_reuse_optimization():
"""测试截图复用优化"""
print("测试点击福袋后阶段识别与OCR共用截图优化...")
print("=" * 60)
# 1. 模拟阶段诊断检测到任务数量 > 0
print("\n1. 模拟阶段诊断检测到任务数量 > 0")
class MockAnalyser:
def __init__(self):
self._fudai_detail_task_count_from_stage = 2
self._screenshot_ready_for_ocr = False
def _log_kv(self, key, value, **kwargs):
timestamp = time.strftime("%H:%M:%S", time.localtime())
print(f"[{timestamp}] [{key}] {value}")
analyser = MockAnalyser()
# 模拟阶段诊断设置标志
analyser._fudai_detail_task_count_from_stage = 2
analyser._screenshot_ready_for_ocr = True
print(f"任务数量: {analyser._fudai_detail_task_count_from_stage}")
print(f"截图复用标志: {analyser._screenshot_ready_for_ocr}")
# 2. 模拟OCR开始时的逻辑
print("\n2. 模拟OCR开始时的截图复用检查")
# 检查是否可以复用阶段诊断时的截图
screenshot_reused = False
try:
if getattr(analyser, '_screenshot_ready_for_ocr', False):
analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用
screenshot_reused = True
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once:复用阶段诊断截图",
reason="stage_diagnosed_task_count_gt_zero"
)
except Exception:
pass
except Exception:
pass
print(f"截图是否复用: {screenshot_reused}")
print(f"清除后的复用标志: {analyser._screenshot_ready_for_ocr}")
# 3. 验证优化效果
print("\n3. 验证优化效果")
if screenshot_reused:
print("[OK] 成功复用阶段诊断时的截图,避免重复截图")
print("[OK] OCR跳过了get_screenshot调用")
print("[OK] 减少了一次不必要的截图操作")
success = True
else:
print("[FAIL] 截图复用失败,仍会进行新的截图")
success = False
# 4. 模拟任务数量为0的情况
print("\n4. 模拟任务数量为0的情况")
analyser2 = MockAnalyser()
analyser2._fudai_detail_task_count_from_stage = 0
analyser2._screenshot_ready_for_ocr = False # 任务数量为0时不应该设置复用标志
screenshot_reused_2 = False
try:
if getattr(analyser2, '_screenshot_ready_for_ocr', False):
analyser2._screenshot_ready_for_ocr = False
screenshot_reused_2 = True
except Exception:
pass
print(f"任务数量: {analyser2._fudai_detail_task_count_from_stage}")
print(f"截图复用标志: {analyser2._screenshot_ready_for_ocr}")
print(f"截图是否复用: {screenshot_reused_2}")
if not screenshot_reused_2:
print("[OK] 任务数量为0时正确不复用截图")
else:
print("[FAIL] 任务数量为0时错误复用截图")
success = False
# 5. 分析性能提升
print("\n5. 性能提升分析")
print("-" * 40)
print("优化前:")
print("- 阶段诊断: 1次截图")
print("- OCR识别: 1次截图")
print("- 总计: 2次截图")
print("\n优化后:")
print("- 阶段诊断: 1次截图")
print("- OCR识别: 复用阶段诊断截图")
print("- 总计: 1次截图")
print("\n性能提升:")
print("- 减少50%的截图操作")
print("- 减少截图等待时间")
print("- 降低系统负载")
print(f"\n{'='*60}")
print(f"测试结果: {'PASS' if success else 'FAIL'}")
print("优化目标: 当阶段诊断发现任务数量>0时,OCR复用同一张截图")
print(f"{'='*60}")
return success
if __name__ == "__main__":
success = test_screenshot_reuse_optimization()
sys.exit(0 if success else 1)
@@ -1,59 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试截图服务修复效果
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_service_startup():
"""测试截图服务启动"""
print("测试截图服务启动修复...")
# 模拟启动过程
from douyin.core.douyin_fudai import fudai_analyse
# 创建分析器实例
analyser_instance = fudai_analyse()
print("启动fudai_choujiang(只运行几秒钟测试服务启动)...")
try:
# 设置设备ID(需要根据实际情况修改)
device_id = "emulator-5554" # 或者其他设备ID
# 启动服务(只运行5秒)
analyser_instance.fudai_choujiang(
device_id=device_id,
wait_minutes=0, # 不等待,直接测试启动
)
except KeyboardInterrupt:
print("测试被中断")
except Exception as e:
print(f"测试过程中出现异常: {e}")
import traceback
traceback.print_exc()
# 检查服务状态
print("\n检查服务状态:")
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
info = service.get_cache_info()
print(f"服务运行中: {info['running']}")
print(f"设备ID: {info['device_id']}")
print(f"后台线程: {'运行中' if hasattr(service, '_thread') and service._thread and service._thread.is_alive() else '未运行'}")
# 停止服务
if service.is_running():
service.stop()
print("服务已停止")
if __name__ == "__main__":
test_service_startup()
@@ -1,91 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR时停止后台截图服务的优化效果
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_screenshot_service_ocr_integration():
"""测试截图服务与OCR集成的优化"""
print("=" * 80)
print("测试OCR时停止后台截图服务的优化")
print("=" * 80)
# 1. 启动截图服务
print("\n1. 启动后台截图服务...")
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
# 模拟设备ID(实际测试时需要替换为真实设备ID)
device_id = "emulator-5554"
if service.is_running():
print("服务已在运行")
else:
service.start(device_id, interval=1.5)
time.sleep(0.5) # 等待服务启动
if service.is_running():
print("[OK] 后台截图服务启动成功")
else:
print("[FAIL] 后台截图服务启动失败")
return
# 2. 模拟OCR密集操作
print("\n2. 模拟OCR密集操作(调用read_fudai_detail_once)...")
# 创建一个模拟的analyser对象
class MockAnalyser:
def __init__(self):
self.device_id = device_id
self._fudai_detail_task_count_from_stage = 2
def _log_kv(self, key, value, **kwargs):
timestamp = time.strftime("%H:%M:%S", time.localtime())
print(f"[{timestamp}] [{key}] {value}")
analyser = MockAnalyser()
# 调用read_fudai_detail_once,这应该会停止后台服务
start_time = time.time()
try:
from fudai_detail_modules.fudai_detail_reader import read_fudai_detail_once
result = read_fudai_detail_once(analyser)
elapsed = time.time() - start_time
print(".2f")
print(f" 返回状态: {result[0]}")
except Exception as e:
elapsed = time.time() - start_time
print(".2f")
print(f" 错误: {e}")
# 3. 检查服务是否重新启动
print("\n3. 检查后台截图服务是否重新启动...")
time.sleep(0.5) # 等待服务重新启动
if service.is_running():
print("[OK] 后台截图服务已自动重新启动")
info = service.get_cache_info()
print(f" 设备ID: {info['device_id']}")
print(f" 截图间隔: {info['interval']}秒")
print(f" 缓存有效期: {info['cache_valid_duration']}秒")
else:
print("[FAIL] 后台截图服务未重新启动")
# 4. 清理
if service.is_running():
service.stop()
print("\n4. 测试完成,停止后台截图服务")
print("\n" + "=" * 80)
print("测试完成")
print("=" * 80)
if __name__ == "__main__":
test_screenshot_service_ocr_integration()
@@ -1,84 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单测试:验证OCR时停止后台截图服务的代码修改
"""
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_code_modification():
"""测试代码修改是否正确"""
print("测试OCR时停止后台截图服务的代码修改...")
# 1. 检查文件是否存在
file_path = "fudai_detail_modules/fudai_detail_reader.py"
if not os.path.exists(file_path):
print(f"[FAIL] 文件不存在: {file_path}")
return False
# 2. 检查代码中是否包含停止服务的逻辑
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 检查关键代码片段
checks = [
("停止服务代码", "service.stop()" in content),
("启动服务代码", "service.start(" in content),
("screenshot_service_stopped变量", "screenshot_service_stopped" in content),
("finally块", "finally:" in content),
("ScreenshotService导入", "from operations.screenshot_service import ScreenshotService" in content),
]
all_passed = True
for check_name, result in checks:
if result:
print(f"[OK] {check_name}")
else:
print(f"[FAIL] {check_name}")
all_passed = False
# 3. 检查语法是否正确
try:
compile(content, file_path, 'exec')
print("[OK] 语法检查通过")
except SyntaxError as e:
print(f"[FAIL] 语法错误: {e}")
all_passed = False
# 4. 检查导入是否工作
read_fudai_detail_once = None # 初始化变量
try:
from fudai_detail_modules.fudai_detail_reader import read_fudai_detail_once
print("[OK] 模块导入成功")
except ImportError as e:
print(f"[FAIL] 模块导入失败: {e}")
all_passed = False
# 5. 检查函数签名
import inspect
try:
if read_fudai_detail_once is not None:
sig = inspect.signature(read_fudai_detail_once)
print(f"[OK] 函数签名: {sig}")
else:
print("[SKIP] 函数未导入,跳过签名检查")
except Exception as e:
print(f"[FAIL] 函数签名检查失败: {e}")
all_passed = False
print()
if all_passed:
print("[SUCCESS] 代码修改验证通过!")
print("OCR密集操作时会自动停止后台截图服务,避免资源冲突。")
else:
print("[FAIL] 代码修改存在问题,请检查!")
return all_passed
if __name__ == "__main__":
success = test_code_modification()
sys.exit(0 if success else 1)
@@ -1,113 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试OCR时停止后台截图服务的功能
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def test_screenshot_service_stop_during_ocr():
"""测试OCR过程中后台截图服务是否被停止"""
print("测试OCR时停止后台截图服务功能...")
# 1. 启动截图服务
print("\n1. 启动后台截图服务...")
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
# 模拟设备ID
device_id = "emulator-5554"
if not service.is_running():
service.start(device_id, interval=1.5)
time.sleep(0.5)
if service.is_running():
print("[OK] 后台截图服务已启动")
else:
print("[FAIL] 后台截图服务启动失败")
return False
# 记录初始状态
initial_cache_duration = service._cache_valid_duration
print(f"初始缓存有效期: {initial_cache_duration}秒")
# 2. 模拟OCR操作
print("\n2. 模拟OCR操作...")
# 创建模拟的analyser
class MockAnalyser:
def __init__(self):
self.device_id = device_id
self._fudai_detail_task_count_from_stage = 2
def _log_kv(self, key, value, **kwargs):
timestamp = time.strftime("%H:%M:%S", time.localtime())
print(f"[{timestamp}] [{key}] {value}")
analyser = MockAnalyser()
# 记录开始时的服务状态
service_running_before = service.is_running()
print(f"OCR开始前服务运行状态: {service_running_before}")
start_time = time.time() # 初始化开始时间
try:
# 调用read_fudai_detail_once - 这应该会停止后台服务
from fudai_detail_modules.fudai_detail_reader import read_fudai_detail_once
start_time = time.time()
result = read_fudai_detail_once(analyser)
elapsed = time.time() - start_time
print(".2f")
print(f" 返回状态: {result[0]}")
except Exception as e:
elapsed = time.time() - start_time
print(".2f")
print(f" 错误: {e}")
# 3. 检查OCR后的服务状态
print("\n3. 检查OCR后的服务状态...")
time.sleep(0.5) # 等待服务状态稳定
service_running_after = service.is_running()
final_cache_duration = service._cache_valid_duration
print(f"OCR结束后服务运行状态: {service_running_after}")
print(f"最终缓存有效期: {final_cache_duration}秒")
# 4. 验证结果
success = True
if service_running_before and not service_running_after:
print("[OK] 后台截图服务在OCR期间被正确停止")
elif not service_running_before:
print("[INFO] 后台截图服务在OCR开始前就已经停止")
else:
print("[FAIL] 后台截图服务在OCR期间没有被停止")
success = False
if final_cache_duration == initial_cache_duration:
print("[OK] 缓存有效期在OCR结束后被正确恢复")
else:
print(f"[WARNING] 缓存有效期未恢复: 期望{initial_cache_duration}, 实际{final_cache_duration}")
# 5. 清理
if service.is_running():
service.stop()
print("\n5. 测试完成,停止后台截图服务")
print(f"\n测试结果: {'PASS' if success else 'FAIL'}")
return success
if __name__ == "__main__":
success = test_screenshot_service_stop_during_ocr()
sys.exit(0 if success else 1)
@@ -1,44 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试time导入修复
"""
import time
def test_time_import():
"""测试time模块导入和使用"""
print("测试time模块导入和使用...")
# 模拟read_fudai_detail_once函数的开始部分
try:
start_time = time.time()
print(".3f")
except Exception as e:
print(f"[ERROR] time.time()调用失败: {e}")
return False
# 模拟函数内部的逻辑
try:
task_count = 0
# 清除标志
# 模拟等待逻辑(之前有问题的部分)
wait_start = time.time()
print(".3f")
# 模拟循环
while time.time() - wait_start < 0.1: # 很短的时间
pass
elapsed = time.time() - start_time
print(".3f")
except Exception as e:
print(f"[ERROR] 函数内部time使用失败: {e}")
return False
print("[OK] time模块导入和使用正常")
return True
if __name__ == "__main__":
success = test_time_import()
print(f"\n测试结果: {'PASS' if success else 'FAIL'}")
+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.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -13,7 +13,7 @@
### ✅ 日志文件写入功能正常
**验证点1: 日志文件存在**
- 文件路径: `C:\Users\12742\Desktop\douyin_guaji-main\logs\unified_2025-12-22.log`
- 文件路径: `logs/unified_2025-12-22.log`
- 文件大小: 8800 bytes
- 总行数: 126行
@@ -96,4 +96,3 @@ GUI应用的日志写入功能:
**测试状态**: ✅ 通过
**功能状态**: ✅ 正常
**建议**: 可以投入使用
+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`
@@ -0,0 +1,462 @@
# 拆分 gui/gui_app.py 实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 把 `gui/gui_app.py`(5476 行)中内聚的 `main()` 闭包逐段抽到 `gui/components/*` 子模块,主文件持续瘦身,GUI 行为不变。
**Architecture:** 每个候选段抽到独立模块,改造为顶层函数,通过显式参数(回调 + 必要的 widgets/Vars/路径)接收依赖。每抽完一段独立 commit + push。
**Tech Stack:** Python 3.10+, tkinter / ttkbootstrap, pytest
**Spec:** `docs/superpowers/specs/2026-05-30-split-gui-app-design.md`
---
## 抽取顺序
按 spec 优先级:P1 → P2 → P3 → P4 → P5 → P6。每个任务独立可停。
P1 包括两个紧耦合段(`open_wifi_adb_dialog` 845 行 + `open_scan_dialog` 200 行)。
---
## Task 1: 抽 `open_scan_dialog` 到 `components/wifi_adb_scan_dialog.py`
**Files:**
- Create: `gui/components/wifi_adb_scan_dialog.py`
- Modify: `gui/gui_app.py:539-742` (删除原闭包) + 改 `gui/gui_app.py:1088-1093`(`open_scan_dialog` 调用点)
**理由先抽这个:** `open_scan_dialog` 已经是显式参数形式,不依赖 `main()` 任何捕获变量,迁移最简单。先做它能熟悉抽取流程,降 ~200 行。
- [ ] **Step 1: 读完整段确认依赖**
```bash
# 看 539-742 完整段
```
确认 `open_scan_dialog` 仅依赖参数 `parent, adb_exe_local, ip_var, on_line_local, refresh_cb` 和模块级 import(`tk`, `ttk`, `discover_adb_devices`, `get_local_subnet`, `pick_best_match`, `verify_adb_target` 等)。
- [ ] **Step 2: 创建新模块**
写 `gui/components/wifi_adb_scan_dialog.py`,把 539-742 的整段函数原样复制为 `open_scan_dialog`,加 `from __future__ import annotations` 与所有需要的 import。
- [ ] **Step 3: 修改 `gui_app.py`,替换调用点**
在 `gui_app.py` 顶部 import 新模块:
```python
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
```
删除 539-742 的原 `def open_scan_dialog(...)` 定义。
- [ ] **Step 4: 验证语法**
```bash
python -m py_compile gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
```
Expected: 无输出(成功)
- [ ] **Step 5: 跑测试**
```bash
pytest -x
```
Expected: 全部 PASS
- [ ] **Step 6: 行数核对 + commit**
```bash
wc -l gui/gui_app.py
git status --short
git add gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
git commit -m "refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → <new>)"
git push
```
---
## Task 2: 抽 `open_wifi_adb_dialog` 到 `components/wifi_adb_dialog.py`
**Files:**
- Create: `gui/components/wifi_adb_dialog.py`
- Modify: `gui/gui_app.py:743-1111` (删除原闭包,改 `wifi_adb_btn` 的 command)
**依赖分析(已完成):**
模块级(已 import,直接用):
- `list_adb_devices`, `enable_wifi_adb`, `connect_wifi_adb`, `disconnect_wifi_adb`, `auto_connect_wifi_adb`, `get_device_ip`, `get_connected_wifi_devices`(from `gui.gui_core`)
- `set_last_wifi_target`, `get_last_wifi_target`, `clear_last_wifi_target`(from `gui.gui_core_pkg`)
- `verify_adb_target`, `query_device_model`(from `gui.gui_core_pkg.wifi_adb_scan`)
`main()` 局部(必须传):
- `root: tk.Misc`(父窗口,用于 `tk.Toplevel(root)`)
- `adb_exe: str`
- `on_line: Callable[[str], None]`
- `refresh_devices: Callable[[], None]`
- `open_scan_dialog`(Task 1 完成后已为顶层函数,直接 import)
自递归(三处 `dialog.destroy(); open_wifi_adb_dialog()`):
改造为传入自己的引用 —— 用一个内部函数 `_reopen()` 闭包捕获参数,或参数化 `parent`/`adb_exe` 后直接再调用顶层函数。**采用方案 B:把 `open_wifi_adb_dialog` 改成顶层函数,签名带所有依赖,自递归直接调用自己。**
- [ ] **Step 1: 创建新模块骨架**
```python
# gui/components/wifi_adb_dialog.py
from __future__ import annotations
import re
import threading
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, W, X
from typing import Callable
from gui.gui_core import (
auto_connect_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
enable_wifi_adb,
get_connected_wifi_devices,
get_device_ip,
list_adb_devices,
)
from gui.gui_core_pkg import (
clear_last_wifi_target,
get_last_wifi_target,
set_last_wifi_target,
)
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
def open_wifi_adb_dialog(
root: tk.Misc,
*,
adb_exe: str,
on_line: Callable[[str], None],
refresh_devices: Callable[[], None],
) -> None:
"""打开 WiFi ADB 设置对话框。
从 gui_app.main 抽出,显式接收依赖。
"""
# ... (Step 2 复制原 743-1111 函数体,把对外部名字的引用替换为参数)
```
- [ ] **Step 2: 复制函数体并替换闭包变量引用**
把 `gui_app.py:743-1111`(从 `def open_wifi_adb_dialog():` 内 body 开始,到 `info_label.pack(...)` 结束)整段复制进新函数体,缩进调整 4 → 4(已经一致,只是去掉外层 `def main()` 这一层)。
把三处自递归改为带参数的:
```python
# 原: open_wifi_adb_dialog()
# 改: open_wifi_adb_dialog(root, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
```
把对 `open_scan_dialog` 的引用保留为 module-import 形式:
```python
# 原:
# command=lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists)
# 不变(因为已 import 顶层 open_scan_dialog)
```
注意 `toggle_maximize`、`refresh_device_lists` 是嵌套闭包,保持原样不抽 —— 它们捕获的是对话框内 widgets,只在对话框内用。
- [ ] **Step 3: 改 `gui_app.py`,删原闭包,改按钮 command**
在 `gui_app.py` 顶部加:
```python
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
```
删除 743-1111 的原嵌套 `def open_wifi_adb_dialog():` 整段。
把 1113 行的按钮 command 改为:
```python
wifi_adb_btn = ttk.Button(
top,
text="WiFi ADB",
command=lambda: _open_wifi_adb_dialog(
root,
adb_exe=adb_exe,
on_line=on_line,
refresh_devices=refresh_devices,
),
)
```
- [ ] **Step 4: 验证语法**
```bash
python -m py_compile gui/gui_app.py gui/components/wifi_adb_dialog.py
```
Expected: 无输出
- [ ] **Step 5: 跑测试**
```bash
pytest -x
```
Expected: 全部 PASS
- [ ] **Step 6: 行数核对 + commit**
```bash
wc -l gui/gui_app.py
git status --short
git add gui/gui_app.py gui/components/wifi_adb_dialog.py
git commit -m "refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (<old> → <new>)"
git push
```
---
## Task 3: 评估 P2(`load_config_to_ui` + `save_ui_to_config`)
P2 在 spec 里被标记为高风险(100+ Var)。只有 Task 1+2 完成且测试稳定时才做。
- [ ] **Step 1: 数 Var 数量**
```bash
grep -nE "^\s+[a-zA-Z_]+_var = " gui/gui_app.py | wc -l
```
如果数量 ≥ 50,跳过 Task 3,直接进 Task 4。
如果 < 50,继续。
- [ ] **Step 2: 如果继续,设计 dataclass 聚合 Var**
读 2748-3402 列出所有用到的 Var,定义:
```python
# gui/components/config_io.py
@dataclass
class ConfigVars:
y_var: tk.IntVar
needswitch_var: tk.BooleanVar
# ... 全部
```
抽出函数:
```python
def load_config_to_ui(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
def save_ui_to_config(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
```
实施步骤参考 Task 2 的 Step 1-6。
如果改动量过大或测试卡住,**回滚并跳过 P2**。
---
## Task 4: 抽 `refresh_reservations` 到 `components/reservations_view.py`
**Files:**
- Create: `gui/components/reservations_view.py`
- Modify: `gui/gui_app.py:4530-4805` (删原闭包),改调用点
- [ ] **Step 1: 列出依赖**
读 4530-4805,记录捕获的 widgets(主要是 `reservations_tree: ttk.Treeview`)、状态变量、回调。
- [ ] **Step 2: 创建模块,函数签名**
```python
# gui/components/reservations_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable
def refresh_reservations(
tree: ttk.Treeview,
*,
on_line: Callable[[str], None] = lambda _msg: None,
) -> None:
"""刷新预约 Tab 的 Treeview。"""
# body 来自原 4530-4805
```
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
- [ ] **Step 3: 修改 `gui_app.py`**
```python
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
# 原 def refresh_reservations(): ... 改为:
def refresh_reservations():
_refresh_reservations_impl(reservations_tree, on_line=on_line)
```
保留薄包装 `def refresh_reservations()`,因为 `auto_refresh_reservations` 等地方仍以闭包形式调用它。
- [ ] **Step 4: 验证 + 测试 + commit**
```bash
python -m py_compile gui/gui_app.py gui/components/reservations_view.py
pytest -x
wc -l gui/gui_app.py
git add gui/gui_app.py gui/components/reservations_view.py
git commit -m "refactor(gui): 抽 refresh_reservations 到 components/reservations_view (<old> → <new>)"
git push
```
---
## Task 5: 抽 `refresh_high_value_rooms` 到 `components/high_value_view.py`
**Files:**
- Create: `gui/components/high_value_view.py`
- Modify: `gui/gui_app.py:4805-5085`
- [ ] **Step 1: 列出依赖**
读 4805-5085,记录捕获的 widgets(主要是 `high_value_rooms_tree: ttk.Treeview`)、状态变量、回调。
- [ ] **Step 2: 创建模块,函数签名**
```python
# gui/components/high_value_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable
def refresh_high_value_rooms(
tree: ttk.Treeview,
*,
on_line: Callable[[str], None] = lambda _msg: None,
) -> None:
"""刷新高价值房间 Tab 的 Treeview。"""
# body 来自原 4805-5085
```
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
- [ ] **Step 3: 修改 `gui_app.py`**
```python
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
# 原 def refresh_high_value_rooms(): ... 改为薄包装:
def refresh_high_value_rooms():
_refresh_high_value_rooms_impl(high_value_rooms_tree, on_line=on_line)
```
- [ ] **Step 4: 验证 + 测试 + commit**
```bash
python -m py_compile gui/gui_app.py gui/components/high_value_view.py
pytest -x
wc -l gui/gui_app.py
git add gui/gui_app.py gui/components/high_value_view.py
git commit -m "refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (<old> → <new>)"
git push
```
---
## Task 6: 抽 `do_screenshot` + `_bind_screenshot_button` 到 `components/screenshot_action.py`
**Files:**
- Create: `gui/components/screenshot_action.py`
- Modify: `gui/gui_app.py:3402-3651`
- [ ] **Step 1: 列出依赖**
读 3402-3651。`do_screenshot` 依赖:`adb_exe`、状态 Label、图片预览刷新回调、ADB 截图工具函数。
- [ ] **Step 2-4: 抽出,签名:**
```python
def do_screenshot(
*,
adb_exe: str,
on_line: Callable[[str], None],
on_done: Callable[[str], None], # 截图保存路径
status_label: ttk.Label | None = None,
) -> None:
...
def bind_screenshot_button(
btn: ttk.Button,
*,
adb_exe: str,
on_line: Callable[[str], None],
on_done: Callable[[str], None],
status_label: ttk.Label | None = None,
) -> None:
btn.configure(command=lambda: do_screenshot(
adb_exe=adb_exe, on_line=on_line, on_done=on_done, status_label=status_label
))
```
调用点同 Task 4。
commit msg: `refactor(gui): 抽 do_screenshot 到 components/screenshot_action (<old> → <new>)`
---
## Task 7: 抽 `refresh_actions_log` + 搜索栏 到 `components/actions_log_view.py`
**Files:**
- Create: `gui/components/actions_log_view.py`
- Modify: `gui/gui_app.py:4845-5070`
- [ ] **Step 1: 列出依赖**
读 4845-5070。包含:`configure_actions_log_colors`、`refresh_actions_log`、几个搜索方法 `search_in_actions_log`/`search_next_in_actions`/`search_prev_in_actions`/`clear_search_in_actions`/`on_actions_search_entry_key`。
- [ ] **Step 2-4: 设计**
设计成 1 个 `setup_actions_log_view(text_widget, search_entry, ...)` 一次性绑定所有,或者保留几个独立函数都接收 `text_widget` 参数。优先后者(更小步)。
签名:
```python
def configure_actions_log_colors(text_widget: tk.Text) -> None: ...
def refresh_actions_log(text_widget: tk.Text, *, on_line: Callable[[str], None]) -> None: ...
def search_in_actions_log(text_widget: tk.Text, search_entry: ttk.Entry, *, direction: int = 1) -> None: ...
```
`gui_app.py` 里保留薄包装让原闭包调用模式不变。
commit msg: `refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (<old> → <new>)`
---
## Task 8: 评估停止条件 + 收尾
- [ ] **Step 1: 检查停止条件**
```bash
wc -l gui/gui_app.py
```
满足以下任一即停:
1. ≤ 3000 行
2. 行数下降 < 50
3. 下一段需传 ≥ 50 个独立依赖
- [ ] **Step 2: 如果停止,写收尾说明**
如果停止,在 `docs/superpowers/specs/2026-05-30-split-gui-app-design.md` 末尾追加 `## Outcome` 段:列出实际抽出的模块、行数变化、未做的项。
```bash
git add docs/superpowers/specs/2026-05-30-split-gui-app-design.md
git commit -m "docs(specs): 补充 gui_app 拆分实际成果"
git push
```
- [ ] **Step 3: 报告**
总结输出给用户:
- 起始行数:5476
- 当前行数:`<X>`
- 抽出的模块列表
- pytest 状态
- 是否还有未抽的候选(可作为下一轮)
---
## 关键约束(每个 Task 都要遵守)
1. **AGENTS.md**:每个 Task 都要 commit + push,只 stage 本任务实际改的文件,不混入用户已有改动。
2. **不改行为**:抽取是纯重构,不修 bug、不优化性能、不删功能。
3. **失败回滚**:若 pytest 失败且修复需改 ≥ 2 个非目标文件,`git reset --hard HEAD~1`(本任务的 commit 还没 push),回到上一 Task 报告问题。
4. **每个 Task 验证后再开下一个**:不批量做。
5. **手工 smoke 推迟到批次末尾**:本计划的 pytest 不覆盖 GUI 交互(项目测试有意写得轻),抽取属纯重构,逻辑保持一致。每个 Task 完成后,在 Task 8 的收尾报告里提示用户:「请启动 GUI 跑一遍受影响功能(WiFi 对话框 / 预约 Tab / 高价值房间 / 截图按钮 / 操作日志 Tab),确认无回归。」用户 smoke 后若发现问题,定位到具体 Task 的 commit 回滚。
@@ -0,0 +1,982 @@
# Split WebUI Large Files Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server.
**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task.
**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes.
---
## Current Evidence
From the current worktree on 2026-05-31:
| File | Lines | Role |
|---|---:|---|
| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules |
| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring |
| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving |
| `webui/index.html` | 1232 | WebUI DOM structure and config bindings |
`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle.
## Stop Conditions
Stop this plan and write an outcome note when any one is true:
1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines.
2. The next split would require changing more than 3 of the large files in one task.
3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary.
4. Tests fail and the fix would require behavior changes outside the current responsibility.
## Verification Commands
Run these after every JavaScript or HTML task:
```powershell
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected:
```text
py_compile: exit code 0
pytest: all selected tests PASS
```
Run these after every CSS or visual task:
```powershell
python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1
```
Expected:
```text
py_compile: exit code 0
pytest: all selected tests PASS
```
For frontend visual changes, also start the Web GUI and inspect it in a browser:
```powershell
python gui\web_gui.py
```
Expected browser checks:
- `/` loads without a blank page.
- Console has no module load errors, syntax errors, or missing function errors.
- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width.
- At mobile width, command buttons wrap and panels remain readable.
## Static Loading Decision
The current page loads:
```html
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
<script src="app.js?v=console-20260520-theme-v35"></script>
```
Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them.
For CSS, use multiple `<link rel="stylesheet">` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split.
---
## Task 1: Add WebUI Static Asset Structure
**Files:**
- Create: `webui/js/README.md`
- Create: `webui/css/README.md`
- Modify: `webui/index.html`
- [ ] **Step 1: Create asset directory docs**
Create `webui/js/README.md`:
```markdown
# WebUI JavaScript modules
Classic browser scripts loaded by `webui/index.html`.
Load order matters:
1. `constants.js`
2. `dom.js`
3. `api.js`
4. focused feature scripts
5. `app.js`
Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout.
```
Create `webui/css/README.md`:
```markdown
# WebUI CSS modules
Plain CSS files loaded by `webui/index.html`.
Recommended order:
1. `tokens.css`
2. `base.css`
3. `layout.css`
4. `components.css`
5. focused panel or feature CSS
6. `styles.css` compatibility remainder
Keep selectors stable so existing HTML and JavaScript continue to work.
```
- [ ] **Step 2: Add no-op load anchors to `index.html`**
Insert comments around the existing assets:
```html
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
```
```html
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="app.js?v=console-20260520-theme-v35"></script>
```
- [ ] **Step 3: Verify**
Run:
```powershell
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected: selected tests PASS.
- [ ] **Step 4: Commit and push**
```powershell
git add webui/index.html webui/js/README.md webui/css/README.md
git commit -m "refactor(webui): add static module split structure"
git push
```
---
## Task 2: Extract JavaScript Constants and Copy
**Files:**
- Create: `webui/js/constants.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `constants.js`**
Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged:
```javascript
const UI_LIMITS = Object.freeze({
runLogMaxLines: 50000,
runLogMaxChars: 200000,
actionsLogMaxLines: 5000,
scrollBottomThresholdPx: 5,
screenshotPollMs: 1500,
logPollMs: 800,
statsPollMs: 1200,
});
const UI_CLASS = Object.freeze({
busy: "isBusy",
clickable: "isClickable",
collapsed: "isCollapsed",
listCollapsed: "isListCollapsed",
reservationHeader: "reservationHeader",
reservationBody: "reservationBody",
reservationsList: "reservationsList",
shotEmpty: "isShotEmpty",
statusRunning: "statusRunning",
statusIdle: "statusIdle",
statusError: "statusError",
});
const RUN_TONE = Object.freeze({
running: "running",
idle: "idle",
error: "error",
});
```
Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged.
- [ ] **Step 2: Remove moved constants from `app.js`**
Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now.
- [ ] **Step 3: Load `constants.js` before `app.js`**
Change the bottom of `webui/index.html` to:
```html
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="js/constants.js?v=console-20260531-split-1"></script>
<script src="app.js?v=console-20260531-split-1"></script>
```
- [ ] **Step 4: Verify**
Run:
```powershell
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected: both PASS.
- [ ] **Step 5: Browser smoke**
Start:
```powershell
python gui\web_gui.py
```
Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors.
- [ ] **Step 6: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/constants.js
git commit -m "refactor(webui): extract frontend constants"
git push
```
---
## Task 3: Extract DOM and Formatting Helpers
**Files:**
- Create: `webui/js/dom_utils.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `dom_utils.js`**
Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged:
```javascript
function $(id)
function setTextIfExists(id, text)
function clearEl(el)
function escapeHtml(s)
function fmtTime(ts)
function fmtNum(v)
function fmtDuration(seconds)
```
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete the moved function declarations only. Do not move UI initialization functions yet.
- [ ] **Step 3: Load `dom_utils.js` after `constants.js`**
```html
<script src="js/constants.js?v=console-20260531-split-2"></script>
<script src="js/dom_utils.js?v=console-20260531-split-2"></script>
<script src="app.js?v=console-20260531-split-2"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/dom_utils.js
git commit -m "refactor(webui): extract DOM and format helpers"
git push
```
---
## Task 4: Extract API Client Helpers
**Files:**
- Create: `webui/js/api_client.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `api_client.js`**
Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged:
```javascript
let _apiFailStreak = 0;
const _apiFailThreshold = 2;
let _csrfToken = null;
function setConnState(state)
function notifyApiOk()
function notifyApiFail()
async function apiGet(path)
async function getCsrfToken()
async function apiPost(path, body)
```
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
- [ ] **Step 2: Remove moved declarations from `app.js`**
Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`.
- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`**
```html
<script src="js/constants.js?v=console-20260531-split-3"></script>
<script src="js/dom_utils.js?v=console-20260531-split-3"></script>
<script src="js/api_client.js?v=console-20260531-split-3"></script>
<script src="app.js?v=console-20260531-split-3"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/api_client.js
git commit -m "refactor(webui): extract API client helpers"
git push
```
---
## Task 5: Extract Log View Behavior
**Files:**
- Create: `webui/js/log_views.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `log_views.js`**
Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`:
```javascript
function classifyLogLine(line)
function renderLogLineNode(line)
function appendLog(lines)
function renderRunLog()
function appendRunLogLines(lines)
async function fetchActionsLog()
function renderActionsLog()
```
Keep these shared state variables in `app.js` for this task:
```javascript
let runLogBuffer = [];
let runLogFilter = "";
let runLogMode = "filter";
let runSearchResultsBuffer = [];
let runSearchActive = false;
let actionsLogBuffer = [];
let actionsLogFilter = "";
```
Because classic scripts share global scope, `log_views.js` can keep using these names.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved function declarations.
- [ ] **Step 3: Load `log_views.js` before `app.js`**
```html
<script src="js/constants.js?v=console-20260531-split-4"></script>
<script src="js/dom_utils.js?v=console-20260531-split-4"></script>
<script src="js/api_client.js?v=console-20260531-split-4"></script>
<script src="js/log_views.js?v=console-20260531-split-4"></script>
<script src="app.js?v=console-20260531-split-4"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/log_views.js
git commit -m "refactor(webui): extract log view behavior"
git push
```
---
## Task 6: Extract Dashboard Renderers
**Files:**
- Create: `webui/js/dashboard_renderers.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `dashboard_renderers.js`**
Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`:
```javascript
function renderBars(containerId, dataMap, labelMap)
function renderTopContent(containerId, items)
function renderWinsTable(containerId, wins)
function renderTimeline(containerId, timeline)
function renderOverviewSparkline(svgId, timeline)
```
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved renderer declarations.
- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`**
```html
<script src="js/dashboard_renderers.js?v=console-20260531-split-5"></script>
<script src="app.js?v=console-20260531-split-5"></script>
```
Keep all earlier module script tags before `dashboard_renderers.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/dashboard_renderers.js
git commit -m "refactor(webui): extract dashboard renderers"
git push
```
---
## Task 7: Extract Config Form Binding
**Files:**
- Create: `webui/js/config_form.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `config_form.js`**
Move these config-related functions from `app.js` into `webui/js/config_form.js`:
```javascript
function getConfigBoundElements()
function syncMirrorFields()
function getConfigValue(cfg, key)
function coerceValue(type, raw, isCheckbox)
function applyConfigToUI(cfg)
function collectConfigFromUI()
async function loadConfig()
async function saveConfig()
```
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved config declarations.
- [ ] **Step 3: Load `config_form.js` before `app.js`**
```html
<script src="js/config_form.js?v=console-20260531-split-6"></script>
<script src="app.js?v=console-20260531-split-6"></script>
```
Keep all earlier module script tags before `config_form.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/config_form.js
git commit -m "refactor(webui): extract config form bindings"
git push
```
---
## Task 8: Extract Polling and Device Actions
**Files:**
- Create: `webui/js/runtime_actions.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `runtime_actions.js`**
Move these functions from `app.js` into `webui/js/runtime_actions.js`:
```javascript
async function refreshDevices()
function decorateDeviceSelect()
function selectedDeviceId()
async function postDeviceAction(path, body, successPrefix)
async function forceStopRun()
async function sendBackKey()
async function wifiEnable()
async function wifiConnect()
async function wifiDisconnect()
async function tryAutoReconnectLastWifi()
async function wifiScan()
async function startRun()
async function testYanghao()
async function testComment()
async function stopRun()
async function pollLogs()
async function pollReservations()
async function pollHighValueRooms()
async function pollStats()
function startPolling()
function startStatsPolling()
```
Keep `DOMContentLoaded` event wiring in `app.js`.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved runtime declarations.
- [ ] **Step 3: Load `runtime_actions.js` before `app.js`**
```html
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
<script src="app.js?v=console-20260531-split-7"></script>
```
Keep all earlier module script tags before `runtime_actions.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/runtime_actions.js
git commit -m "refactor(webui): extract runtime actions and polling"
git push
```
---
## Task 9: Reduce `app.js` to Initialization Glue
**Files:**
- Create: `webui/js/ui_init.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Move UI initialization helpers**
Move these functions into `webui/js/ui_init.js`:
```javascript
function initTheme()
function ensureToastContainer()
function toast(message, kind = "info", { duration = 3500 } = {})
function initConfigSearch()
function initFooter()
function attachCopyButtons()
function initKeyboardShortcuts()
function initHeaderScroll()
function initShotFullscreen()
function applyKbdHints()
function initStickySectionShadow()
function initShortcutsHelp()
function updateTabBadge(target, count)
function startReservationsCountdownTick()
function initTabs()
function attachNumberSteppers()
function pollShot()
function startShotPolling()
function setButtonBusy(id, busy)
function setRunOverview(state, meta, tone)
function updateDeviceOverview()
```
- [ ] **Step 2: Keep `app.js` as bootstrapping only**
After this task, `app.js` should contain:
```javascript
window.addEventListener("DOMContentLoaded", async () => {
initTheme();
initTabs();
initConfigSearch();
initFooter();
attachCopyButtons();
initShotFullscreen();
initHeaderScroll();
initKeyboardShortcuts();
initShortcutsHelp();
initStickySectionShadow();
attachNumberSteppers();
applyKbdHints();
syncMirrorFields();
await refreshDevices();
await loadConfig();
startPolling();
startStatsPolling();
startShotPolling();
startReservationsCountdownTick();
pollLogs();
pollStats();
pollShot();
pollReservations();
pollHighValueRooms();
});
```
During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`.
- [ ] **Step 3: Verify and smoke**
Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save.
- [ ] **Step 4: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/ui_init.js
git commit -m "refactor(webui): reduce app script to initialization glue"
git push
```
---
## Task 10: Split CSS Tokens and Base Rules
**Files:**
- Create: `webui/css/tokens.css`
- Create: `webui/css/base.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract theme tokens**
Move these ranges from `styles.css` into `webui/css/tokens.css`:
- `:root { ... }` light theme token block
- `:root[data-theme="dark"] { ... }` dark theme token block
- reduced-motion token or global animation defaults that are pure variables
Do not rename variables.
- [ ] **Step 2: Extract base element rules**
Move base reset and generic element rules into `webui/css/base.css`:
- `*`, `html`, `body`
- `button`, `input`, `select`, `textarea`
- generic focus-visible rules
- global scrollbar rules
- generic utility classes that are not tied to one panel
- [ ] **Step 3: Load extracted CSS before `styles.css`**
```html
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-1" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-1" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-1" />
```
- [ ] **Step 4: Verify and smoke**
Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css
git commit -m "refactor(webui): extract CSS tokens and base rules"
git push
```
---
## Task 11: Split CSS Layout and Shared Components
**Files:**
- Create: `webui/css/layout.css`
- Create: `webui/css/components.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract layout rules**
Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors.
- [ ] **Step 2: Extract shared component rules**
Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors.
- [ ] **Step 3: Load CSS in stable order**
```html
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-2" />
```
- [ ] **Step 4: Verify and smoke**
Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css
git commit -m "refactor(webui): extract CSS layout and shared components"
git push
```
---
## Task 12: Split CSS Feature Panels
**Files:**
- Create: `webui/css/panels.css`
- Create: `webui/css/logs.css`
- Create: `webui/css/charts.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract panel-specific styles**
Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`.
- [ ] **Step 2: Extract log styles**
Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`.
- [ ] **Step 3: Extract chart/table styles**
Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`.
- [ ] **Step 4: Load CSS in stable order**
```html
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/panels.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/logs.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/charts.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-3" />
```
- [ ] **Step 5: Verify and smoke**
Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping.
- [ ] **Step 6: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css
git commit -m "refactor(webui): extract CSS feature panels"
git push
```
---
## Task 13: Decide Whether to Split `index.html`
**Files:**
- Modify: `webui/index.html`
- Optional create: `webui/partials/README.md`
- [ ] **Step 1: Recount file sizes**
Run:
```powershell
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
```
- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines**
If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet.
If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of:
- server-side partial injection in `gui/web_gui.py`
- client-side fetch of static partials
- build-time HTML generation
- [ ] **Step 3: Commit only if docs are added**
If `webui/partials/README.md` is created:
```powershell
git add webui/partials/README.md
git commit -m "docs(webui): record HTML partial split decision"
git push
```
---
## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable
**Files:**
- Create: `gui/web_gui_pkg/static_handler.py`
- Create: `gui/web_gui_pkg/request_parsing.py`
- Create: `gui/web_gui_pkg/routes.py`
- Modify: `gui/web_gui.py`
- Test: `tests/test_webgui.py`
- [ ] **Step 1: Extract request parsing helpers**
Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance:
```python
def send_json(handler: BaseHTTPRequestHandler, obj: object, status: int = 200) -> None:
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Cache-Control", "no-store")
handler.send_header("Content-Length", str(len(data)))
handler.end_headers()
handler.wfile.write(data)
```
```python
def read_json(handler: BaseHTTPRequestHandler) -> dict:
n = int(handler.headers.get("Content-Length") or 0)
raw = handler.rfile.read(n) if n > 0 else b"{}"
try:
value = json.loads(raw.decode("utf-8"))
except Exception:
return {}
return value if isinstance(value, dict) else {}
```
Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first.
- [ ] **Step 2: Extract static file serving**
Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`:
```python
def serve_static(
handler: BaseHTTPRequestHandler,
*,
webui_dir: str,
rel_path: str,
log_error: Callable[[str], None],
) -> None:
# paste current Handler._serve_static body and replace:
# self -> handler
# WEBUI_DIR -> webui_dir
# _wg_log(...) -> log_error(...)
```
Keep `Handler._serve_static` as:
```python
def _serve_static(self, rel_path: str) -> None:
serve_static(
self,
webui_dir=WEBUI_DIR,
rel_path=rel_path,
log_error=lambda msg: _wg_log(msg, level="ERROR"),
)
```
- [ ] **Step 3: Verify**
Run:
```powershell
python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1
pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1
```
Expected: PASS.
- [ ] **Step 4: Commit and push**
```powershell
git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py
git commit -m "refactor(webgui): extract request and static helpers"
git push
```
---
## Task 15: Final Outcome Note
**Files:**
- Modify: this plan file
- [ ] **Step 1: Record final sizes**
Run:
```powershell
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
```
- [ ] **Step 2: Append outcome**
Append:
```markdown
## Outcome
- `webui/app.js`: 2512 -> actual final line count
- `webui/styles.css`: 3745 -> actual final line count
- `webui/index.html`: 1232 -> actual final line count
- `gui/web_gui.py`: 1663 -> actual final line count
- Extracted JS modules: actual module filenames
- Extracted CSS modules: actual module filenames
- Verification: exact pytest log path and browser smoke result
- Remaining large files: actual top remaining files from the final size command
```
- [ ] **Step 3: Commit and push**
```powershell
git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md
git commit -m "docs(webui): record large-file split outcome"
git push
```
---
## Execution Notes
- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one.
- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task.
- Do not introduce a frontend build step in this plan.
- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean.
- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit.
- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade.
- Project rule: only stage files changed by the current task.
@@ -0,0 +1,244 @@
# 拆分 gui/gui_app.py 设计文档
## 背景
`gui/gui_app.py` 当前 5476 行,几乎全部代码都嵌在单个 `main()` 函数里,
内含 50+ 个闭包,捕获大量 widgets 和 tkinter Var。文件已经被多轮抽取过:
- `5649 → 5537`:`ThreadSafeLogWriter` → `components/log_writer`
- `5539 → 5370`:`_open_realtime_viewer_impl` → `components/realtime_viewer`
- `6339 → 5634`:`refresh_stats` 字符串格式化 → `components/stats_formatter`
继续按相同思路把内聚闭包抽到 `gui/components/*`,主文件继续瘦身。
## 目标
迭代式抽取 `gui/gui_app.py` 中的内聚闭包,主文件越变越小,
**不改变任何 GUI 运行行为**。
### 成功标准
1. `gui/gui_app.py` 行数显著下降(目标:≤ 3000 行;继续视边际收益决定是否再抽)
2. `pytest` 全绿
3. 每次抽取产生一个独立 commit,保持小步可回滚
4. GUI 启动 + 主要交互路径无回归(手工 smoke:启动 GUI、打开 WiFi 对话框、加载配置、截图、查看日志)
### 非目标
- 不重构 GUI 整体架构(不引入 MVC/MVVM)
- 不改变 `gui_app.py` 对外暴露的入口(`main()`、`format_gui_log_line()`)
- 不优化性能、不修 bug(除非抽取过程中发现)
- 不动 `gui/web_gui.py`(属于下一轮独立 spec)
## 抽取候选清单
按「行数 × 边界清晰度」排序(行数粗略统计):
| 优先级 | 闭包 | 行范围 | 行数 | 目标文件 | 主要依赖 |
|---|---|---|---|---|---|
| P1 | `open_wifi_adb_dialog` | 743-1588 | 845 | `components/wifi_adb_dialog.py` | ADB 工具 + 几个回调 |
| P2 | `load_config_to_ui` + `save_ui_to_config` | 2748-3402 | 654 | `components/config_io.py` | 100+ tkinter Var(需聚合)|
| P3 | `refresh_reservations` | 4530-4805 | 275 | `components/reservations_view.py` | 1-2 个 Treeview + 路径 |
| P4 | `refresh_high_value_rooms` | 4805-5085 | ~280 | `components/high_value_view.py` | 1 个 Treeview + 路径 |
| P5 | `do_screenshot` + `_bind_screenshot_button` | 3402-3651 | 249 | `components/screenshot_action.py` | ADB exe + 路径 + 状态 Label |
| P6 | `refresh_actions_log` + 搜索栏 | 4892-5070 | ~178 | `components/actions_log_view.py` | Text widget + 路径 |
**估算**:完整抽完 P1-P6 约减 2480 行 → 主文件 ~3000 行。
若 P2 风险评估后觉得不值得做,可跳过,仍能减约 1830 行 → ~3650 行。
## 抽取模式(每轮通用)
每个候选段按以下步骤处理:
### 1. 摸清依赖
读完整段代码,列出:
- 捕获的 `main()` 局部变量(widgets / Vars / 路径 / 状态)
- 调用的 `main()` 内其它闭包(回调)
- 调用的 module-level 函数 / 项目其它模块函数
### 2. 设计签名
把闭包改造为顶层函数:
```python
# components/<feature>.py
def <feature_action>(
parent: tk.Misc, # 父窗口或容器
*,
deps: <FeatureDeps>, # 依赖注入容器
on_line: Callable[[str], None], # 日志回调
...
) -> <return-type>:
"""..."""
```
依赖容器优先用 `dataclass`(命名参数太多时):
```python
@dataclass
class <FeatureDeps>:
adb_exe: str
ip_var: tk.StringVar
refresh_devices: Callable[[], None]
# ...
```
### 3. 抽取 + 注入
- 在 `gui/components/<feature>.py` 写新函数
- 在 `gui_app.py` 原位置:删旧闭包,import 新函数,传依赖调用
### 4. 验证
```bash
pytest # 全部通过
python -m py_compile gui/gui_app.py gui/components/<feature>.py
# 手工 smoke:启动 GUI 走一遍受影响功能
```
### 5. 提交
按 AGENTS.md 规则:
- `git status` 检查只改了预期文件
- `git add` 具体路径,不用 `-A`
- commit 消息格式参考历史:`refactor(gui): 抽 <feature> 到 components/<file> (<旧行数> → <新行数>)`
- `git push`
## 风险
| 风险 | 缓解 |
|---|---|
| 闭包捕获 Var 漏传 → 配置项静默丢失 | P2 用 `dataclass` 聚合 Var 引用;先写完整测试再改 |
| GUI 交互回归(按钮回调失效等) | 每轮手工 smoke;优先抽边界清晰的 P1/P5 验证流程 |
| `mainloop` / `after()` 调度跨闭包失效 | 显式把 `root` 或 `tk_widget.after` 当依赖传入 |
| import 循环(components → gui_app) | components/* 不允许 import gui_app;只接收依赖参数 |
## 停止条件
满足任一即停手,向用户报告本轮成果:
1. `gui_app.py` ≤ 3000 行
2. 下一个候选段需要传 ≥ 50 个独立依赖(信号:应该先把 widgets 聚成一个 `UiState`,那是另一个 spec)
3. 抽取后 `gui_app.py` 行数下降 < 50(边际收益太小)
4. 某轮抽取后 pytest 失败且修复需要改动多个非目标文件(信号:风险扩散,停下复盘)
## 实现顺序
按 P1 → P2 → P3 → P4 → P5 → P6,每段独立 commit。
P2 视 P1 完成后情况评估(如果 P1 已经把主文件压到很小,P2 可推迟)。
## 测试策略
- **现有 pytest**:每轮必须保持全绿(不需要为抽取新增单测,因为是纯重构)
- **手工 smoke**(每轮都要走一遍受影响路径):
- P1:启动 → 打开 "WiFi ADB" 对话框 → 扫描设备 → 连接
- P2:启动 → 修改若干配置项 → 关闭 → 重启 → 检查配置已保存
- P3/P4:启动 → 切到「预约」/「高价值房间」Tab → 验证刷新
- P5:启动 → 截图按钮 → 检查图片落盘
- P6:启动 → 切到「操作日志」Tab → 搜索
## Out of Scope
- `gui/web_gui.py`(1810 行)—— 下一轮独立 spec
- `douyin/core/*` 几个 1000+ 行业务文件 —— 下一轮独立 spec
- 引入新的 GUI 框架或异步模式
- 单元测试覆盖率提升
## Outcome(2026-05-30 实施完成)
**起始**:5476 行
**结束**:178 行
**降幅**:5298 行(-96.7%)
**新增模块**:54 个 component 文件
### 主文件最终结构(178 行)
```
imports 45 行 (gui_core / 14 个 components / stdlib)
warnings 抑制 / format_gui_log_line 18 行
def main(): ~115 行
setup_root_window
setup_log_pipeline ← (queue + ThreadSafeLogWriter + on_line + Runner)
setup_top_device_bar ← (设备选择 + WiFi 工具)
build_config_vars ← (127 个 tk Var)
setup_left_config_area ← (PanedWindow + 7 配置 Tab + load/save IO)
setup_right_main_area ← (Notebook + 9 Tab + actions + pump_logs)
setup_top_buttons ← (保存配置 + 截图+OCR)
setup_periodic_refreshers ← (启动延迟 + 周期刷新)
setup_close_handler ← (WM_DELETE_WINDOW)
refresh_devices() / mainloop()
```
### 抽取阶段总结
实施分 4 个阶段:
**阶段 1:闭包/视图抽取(5476 → 3590 行,-34%)**
把 `main()` 内的内聚闭包和视图刷新函数抽到独立模块。共 17 个模块:
wifi_adb_scan_dialog / wifi_adb_dialog / reservations_view / high_value_view /
screenshot_action / actions_log_view / wifi_adb_pick_dialog / wifi_adb_reconnect /
ocr_results_view / log_pump / win_record_view / preview_view /
wifi_adb_one_click_scan / run_log_view / text_search /
logging_config_io / run_params_builder。
**阶段 2:Var 聚合 + Tab UI(3590 → 1373 行,-44% → -75%)**
- `config_io.py`(load/save 640 行 → 1 个模块)用 dict-of-vars 模式
- `build_config_vars()` 工厂集中创建 127 个 tk Var
- 7 个 Tab UI(debug / logging / yanghao / reservation / run / filter / realtime)抽
到独立 `setup_*_tab(parent, vars_=_vars_)`,直接接受 vars 全集
**阶段 3:右侧 Tab + 工具栏 + 模板复用(1373 → 519 行,-75% → -90.5%)**
- log_search_toolbar / actions_log_toolbar 用 dataclass + handles 返回
- win_record_tab / preview_tab / log_tab 整段抽出
- simple_tabs.py 提供 setup_simple_text_tab / setup_text_tab_with_refresh /
setup_stats_tab / setup_actions_log_tab / setup_ocr_results_tab 复用模板
- main_notebook / action_buttons / top_buttons / top_device_bar /
log_pipeline / periodic_refreshers / log_text_colors / keywords_tab 全部抽出
**阶段 4:聚合层 + 死代码清理(519 → 178 行,-90.5% → -96.7%)**
最后阶段把 main() 里剩余的"装配脉络"打包成更高层组件,清理失效的导入和死注释:
- `setup_root_window`: ttkbootstrap fallback + root window
- `setup_left_config_area`: PanedWindow 布局 + 7 配置 Tab + load/save IO
- `setup_right_main_area`: Notebook + 9 Tab + actions + pump_logs
- 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var)
- 死注释清理 / 重复 import / 冗余 dict 字面量(_config_io_vars 复用 _vars_ 全集)
- 重复 lambda 去重(theme_getter / _open_realtime_viewer)
### 抽取模式(54 个 components 按用途分类)
| 类型 | 模块 |
|---|---|
| WiFi ADB(6 个) | wifi_adb_scan_dialog / wifi_adb_dialog / wifi_adb_pick_dialog / wifi_adb_reconnect / wifi_adb_one_click_scan / top_device_bar |
| Tab 视图(8 个) | reservations_view / high_value_view / actions_log_view / ocr_results_view / win_record_view / preview_view / run_log_view / log_pump |
| Tab UI 容器(13 个) | run_tab / filter_tab / reservation_tab / yanghao_tab / debug_tab / logging_tab / keywords_tab / log_tab / preview_tab / win_record_tab / realtime_tab / simple_tabs / main_notebook |
| 工具栏(2 个) | log_search_toolbar / actions_log_toolbar |
| 配色 / 状态(3 个) | log_text_colors / text_search / screenshot_action |
| 配置序列化(4 个) | logging_config_io / run_params_builder / config_io / config_vars |
| 顶部 / 底部按钮(2 个) | top_buttons / action_buttons |
| 系统调度(2 个) | log_pipeline / periodic_refreshers |
| 高层聚合(3 个) | root_window / left_config_area / right_main_area |
| 已有共用(11 个) | log_writer / log_viewer / log_color_config / mapping_table / mapping_utils / device_selector / actions_log_viewer / error_log_viewer / realtime_viewer / stats_formatter / __init__ |
### 验证
- 每轮抽取后 `pytest` 全绿(1374 passed),包括 `test_gui_app_smoke.py` 启动 smoke 和
`test_gui_webui_sync.py` GUI/WebUI 配置 key 同步检查。
- 共 7 次 pytest 失败均能定位修复(具体错误参见各次 commit message):
- `_preview_view` 在 `update_image_list` 之前被引用
- `enable_ocr_mode1_var` 因含数字未被正则替换(2 次)
- `BOTH` 常量 / `ScrolledText` import 缺失
- sync 工具锚点失效 → 让工具改读 `config_io.py` + `realtime_tab.py`
- `image_var` 在 `setup_top_buttons` 调用时还没创建 → 调整顺序
- 未做手工 GUI smoke(建议用户启动 GUI 走一遍 WiFi 对话框 / 各 Tab,确认无回归)。
### 停止原因
主文件已从 5476 → 178(-96.7%)。当前 main() 是清晰的"装配胶水":每个 setup_*
调用对应一个明确的功能区。继续抽要么打散这个装配脉络,要么把整个 main 改造成
`GuiApp` 类(MVC/MVVM),都属于另一个 spec。`pytest` 1374 全绿。
+83 -65
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=/mnt/share/douyin_debug 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`
**优化措施**:
@@ -7361,4 +7380,3 @@ def get_fudai_contain(analyser, renwu: int = 2):
- 第24章:OCR预处理和优化详解
- 第25章:路径配置系统详解
- 第26章:文本处理工具函数详解
+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加速
View File
Whitespace-only changes.
+7 -6
View File
@@ -19,8 +19,8 @@
2. **运行设置脚本(使用Bypass参数绕过执行策略)**
```powershell
cd "C:\Users\12742\Desktop\douyin_guaji-main"
powershell.exe -ExecutionPolicy Bypass -File ".\setup_auto_commit.ps1"
cd "<项目根目录>"
powershell.exe -ExecutionPolicy Bypass -File ".\scripts\setup_auto_commit.ps1"
```
3. **完成!** 脚本会自动创建定时任务,每小时自动提交和推送代码。
@@ -51,8 +51,8 @@
1. 选择"启动程序"
2. 点击"下一步"
3. 程序或脚本:输入 `powershell.exe`
4. 添加参数:输入 `-ExecutionPolicy Bypass -File "C:\Users\12742\Desktop\douyin_guaji-main\auto_commit_push.ps1"`
5. 起始于:输入 `C:\Users\12742\Desktop\douyin_guaji-main`
4. 添加参数:输入 `-ExecutionPolicy Bypass -File "<项目根目录>\scripts\auto_commit_push.ps1"`
5. 起始于:输入 `<项目根目录>`
6. 点击"下一步"
### 步骤5:完成设置
@@ -85,7 +85,9 @@
您也可以使用以下PowerShell命令(以管理员身份运行)快速创建任务:
```powershell
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"C:\Users\12742\Desktop\douyin_guaji-main\auto_commit_push.ps1`"" -WorkingDirectory "C:\Users\12742\Desktop\douyin_guaji-main"
$projectRoot = "<项目根目录>"
$scriptPath = Join-Path $projectRoot "scripts\auto_commit_push.ps1"
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"$scriptPath`"" -WorkingDirectory $projectRoot
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration (New-TimeSpan -Days 365)
@@ -130,4 +132,3 @@ Register-ScheduledTask -TaskName "Git自动提交推送" -Action $action -Trigge
4. 切换到"触发器"选项卡
5. 编辑触发器,修改重复间隔
6. 保存更改
+1 -1
View File
@@ -148,4 +148,4 @@ python run_cli.py --high-value-room-revisit-only-current-run
2. **价值预测**:基于历史数据预测房间价值潜力
3. **多策略**:支持不同的重访策略选择
4. **统计报告**:生成重访效果统计报告</content>
<parameter name="filePath">c:\Users\12742\Desktop\douyin_guaji-main\docs\高价值房间重访功能说明.md
<parameter name="filePath">docs\高价值房间重访功能说明.md
+19 -705
View File
@@ -1,709 +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 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:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
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,539 @@
"""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, Optional
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
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):
_raw = Image.open(screenshot_path)
try:
_raw.load()
pic_rgb_full = _raw.convert("RGB")
finally:
_raw.close()
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,89 @@
"""douyin_flow_control_pkg.no_fudai - 无福袋情况的简单流程。
handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待 / 上滑切换。
"""
from __future__ import annotations
import logging
import time
from typing import Any, Callable, List, Optional
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,28 @@
"""douyin_flow_control_pkg.stage_handler - 阶段诊断后的状态记录。
handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转),
为基础抢福袋流程的状态机提供锚点。
"""
from __future__ import annotations
import time
from typing import Any
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,
)
+119 -2862
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,91 @@
"""douyin/core/fudai_modules/fudai_device_control - 共享 ADB 设备操作
抽出 handle_detail_helpers 中重复 2 次的兜底 swipe 逻辑:
- _handle_error_status (L266-318)
- _fallback_swipe_up (L1187-1239)
两处都做"没有 swipe_up_to_next_live 时直接 ADB shell input swipe,失败再回退到
operation.swipe"。提到这里统一管理。
"""
from __future__ import annotations
import os
import subprocess
from typing import Any
def fallback_swipe_up_via_adb(self: Any) -> None:
"""没有 swipe_up_to_next_live 时用 ADB shell input swipe 兜底切换直播间。
流程:
1. 按 self.resolution_ratio_x/y(默认 1080x2400)计算起止坐标
2. 优先调用 self.operation._adb_path() 获取 adb 路径
3. 直接 subprocess.run ADB shell input swipe
4. 任何异常 → 回退到 self.operation.swipe(...)
主要用于 _handle_error_status 的"连续 task_count_zero≥3 强制切房"分支
和 _fallback_swipe_up 的"没有 swipe_up_to_next_live 时兜底"。
"""
try:
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
try:
if hasattr(self.operation, "_adb_path"):
adb_cmd = self.operation._adb_path()
else:
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if adb_cmd.startswith('"') and adb_cmd.endswith('"'):
adb_cmd = adb_cmd[1:-1]
cmd = [
adb_cmd,
"-s",
str(self.device_id),
"shell",
"input",
"swipe",
str(int(start_x)),
str(int(start_y)),
str(int(end_x)),
str(int(end_y)),
"300",
]
subprocess.run(
cmd,
timeout=5.0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
def swipe_up_or_fallback(self: Any) -> None:
"""优先调 self.swipe_up_to_next_live(),否则走 fallback_swipe_up_via_adb 兜底。
替代 handle_detail_helpers 中 L266-318 的内联兜底实现。
"""
try:
if hasattr(self, "swipe_up_to_next_live"):
self.swipe_up_to_next_live()
return
except Exception:
pass
fallback_swipe_up_via_adb(self)
@@ -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(
File diff suppressed because it is too large. Load diff
+217
View File
@@ -0,0 +1,217 @@
"""douyin/core/fudai_modules/init_helpers - fudai_analyse 配置默认值与运行时状态初始化
把 fudai_analyse.__init__ 中"配置字段默认值 + 运行时状态字段初始化 + 状态文件
路径解析"的整段抽出来。原 __init__ 保留:设备/分辨率、operation 实例、日志系统
初始化、_run_id、_log_kv 等需要早期就绪的核心字段。
入口:apply_fudai_defaults(self) 一次性把所有"普通字段默认值"应用到实例。
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional, Tuple
def apply_fudai_defaults(self: Any) -> None:
"""把 fudai_analyse 实例的所有配置默认值 + 运行时状态字段一次性初始化。
依赖前提(必须由 caller 在调用前已设置):
- self.operation, self.device_id, self.y_pianyi
- self.resolution_ratio_x, self.resolution_ratio_y
- self._log_kv 等日志相关字段
本函数不调用 load_config(让 caller 决定时机)。
"""
self._forced_reservation_detail = None
self._forced_reservation_fudai_x = None
# 进入直播间后诊断与阶段流转所需的一些状态
self._last_diag_stage = "INIT"
self._last_diag_seen = "-"
self._last_diag_ts = 0.0
# 30 分钟超时相关:记录最后一次成功参与福袋的时间
self._last_successful_attend_ts = 0.0
self._no_attend_timeout_minutes = 30.0
self._run_start_ts = time.time()
# 预约状态上次写盘时间(初始化以避免 attribute-defined-outside-init 警告)
self._reservations_state_last_write_ts = 0.0
self.last_fudai_x = 0 # 上次检测到的福袋图标 X 坐标(用于优化搜索)
# 与配置相关的核心字段
self.contains_not_want = []
self.contains_want = []
self.min_prize_value_yuan = 0.0
self.min_participants = 0
self.max_participants = 0
self.skip_if_countdown_gt_seconds = 900
self.skip_if_countdown_lt_seconds = 0
self.no_fudai_watchdog_enabled = False
# 福袋图标检测节流相关默认值
self.fudai_icon_retry_delay_seconds = 0.6
self.fudai_icon_max_wait_seconds = 5.0
self.fudai_exit_after_misses = 999999
self.enable_back_on_misses = False
self.fudai_click_wait_seconds = 1.0
self.switch_room_wait_after_stage_diag_seconds = 7.0
self.swipe_duration_ms = 600
self.fudai_find_max_attempts = 10 # 已废弃,保留兼容性
# 优化查找器相关配置
self.fudai_finder_optimized_enabled = True
self.fudai_click_verify_enabled = True
self.fudai_find_max_retries = 3
self.screenshot_diagnose_min_interval_seconds = 8.0
self.lucky_draw_red_ratio_threshold = 0.9
self.coupon_template_match_threshold = 0.75
self.attend_button_red_ratio_threshold = 0.25
self.fansclub_join_red_ratio_threshold = 0.25
self.live_room_match_threshold = 0.8
self.fudai_template_match_enabled = False
self.fudai_template_match_threshold = 0.7
# 高价值福袋 / 预约相关配置
self.high_value_fudai_enabled = False
self.high_value_fudai_threshold_yuan = 500.0
self.high_value_fudai_join_ahead_seconds = 100
self.high_value_fudai_max_swipe_back = 35
self.high_value_fudai_max_reservations = 3
self.high_value_fudai_after_action = "continue"
self.high_value_fudai_after_stay_seconds = 120
self.high_value_fudai_poll_before_seconds = 10.0
# 高价值直播间"回访"相关
self.high_value_room_revisit_enabled = False
self.high_value_room_revisit_only_current_run = False
self.high_value_room_revisit_min_interval_seconds = 300
self.high_value_room_revisit_max_per_run = 5
self.high_value_room_revisit_min_prize_value = 0.0
self.high_value_room_revisit_max_age_days = 30
# 粉丝团相关配置
self.auto_join_fansclub = False
self.fansclub_fail_action = "stay"
# 预约回退相关
self.reservation_back_verify_enabled = True
self.reservation_back_swipe_delay = 0.6
# 滑动次数重置相关
self.reset_after_swipes_enabled = False
self.reset_after_swipes = 10
# 意外返回桌面自救相关(坐标兜底,主路径已改用 launch_package 包名启动)
self.desktop_icon_x = 153
self.desktop_icon_y = 260
self.yanghao_fallback_live_x = 540
self.yanghao_fallback_live_y = 2000
self.yanghao_fallback_enter_live_x = 540
self.yanghao_fallback_enter_live_y = 1200
# 推荐页养号默认配置
_apply_yanghao_defaults(self)
# 预约运行时状态(单次运行内有效)
self.reservations = []
self._first_run_once_basic = True
self.room_pos = 0
self.reservation_focus_until_ts = 0.0
self.reservation_after_action_pending = False
self.reset_to_list_after_reservations = False
self.queue_full_waiting_at_earliest = False
# 预约队列状态文件 + 清理映射表导出文件
_resolve_reservations_state_path(self)
_cleanup_old_room_pos_map_files(self)
# 已记录统计的福袋跟踪
self._recorded_fudai_stats = set()
# 运行时状态标志
self.needswitch = None
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._skip_stage_diagnosis_and_find_fudai = False
self._just_switched_room = False
# 高价值房间重访相关状态
self._last_high_value_revisit_ts = time.time()
self._current_run_revisit_count = 0
self._current_run_high_value_rooms = []
self._last_fudai_detail_tuple = None
self._current_fudai_future_ts = 0.0
self._current_fudai_content = ""
self._fudai_detail_first_read = False
self._fudai_detail_consecutive_failures = 0
self._detail_closed_by_attend = False
self._lottery_result_expected_ts = 0.0
self._lottery_wait_start_ts = 0.0
def _apply_yanghao_defaults(self: Any) -> None:
"""推荐页养号相关默认配置。"""
self.yanghao_enabled = True
self.yanghao_enable_actions = True
self.yanghao_step_screenshot = False
self.yanghao_recommend_duration_seconds = 60
self.yanghao_recommend_interval_seconds = 0
self.yanghao_like_prob = 0.15
self.yanghao_fav_prob = 0.05
self.yanghao_comment_prob = 0.0
self.yanghao_dwell_on_action_min_seconds = 5.0
self.yanghao_dwell_on_action_max_seconds = 30.0
self.yanghao_icon_roi_size = 180
self.yanghao_icon_match_threshold = 0.70
self.yanghao_like_roi_scale = 1.5
self.yanghao_fav_roi_scale = 1.5
self.yanghao_like_icon_match_threshold = None
self.yanghao_fav_icon_match_threshold = None
self.yanghao_like_icon_x = 0
self.yanghao_like_icon_y = 0
self.yanghao_fav_icon_x = 0
self.yanghao_fav_icon_y = 0
self.yanghao_like_roi_offset_x = 0
self.yanghao_like_roi_offset_y = 0
self.yanghao_fav_roi_offset_x = 0
self.yanghao_fav_roi_offset_y = 0
self._last_yanghao_ts = 0.0
self.yanghao_comment_btn_x = 0
self.yanghao_comment_btn_y = 0
self.yanghao_comment_input_x = 0
self.yanghao_comment_input_y = 0
self.yanghao_comment_send_x = 0
self.yanghao_comment_send_y = 0
self.yanghao_comment_close_x = 0
self.yanghao_comment_close_y = 0
self.yanghao_comment_texts = []
def _resolve_reservations_state_path(self: Any) -> None:
"""通过 path_config 解析预约状态文件路径,失败时退化到相对兜底。"""
try:
from douyin.core import path_config as _pc
self._reservations_state_path = _pc.get_reservations_path()
except Exception:
# 兜底:path_config 不可用时退到相对路径,与 douyin/core/state/ 一致
self._reservations_state_path = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "state", "reservations.json")
)
# 运行时直播间标题/位置映射表(清空后存)
self._room_pos_to_title_map = {}
def _cleanup_old_room_pos_map_files(self: Any) -> None:
"""每次启动时删除上次运行的导出文件,避免 GUI 显示过期内容。"""
try:
state_dir = os.path.dirname(self._reservations_state_path)
for filename in ("room_pos_map.json", "room_pos_map.csv", "room_pos_map.md"):
try:
p = os.path.join(state_dir, filename)
if os.path.exists(p):
os.remove(p)
except Exception:
pass
except Exception:
pass
File diff suppressed because it is too large. Load diff
+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",
]
+13 -4
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:
@@ -176,7 +184,8 @@ def find_executable(cmd: str) -> Optional[str]:
return first
else:
# 类 Unix:尝试 command -v 再 which
proc = subprocess.run(["/bin/sh", "-c", f"command -v {cmd} || which {cmd}"], capture_output=True, text=True)
import shlex
proc = subprocess.run(["/bin/sh", "-c", f"command -v {shlex.quote(cmd)} || which {shlex.quote(cmd)}"], capture_output=True, text=True)
if proc.returncode == 0 and proc.stdout:
first = proc.stdout.splitlines()[0].strip()
if first:
+113
View File
@@ -0,0 +1,113 @@
"""桌面自救共享逻辑
把 fudai_modules.run_once_basic_helpers 和 douyin.other.douyin_yanghao
中重复的"前台不在抖音 → 包名启动 → 失败兜底点击坐标"逻辑抽到这里。
"""
from __future__ import annotations
import time
from typing import Any, Callable, Optional
def is_douyin_foreground(top_pkg: str) -> bool:
"""判断给定的前台包名是否属于抖音相关包。"""
return bool(top_pkg) and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
def fallback_click_recovery(
analyser: Any,
log: Optional[Callable[[str], None]] = None,
) -> None:
"""旧的点击坐标自救:桌面图标 → 直播按钮 → 进入直播间×2。
保留作为 launch_package 失败时的兜底。所有坐标读 analyser 上的属性,
取不到时使用默认值(适配 1080x2400 的位置)。
"""
op = analyser.operation
device_id = analyser.device_id
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
try:
op.click(device_id, desktop_x, desktop_y)
except Exception:
# 退化为默认硬编码位置
try:
op.click(device_id, 153, 260)
except Exception:
pass
op.delay(2)
fallback_x = int(getattr(analyser, "yanghao_fallback_live_x", 540) or 540)
fallback_y = int(getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000)
try:
if log:
log(f"点击直播按钮 x={fallback_x} y={fallback_y}")
op.click(device_id, fallback_x, fallback_y)
op.delay(1.5)
except Exception:
pass
enter_x = int(getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540)
enter_y = int(getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200)
try:
if log:
log(f"点击进入直播间 x={enter_x} y={enter_y} 次数=2")
op.click(device_id, enter_x, enter_y)
op.delay(0.6)
op.click(device_id, enter_x, enter_y)
op.delay(2.0)
except Exception:
pass
def recover_to_douyin(
analyser: Any,
log: Optional[Callable[[str], None]] = None,
) -> bool:
"""统一的桌面自救入口。
流程:
1. 优先 op.launch_package(device_id, ""),按抖音常用包名顺序尝试
2. 包名启动失败或抛异常时,回退到点击坐标自救(fallback_click_recovery)
参数:
analyser: 提供 .operation / .device_id / 自救坐标属性的对象
log: 可选的日志回调(接受单字符串)
返回:
True 表示已尝试某种自救(不保证一定成功,但已执行动作);
False 仅在调用环境本身出现严重异常时返回。
"""
try:
op = analyser.operation
device_id = analyser.device_id
except Exception:
return False
launched_ok = False
used_pkg = ""
try:
launched_ok, used_pkg = op.launch_package(device_id, "")
except Exception as exc:
if log:
log(f"包名启动调用异常 {exc},回退点击坐标")
if launched_ok:
if log:
log(f"包名启动抖音成功 pkg={used_pkg}")
try:
op.delay(2.5)
except Exception:
time.sleep(2.5)
return True
# 兜底:保留旧的点击坐标自救
if log:
log("包名启动失败,回退点击桌面图标 + 备用坐标")
fallback_click_recovery(analyser, log=log)
return True
File diff suppressed because it is too large. Load diff
@@ -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 <= 3600:
return total1
if total2 is not None and total2 <= 3600:
return total2
# 若一个明显异常而另一个更合理(<=3600),交换
if total1 is not None and total2 is not None:
if total1 > 3600 and total2 <= 3600:
return total2
if total2 > 3600 and total1 <= 3600:
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)
# 超过 60 分钟视为 OCR 误识别,按 59 分 50 秒处理
if total_seconds > 3600:
total_seconds = 3590
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,74 @@
"""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()
try:
num = int(num)
except ValueError:
print("请输入有效数字:")
return False
while not num in dictdevice.keys():
print("输入不正确,请重新输入:")
num = input()
try:
num = int(num)
except ValueError:
print("请输入有效数字:")
return False
return dictdevice[num]
@@ -0,0 +1,276 @@
"""douyin/core/underlying_operations_pkg/image_ops - cut_pic 图片裁剪管道
把 underlying_operations.cut_pic 整段抽出来。流程:
- 默认分支(target=""):从项目根 pic/screenshot.png 读图,裁出 cut.png 或 ocr/<name>.png
- 命名分支(target="xxx"):从 pic/<target>/screenshot.png 读图,裁出 pic/<target>/<name>.png
- 重试 3 次(截图缺失/文件太小/PIL 损坏)
- 写入坐标缓存供 analyse_pic_word 调试图像用
- 可选保存 cut_pic 调试图(SAVE_CUT_PIC_DEBUG_IMAGES=1)
入口:cut_pic(self, left_up, right_down, target, name) -> bool
self 必须提供:_find_pic_path / _ocr_coords_lock / _ocr_coords_cache
"""
from __future__ import annotations
import logging
import os
import time as time_module
from typing import Any
from PIL import Image
def _ensure_parent_dir(path: str) -> None:
"""确保路径的父目录存在。"""
try:
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
except Exception:
pass
def _validate_coords(
left_up: tuple, right_down: tuple, image_size: tuple
) -> bool:
"""检查裁剪坐标在图片范围内且非空。"""
left, top = left_up
right, bottom = right_down
width, height = image_size
return not (
left < 0 or top < 0
or right > width or bottom > height
or left >= right or top >= bottom
)
def _save_cut_debug_images(self: Any, cropped_img, pic, name: str, source_label: str, left: int, top: int, right: int, bottom: int) -> None:
"""根据环境变量决定是否保存 cut_pic 调试图。"""
try:
save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
if not save_debug:
try:
save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
except Exception:
pass
if not save_debug:
return
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(完整截图+区域标注)
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": source_label,
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def cut_pic(
self: Any,
left_up=(0, 63),
right_down=(1080, 1620),
target: str = "",
name: str = "",
) -> bool:
"""裁剪图片,获取需要的区域小图片方便识别。"""
from douyin.core.underlying_operations import _uo_log
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
if target == "" or target is False:
from douyin.core import path_config
path = path_config.get_pic_dir()
pic1_path = path_config.get_screenshot_path()
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path + "/cut.png"
else:
cut_pic_path = self._find_pic_path(name, for_reading=False)
if not _validate_coords(left_up, right_down, pic.size):
raise ValueError(
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
)
left, top = left_up
right, bottom = right_down
cropped_img = pic.crop((left, top, right, bottom))
assert cut_pic_path is not None
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
# 存储坐标信息供 analyse_pic_word 使用
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
try:
_save_cut_debug_images(
self, cropped_img, pic, name,
"screenshot.png", left, top, right, bottom,
)
finally:
pic.close()
return True
else:
from douyin.core import path_config
path_target = os.path.join(path_config.get_pic_dir(), target)
pic1_path = os.path.join(path_target, "screenshot.png")
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path_target + "/cut.png"
else:
cut_pic_path = path_target + "/" + name + ".png"
try:
if not _validate_coords(left_up, right_down, pic.size):
error_msg = (
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, "
f"image_size={pic.size}"
)
if attempt == max_retries - 1:
_uo_log(f"[错误] {error_msg}")
return False
continue
left, top = left_up
right, bottom = right_down
assert cut_pic_path is not None
cropped_img = pic.crop((left, top, right, bottom))
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 命名分支总是保存 cut_pic 调试图(与原版行为一致 — 没有开关检查)
try:
from douyin.handlers import douyin_screenshot_manager
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": target + "/screenshot.png",
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
return True
finally:
pic.close()
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
if attempt == max_retries - 1:
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
_uo_log(error_msg)
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
return False
continue
return False
@@ -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
Loaded 100 of 480 files, more files were not shown because too many files have changed in this diff. Show more