diff --git a/bin/run_cli.py b/bin/run_cli.py index c7abff3..62b620b 100644 --- a/bin/run_cli.py +++ b/bin/run_cli.py @@ -328,6 +328,12 @@ def parse_args(argv: list[str]) -> argparse.Namespace: default=None, help="仅在 --yanghao-only 时有效:覆盖推荐页养号停留秒数", ) + p.add_argument( + "--reenter-live-entry-mode", + choices=["follow_list", "screen_center"], + default=None, + help="重新进入直播间点击模式:follow_list=关注列表坐标,screen_center=屏幕中心坐标", + ) return p.parse_args(argv) @@ -609,6 +615,14 @@ def main(argv: list[str]) -> int: except Exception: pass + if getattr(args, "reenter_live_entry_mode", None) is not None: + try: + analyser.reenter_live_entry_mode = str( + args.reenter_live_entry_mode or "follow_list" + ).strip().lower() + except Exception: + analyser.reenter_live_entry_mode = "follow_list" + device_id = args.device_id.strip() if args.device_id else "" if not device_id: device_id = analyser.operation.select_device() diff --git a/config/config.json b/config/config.json index 94433b3..66b4ea9 100644 --- a/config/config.json +++ b/config/config.json @@ -9,6 +9,7 @@ "reset_after_swipes_enabled": true, "reset_after_swipes": 20, "reset_after_swipes_action": "swipe", + "reenter_live_entry_mode": "follow_list", "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, @@ -38,8 +39,29 @@ "fudai_detail_verified_wait_seconds": 0.2, "fudai_detail_retry_delay_seconds": 0.5, "fudai_detail_save_debug_images": true, - "fudai_disable_content_recognition": true, - "fudai_disable_task_recognition": true, + "fudai_detail_ui_mode": "auto", + "fudai_detail_ocr_content_enabled": true, + "fudai_detail_ocr_value_enabled": true, + "fudai_detail_ocr_countdown_enabled": true, + "fudai_detail_ocr_task_enabled": true, + "fudai_detail_ocr_task_count_enabled": true, + "fudai_detail_ocr_button_enabled": true, + "fudai_detail_ocr_participants_enabled": false, + "fudai_detail_ocr_live_title_enabled": true, + "pixel_detect_fudai_icon_enabled": true, + "pixel_detect_coupon_popup_enabled": true, + "pixel_detect_shopping_redpacket_enabled": false, + "pixel_detect_lottery_result_enabled": true, + "pixel_detect_attend_button_enabled": true, + "pixel_detect_fansclub_join_enabled": true, + "pixel_detect_fudai_detail_enabled": true, + "pixel_detect_live_room_enabled": true, + "ocr_lottery_result_enabled": true, + "ocr_coupon_popup_enabled": true, + "ocr_shopping_redpacket_enabled": false, + "ocr_stage_page_enabled": true, + "fudai_disable_content_recognition": false, + "fudai_disable_task_recognition": false, "yanghao_recommend_duration_seconds": 180, "yanghao_recommend_interval_seconds": 600, "yanghao_like_prob": 0.1, @@ -199,7 +221,7 @@ "max_files": 1000, "auto_cleanup": true, "async_save": false, - "log_on_complete": true + "log_on_complete": false }, "fudai_detail_template_threshold": 0.52, "switch_room_wait_after_stage_diag_seconds": 7.5, @@ -234,8 +256,8 @@ "log_unified_enabled": true, "log_unified_path": "logs/unified.log", "last_wifi_target": { - "target": "192.168.10.107:39051", + "target": "192.168.10.105:39021", "model": "PEPM00", - "saved_at": 1780284199 + "saved_at": 1780417101 } } diff --git a/docs/agent_handoffs/2026-06-02_fudai_detail_ocr_v2_handoff.md b/docs/agent_handoffs/2026-06-02_fudai_detail_ocr_v2_handoff.md new file mode 100644 index 0000000..37063db --- /dev/null +++ b/docs/agent_handoffs/2026-06-02_fudai_detail_ocr_v2_handoff.md @@ -0,0 +1,18 @@ +# 福袋详情页 OCR 2.0 handoff + +1. 目标:按 1080x2400 新福袋详情页更新 OCR 区域,保留 legacy,并支持 `auto/legacy/v2_0`。 +2. 已新增字段开关:内容、价值、倒计时、任务、任务数量、按钮默认开;人数、直播间标题默认关。 +3. 旧开关 `fudai_disable_content_recognition` / `fudai_disable_task_recognition` 仅作新开关缺省兜底。 +4. 2.0 双任务 profile 在 `douyin/fudai/core/coords.py` 的 `DETAIL_UI_V2_0`。 +5. 2.0 单任务下移 profile 在 `DETAIL_UI_V2_0_ONE_TASK`,按当前 ADB 截图微调。 +6. 当前单任务标注图:`logs/fudai_detail_v2_regions_onetask_precise3.png`。 +7. 当前 ADB 原图:`logs/fudai_detail_v2_current_20260602_234012.png`。 +8. 单任务任务框已缩到左侧任务文案,避免混入右侧“未达成”。 +9. 任务数量优先 OCR `(0/1)` / `(1/2)`,失败回退 legacy 像素检测。 +10. debug 截图 extra_info 已包含 `ui_version`、`ocr_enabled`、`region_name` 等信息。 +11. 桌面 GUI 与 Web GUI 已加入 UI 版本和所有 OCR 字段开关。 +12. “参考价值”按实际价值解析,继续写 `prize_value_yuan`。 +13. 验证日志:`logs/pytest_fudai_detail_v2_final4.log` PASS。 +14. 验证日志:`logs/py_compile_fudai_detail_v2_final4.log` PASS。 +15. 验证日志:`logs/web_gui_config_sync_fudai_v2_final4.log` PASS。 +16. 验证日志:`logs/git_diff_check_fudai_v2_final4.log` PASS。 diff --git a/docs/agent_handoffs/2026-06-02_full_code_review_progress.md b/docs/agent_handoffs/2026-06-02_full_code_review_progress.md new file mode 100644 index 0000000..fef09dc --- /dev/null +++ b/docs/agent_handoffs/2026-06-02_full_code_review_progress.md @@ -0,0 +1,239 @@ +# 2026-06-02 全量代码审查进展 + +目标:对 `C:\Users\12742\Desktop\douyin_guaji-main` 做仓库级 code review,并对确认的高风险功能缺陷直接修复。 + +## 已确认并已修复 + +1. `gui/web_gui.py` + - `force_stop()` / `atexit` 会误杀同仓库其他 `run_cli.py` 进程。 + - 已改为只清理当前 Web GUI 自己启动过的 PID。 + +2. `gui/webgui_launcher.py` + - `stop_old_processes()` 会按 `*web_gui.py*` 全局杀进程。 + - 已改为限定当前仓库路径。 + +3. `gui/gui_core_pkg/config.py` + - 配置写入是浅 `update` + 直接覆盖,存在并发丢字段和半写风险。 + - 已改为深合并 + 进程内锁 + `.tmp` + `os.replace()`。 + +4. `operations/screenshot_service.py` + - `start()` 在持锁状态下调用 `stop()`,设备切换时可能死锁。 + - 已改为先释放锁再等待旧线程退出。 + +5. `gui/gui_core_pkg/wifi_adb.py` + - `disconnect_wifi_adb("ip:port")` 会拼成 `ip:port:5555`。 + - 已修复为支持直接 `ip:port` 输入。 + +6. `gui/web_gui_pkg/routes.py` + - `/api/*` GET/POST、`/pic/*` 以及静态页都可被非本地来源访问。 + - 已全部限制为 local-only。 + +7. `douyin/core/douyin_fudai.py` + - `_maybe_run_yanghao_during_run()` 注释说触发推荐页养号,实际只调用 `_yanghao_wait()`。 + - 已改为真正调用 `_yanghao_recommend_flow()`。 + +8. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py` + - `read_once_callback` 参数未被真正使用。 + - `status="ok"` 但 tuple 无效时会走未定义局部变量路径。 + - `task_count_zero` 补救逻辑与 `read_once()` 返回的 `not_in_fudai_detail` 不一致。 + - 已修复以上三点。 + +9. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py` + - 停止后台截图服务后未恢复。 + - 复用阶段截图时不验证可读性,坏图会直接落到 `screenshot_failed`。 + - 已补恢复逻辑和坏图自动 fresh screenshot。 + +10. `douyin/core/fudai_modules/handle_detail_*` + - first-open / second-open / 错误分支存在多处状态残留: + - first-open 可能误标 second-open + - second-open 重读终止状态后不清 flag + - second-open 重读失败后仍卡 second-open + - task_count_zero / not_in_fudai_detail 被消费后不清 `_last_fudai_detail_status/_extra` + - coupon/watch/validation_failed 被消费后不清 `_last_fudai_detail_status` + - 以上已逐项修复。 + +11. `douyin/detection/detection_pkg/finder.py` + - 命中后不写回 `last_fudai_x`。 + - 非 1080 宽屏下历史坐标比较混用坐标系。 + - `fudai_icon_max_wait_seconds=0` 时会 0 次检测直接退出。 + - 已修复。 + +12. `douyin/detection/detection_pkg/finder_template_match.py` + - 模板兜底命中后不写回 `last_fudai_x`,与其他两条检测路径不一致。 + - 已修复。 + +13. 导入链缺依赖即崩 + - 已逐步把以下模块的顶层 `PIL` 依赖改成按需导入: + - `operations.__init__` + - `operations.screenshot_service` + - `douyin.detection.pixel._common` + - `douyin.detection.pixel.buttons` + - `douyin.detection.pixel.popups` + - `douyin.detection.pixel.stage` + - `douyin.detection.detection_pkg.detail` + - `douyin.detection.detection_pkg.finder` + - `douyin.fudai.core.fudai_debug_utils` + - `douyin.fudai.core.fudai_detail_coupon_detection` + - `douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once` + - `douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries` + - `douyin.core.douyin_fudai` + - `douyin.core.underlying_operations` + - 当前机器上已实证: + - `import operations`:PASS + - `import operations.screenshot_service`:PASS + - `import douyin.detection.douyin_detection`:PASS + - `import douyin.core.douyin_fudai`:PASS + +14. `douyin/handlers/douyin_screenshot_handler.py` + - `save_step_screenshot()` 用 `dirname(__file__)` 锚到错误 `pic` 目录。 + - 已改为统一使用 `path_config.get_pic_dir()`。 + +15. `douyin/core/fudai_modules/handle_detail_*` + - `check_invalid_detail_fallback()` 早退时不清 `_fudai_detail_first_read/_last_fudai_detail_tuple`。 + - `handle_first_open_branch()` 的早退路径不清 first-open/缓存状态。 + - `handle_second_open_branch()` 重读无效详情时不清 second-open 标志。 + - 已修复。 + +16. `douyin/core/fudai_modules/handle_detail_helpers.py` + - 终止类状态(coupon/watch/validation_failed)消费后不清 `_last_fudai_detail_status`。 + - task_count_zero / not_in_fudai_detail 错误被消费后不清 `_last_fudai_detail_status/_last_fudai_detail_extra`。 + - 已修复。 + +17. `douyin/detection/detection_pkg/finder.py` + - `fudai_icon_max_wait_seconds=0` 时会 0 次检测直接退出。 + - 旧实现还会把显式配置的 `0` 通过 `or 5.0` 偷偷退回默认值。 + - 已修复为保留显式 `0`,并至少执行一轮即时检测。 + +18. `douyin/fudai/core/fudai_detail_coupon_detection.py` + - 顶层 `PIL` 依赖会继续阻塞 `douyin_fudai` 导入链。 + - 已改为按需导入。 + +19. `douyin/detection/pixel/*` + - `popups.py` / `buttons.py` / `stage.py` / `_common.py` 顶层 `PIL` 依赖会阻塞 detection 导入链。 + - 已改为按需导入。 + +20. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py` + - 第二次打开重读后若仍无有效 detail,会继续保留 second-open 状态。 + - 已修复。 + +21. `douyin/core/fudai_modules/handle_detail_first_open.py` + - `branch_result == "return"` / 验证失败早退时,`_fudai_detail_first_read/_last_fudai_detail_tuple` 不清理。 + - 已修复。 + +22. `douyin/core/fudai_modules/handle_detail_helpers.py` + - `check_invalid_detail_fallback()` 早退时不清 `_fudai_detail_first_read/_last_fudai_detail_tuple`。 + - 已修复。 + +23. `douyin/detection/detection_pkg/finder_template_match.py` + - 模板兜底命中后只写 `last_find_fudai_time`,不写 `last_fudai_x`。 + - 已修复。 + +24. `operations/screenshot_operations.py` / `douyin/core/underlying_operations_pkg/screenshot_direct.py` + - `target_pic` fallback 路径仍相对模块目录拼接。 + - 已统一锚到 `/target_pic`。 + +25. `operations/screenshot_operations.py` + - `_find_pic_path(..., for_reading=True)` 会把 `operations/` 当前目录作为图片搜索路径,可能误命中同名文件。 + - 已修复为只搜索项目根 `pic/` 与 `target_pic/`。 + +26. `douyin/detection/pixel/stage.py` + - 并行阶段检测里实际调用了 popup/button helper,但文件头没导入,对应检测项运行时会静默掉成 False。 + - 已补齐导入。 + +27. `douyin/core/douyin_flow_control_pkg/stage_handler.py` + - 直接调用 `find_and_open_fudai_detail()` 却未导入。 + - 已修复。 + +28. `douyin/core/underlying_operations_pkg/countdown.py` + - 使用 `Optional` 但未导入。 + - 已修复。 + +29. `douyin/core/fudai_modules/handle_detail_filter.py` + - 高价值预约分支里 `basic_join_decision()` 失败也会被当成“已记录预约并完成”。 + - 已修复为只有真成功才消费该分支。 + +30. `douyin/reservation/reservation_logic/add.py` / `attend_window.py` + - 日志里的旧静态检查结果显示两处反复引用 `_RESERVATION_ERROR_UTILS_AVAILABLE`,但模块本身漏导入,属于确定性的 `NameError`/静态错误来源。 + - 已补齐从 `reservation_logic._common` 的导入。 + +31. `gui/web_gui_pkg/request_parsing.py` + - `send_json()` 在客户端主动断开连接时会把正常断链打成 `ConnectionAbortedError` traceback,已在 `logs/web_gui_runtime.err.log` 中出现。 + - 已改为对 `BrokenPipeError` / `ConnectionAbortedError` / `ConnectionResetError` 静默收口,不再把正常断链记成服务端异常。 + +32. `douyin/logging/douyin_logging_pkg/monitor.py` + - `logs` 中出现 `cannot import name 'start_log_monitor' from partially initialized module ... monitor`,根因是 `monitor.py` 顶层反向导入 `config.py`,同时模块导入末尾又主动调用 `configure_logging()`,形成循环导入。 + - 已去掉 `monitor -> config` 的顶层依赖,以及 `monitor` 模块导入时的自动配置副作用,当前 `monitor/config/douyin_logging` 导入链已可直接通过。 + +33. `douyin/logging/action_logger.py` + - `ActionLogger.log_operation()` 之前只认 `elapsed`,会把调用方已经传进来的 `elapsed_seconds` 吞掉并重写成 `0.0`,导致 `actions.log` 大量出现假的 `耗时=0.00ms`。 + - 已改为同时正确接受 `elapsed` / `elapsed_seconds`,只在确实有值时才写入耗时字段,日志耗时保真恢复正常。 + +34. `douyin/fudai/douyin_fudai_contain_impl.py` + - 重 OCR 分支里 `picked_heavy` 只在部分条件下赋值,后续却无条件读取,存在继续污染运行日志的局部变量边界风险。 + - 已补默认初始化,避免该分支再出现这类局部变量异常。 + +35. `douyin/logging/douyin_logging_wrapper_pkg/simple.py` + - 行为日志桥接层之前只识别 `elapsed_ms` / `total_ms`,但 finder 一类日志大量传的是 `total_elapsed_ms`,导致这些本来已有总耗时的操作仍被桥接成缺失耗时或误导性 `0.00ms`。 + - 已补 `total_elapsed_ms -> elapsed_seconds` 的统一映射,后续 `actions.log` 能更真实反映 finder 总耗时。 + +36. `douyin/logging/douyin_logging_wrapper_pkg/detailed.py` + - detailed 模式下的行为日志桥接也存在同样问题:只识别 `elapsed_ms` / `total_ms`,未覆盖 `total_elapsed_ms`,会让不同日志模式下的耗时记录不一致。 + - 已与 simple 模式对齐,补上 `total_elapsed_ms` 识别。 + +37. `douyin/reservation/reservation_logic/attend_window.py` + - 运行时分支里仍残留一组高风险未定义符号:`cleanup_expired_reservations` 未导入,以及 `target_room_title / target_room_title_raw / target_content / target_value` 在成功回退分支会被直接使用。 + - 已补齐导入与目标预约字段的本地初始化,避免这些分支在运行时直接 `NameError`。 + +38. `douyin/fudai/core/fudai_attend.py` + - `attend_choujiang()` 之前会在 5 秒有效期内无条件复用 `_fudai_button_status/_fudai_button_text`,没有校验缓存是否来自当前直播间,存在把上一个房间按钮状态误用到当前房间的风险。 + - 已改为:5 秒内复用也必须满足 `current_room_pos == _fudai_button_room_pos`(或其中一方缺失),避免跨房间误复用按钮 OCR 缓存。 + +39. `douyin/reservation/douyin_reservation_handler_pkg/seek_room.py` + - 回退成功后会直接调用 `_dump_room_pos_map_to_state(analyser)`,但文件头之前没导入这个 helper,属于命中成功回退分支就可能触发的运行时 `NameError`。 + - 已补从 `dump_state.py` 的显式导入,并加了最小导入回归验证。 + +40. `douyin/fudai/core/fudai_attend.py` + - 当 `room_pos` 不命中时,`attend_choujiang()` 之前只会从当前 `room_pos` 的映射表项回收 `button_text`,容易在房间位置漂移时直接掉到 `no_parallel_ocr_result`。 + - 已补按 `current_room_title/current_room_title_raw` 匹配映射表标题的兜底回收路径,减少按钮 OCR 缓存因为位置漂移而失效。 + +41. `douyin/fudai/core/fudai_attend.py` + - `button_text_raw` 作为全局缓存之前会被直接信任,但它本身没有房间归属校验,存在把上一个直播间的裸按钮文本误用到当前直播间的风险。 + - 已改为:只有确认 `_fudai_button_room_pos` 与当前 `room_pos` 同房间(或任一方缺失)时,才允许直接信任 `button_text_raw`。 + +42. `douyin/fudai/core/fudai_attend.py` + - “点击参与抽奖”分支里那两段调试 JSON 写盘之前完全裸奔,遇到不可 JSON 序列化对象时会直接把主流程打断。 + - 已改为真正的 best-effort:写盘整体包裹在 `try/except` 中,并对关键字段做基础类型收敛,`json.dumps(..., default=str)` 不再让调试写盘反咬业务路径。 + +43. `douyin/fudai/douyin_fudai_contain_impl.py` + - 主并行 OCR 写按钮状态时会记录 `_fudai_button_room_pos`,但 fallback 并行 OCR 之前没传 `record_room_pos=True`,导致备用 OCR 成功后仍可能缺失房间归属信息,进而削弱后续跨房间缓存保护。 + - 已补齐 fallback 路径的 `record_room_pos=True`,并加了最小回归验证。 + +44. `gui/components/wifi_adb_dialog.py` + - `toggle_maximize` 之前被错误定义在 `auto_connect_wifi()` 内部,但“放大/恢复”按钮是在外层直接绑定 `command=toggle_maximize`,属于打开对话框就可能命中的真作用域错误。 + - 已把 `toggle_maximize` 提升到 `open_wifi_adb_dialog()` 同级作用域,并补了最小 smoke test 证明按钮命令可正常绑定。 + +## 仍建议继续深挖 + +1. `douyin/detection/detection_pkg/finder.py` + - 坏截图/半写图补拍恢复的一致性。 + - 模板兜底与像素路径在日志、计时和状态清理上的一致性。 + +2. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py` + - 运行期截图/OCR异常回退的进一步收口。 + +## 仍未修复但已确认的风险 + +1. `config/config.json` + - 仍混有明显的本机运行态/本地偏好数据(如 `last_wifi_target`),不适合作为稳定仓库默认值。 + - 因文件属于当前工作树活跃修改内容,未直接重写,避免覆盖用户现场状态。 + +2. `pyright` + - 仓库仍存在一批历史静态类型错误,当前没有被系统性清理。 + +3. `pytest` + - 当前环境缺 `pytest`,无法在本会话中把新增回归测试正式跑绿;目前主要依赖语法检查与轻量行为探针。 + +## 当前验证约束 + +1. 当前环境缺 `pytest`,不能直接在此会话里把新增测试跑绿。 +2. 当前环境缺 `PIL` / OCR 相关依赖,但这反而帮助暴露了导入链的真实缺陷;多处“缺依赖即崩”的问题已被修复并通过轻量 import 探针验证。 diff --git a/douyin/core/douyin_flow_control_pkg/stage_handler.py b/douyin/core/douyin_flow_control_pkg/stage_handler.py index 2787e4b..de87623 100644 --- a/douyin/core/douyin_flow_control_pkg/stage_handler.py +++ b/douyin/core/douyin_flow_control_pkg/stage_handler.py @@ -8,6 +8,8 @@ from __future__ import annotations import time from typing import Any +from .find_open import find_and_open_fudai_detail + def handle_stage_after_diagnosis( analyser: Any, diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index b6fb101..836dc69 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -16,10 +16,6 @@ import time import subprocess import logging -# Optional heavy dependencies used in image processing; Pylance may not have them in analysis env -from PIL import Image # type: ignore[import] -import numpy as np # type: ignore[import] - from douyin.core.underlying_operations import underlying_operations from douyin.stage import douyin_stage @@ -315,7 +311,7 @@ class fudai_analyse: self._last_yanghao_ts = now seconds = int(getattr(self, "yanghao_recommend_duration_seconds", 60) or 60) try: - self._yanghao_wait(seconds) + self._yanghao_recommend_flow(seconds) except Exception: pass except Exception: diff --git a/douyin/core/fudai_modules/handle_detail_filter.py b/douyin/core/fudai_modules/handle_detail_filter.py index 276f2df..304c96e 100644 --- a/douyin/core/fudai_modules/handle_detail_filter.py +++ b/douyin/core/fudai_modules/handle_detail_filter.py @@ -104,13 +104,17 @@ def try_high_value_reservation( ) except Exception: pass + reservation_recorded = False try: - douyin_fudai_core.basic_join_decision(self, detail) + reservation_recorded = bool(douyin_fudai_core.basic_join_decision(self, detail)) except Exception as e: try: self._log_kv("流程", "_handle_in_fudai_detail:记录预约时出错", error=str(e)) except Exception: pass + reservation_recorded = False + if not reservation_recorded: + return "still_skip" elapsed = time.time() - start_time self._log_kv("流程", "_handle_in_fudai_detail完成(记录预约)", elapsed_seconds=round(elapsed, 2)) return "return" diff --git a/douyin/core/fudai_modules/handle_detail_first_open.py b/douyin/core/fudai_modules/handle_detail_first_open.py index 49878c9..04ef244 100644 --- a/douyin/core/fudai_modules/handle_detail_first_open.py +++ b/douyin/core/fudai_modules/handle_detail_first_open.py @@ -32,11 +32,18 @@ def handle_first_open_branch(self: "fudai_analyse", start_time: float) -> bool: branch_result = check_skip_and_handle(self, detail, step2_start, start_time) if branch_result == "return": + try: + self._fudai_detail_first_read = False + self._last_fudai_detail_tuple = None + except Exception: + pass return True try: - self._last_fudai_detail_tuple = detail - self._fudai_detail_first_read = True + current_status = str(getattr(self, "_last_fudai_detail_status", "") or "") + if current_status not in {"coupon_popup", "watch_task", "validation_failed", "error"}: + self._last_fudai_detail_tuple = detail + self._fudai_detail_first_read = True if detail and isinstance(detail, tuple) and len(detail) >= 1: self._current_fudai_content = str(detail[0] if detail[0] else "") self._log_kv( @@ -92,6 +99,11 @@ def validate_first_open_detail( douyin_fudai_detail.close_fudai_detail(self) except Exception: pass + try: + self._fudai_detail_first_read = False + self._last_fudai_detail_tuple = None + except Exception: + pass step2_elapsed = (time.time() - step2_start) * 1000 self._log_kv("详情处理", "步骤2[读取福袋详情]-完成", 总耗时毫秒=step2_elapsed) @@ -114,4 +126,3 @@ def _clear_task_count_flag(self: "fudai_analyse") -> None: pass except Exception: pass - diff --git a/douyin/core/fudai_modules/handle_detail_helpers.py b/douyin/core/fudai_modules/handle_detail_helpers.py index f77ce54..65200df 100644 --- a/douyin/core/fudai_modules/handle_detail_helpers.py +++ b/douyin/core/fudai_modules/handle_detail_helpers.py @@ -128,6 +128,10 @@ def check_last_status_branch( except Exception: pass _clear_task_count_flag(self) + try: + self._last_fudai_detail_status = "" + except Exception: + pass elapsed = time.time() - start_time self._log_kv( "流程", @@ -145,6 +149,10 @@ def check_last_status_branch( except Exception: pass _clear_task_count_flag(self) + try: + self._last_fudai_detail_status = "" + except Exception: + pass elapsed = time.time() - start_time self._log_kv( "流程", @@ -181,6 +189,10 @@ def check_last_status_branch( except Exception: pass _clear_task_count_flag(self) + try: + self._last_fudai_detail_status = "" + except Exception: + pass elapsed = time.time() - start_time self._log_kv( "流程", @@ -228,7 +240,7 @@ def _handle_error_status(self: "fudai_analyse", start_time: float) -> bool: last_extra = getattr(self, "_last_fudai_detail_extra", {}) if not ( isinstance(last_extra, dict) - and last_extra.get("reason") == "task_count_zero" + and last_extra.get("reason") in {"task_count_zero", "not_in_fudai_detail"} ): return False @@ -253,6 +265,11 @@ def _handle_error_status(self: "fudai_analyse", start_time: float) -> bool: except Exception: pass _clear_task_count_flag(self) + try: + self._last_fudai_detail_status = "" + self._last_fudai_detail_extra = {} + except Exception: + pass elapsed = time.time() - start_time self._log_kv( "流程", @@ -297,6 +314,11 @@ def _handle_error_status(self: "fudai_analyse", start_time: float) -> bool: except Exception: pass _clear_task_count_flag(self) + try: + self._last_fudai_detail_status = "" + self._last_fudai_detail_extra = {} + except Exception: + pass elapsed = time.time() - start_time self._log_kv( @@ -370,6 +392,11 @@ def check_invalid_detail_fallback( pass except Exception: pass + try: + self._fudai_detail_first_read = False + self._last_fudai_detail_tuple = None + except Exception: + pass elapsed = time.time() - start_time self._log_kv( diff --git a/douyin/core/fudai_modules/handle_detail_second_open.py b/douyin/core/fudai_modules/handle_detail_second_open.py index 3c973c6..33f421e 100644 --- a/douyin/core/fudai_modules/handle_detail_second_open.py +++ b/douyin/core/fudai_modules/handle_detail_second_open.py @@ -134,9 +134,22 @@ def handle_second_open_branch( ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, ) if detail and isinstance(detail, tuple) and len(detail) >= 6: - self._last_fudai_detail_tuple = detail + current_status = str(getattr(self, "_last_fudai_detail_status", "") or "") + if current_status not in {"coupon_popup", "watch_task", "validation_failed", "error"}: + self._last_fudai_detail_tuple = detail detail_t: Tuple[Any, ...] = tuple(detail) self._current_fudai_content = detail_t[0] if len(detail_t) > 0 else "" + else: + try: + self._fudai_detail_first_read = False + except Exception: + pass + try: + current_status = str(getattr(self, "_last_fudai_detail_status", "") or "") + if current_status in {"coupon_popup", "watch_task", "validation_failed", "error"}: + self._fudai_detail_first_read = False + except Exception: + pass return False try: @@ -210,4 +223,3 @@ def _clear_task_count_flag(self: "fudai_analyse") -> None: pass except Exception: pass - diff --git a/douyin/core/fudai_modules/init_helpers.py b/douyin/core/fudai_modules/init_helpers.py index 17d650f..ae70108 100644 --- a/douyin/core/fudai_modules/init_helpers.py +++ b/douyin/core/fudai_modules/init_helpers.py @@ -70,6 +70,27 @@ def apply_fudai_defaults(self: Any) -> None: self.live_room_match_threshold = 0.8 self.fudai_template_match_enabled = False self.fudai_template_match_threshold = 0.7 + self.fudai_detail_ui_mode = "auto" + self.fudai_detail_ocr_content_enabled = True + self.fudai_detail_ocr_value_enabled = True + self.fudai_detail_ocr_countdown_enabled = True + self.fudai_detail_ocr_task_enabled = True + self.fudai_detail_ocr_task_count_enabled = True + self.fudai_detail_ocr_button_enabled = True + self.fudai_detail_ocr_participants_enabled = False + self.fudai_detail_ocr_live_title_enabled = True + self.pixel_detect_fudai_icon_enabled = True + self.pixel_detect_coupon_popup_enabled = True + self.pixel_detect_shopping_redpacket_enabled = False + self.pixel_detect_lottery_result_enabled = True + self.pixel_detect_attend_button_enabled = True + self.pixel_detect_fansclub_join_enabled = True + self.pixel_detect_fudai_detail_enabled = True + self.pixel_detect_live_room_enabled = True + self.ocr_lottery_result_enabled = True + self.ocr_coupon_popup_enabled = True + self.ocr_shopping_redpacket_enabled = False + self.ocr_stage_page_enabled = True # 高价值福袋 / 预约相关配置 self.high_value_fudai_enabled = False @@ -108,6 +129,10 @@ def apply_fudai_defaults(self: Any) -> None: self.yanghao_fallback_live_y = 2000 self.yanghao_fallback_enter_live_x = 540 self.yanghao_fallback_enter_live_y = 1200 + # 重新进入直播间点击模式: + # - follow_list: 使用关注列表入口坐标 + # - screen_center: 使用屏幕中心坐标 + self.reenter_live_entry_mode = "follow_list" # 推荐页养号默认配置 _apply_yanghao_defaults(self) diff --git a/douyin/core/fudai_modules/run_once_basic_helpers.py b/douyin/core/fudai_modules/run_once_basic_helpers.py index d7fd625..9b3dae9 100644 --- a/douyin/core/fudai_modules/run_once_basic_helpers.py +++ b/douyin/core/fudai_modules/run_once_basic_helpers.py @@ -450,9 +450,19 @@ def dispatch_stage_branch( self._log_kv("流程", "点击进入直播页", x=live_tab_x, y=live_tab_y) self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY) - # 点击进入直播间的位置 (103, 382),连点两次 - enter_live_x = int(103 * self.resolution_ratio_x // 1080) - enter_live_y = int(382 * self.resolution_ratio_y // 2400) + # 点击进入直播间位置(支持模式切换:关注列表坐标/屏幕中心),连点两次 + try: + from douyin.handlers import douyin_swipe_handler + + enter_live_x, enter_live_y, entry_mode = ( + douyin_swipe_handler.SwipeHandler.resolve_reenter_live_click_point( + self + ) + ) + except Exception: + enter_live_x = int(103 * self.resolution_ratio_x // 1080) + enter_live_y = int(382 * self.resolution_ratio_y // 2400) + entry_mode = "follow_list" self.operation.click(self.device_id, enter_live_x, enter_live_y) self.operation.delay(self.ENTER_LIVE_CLICK_DELAY) try: @@ -464,10 +474,11 @@ def dispatch_stage_branch( self.operation.click(self.device_id, enter_live_x, enter_live_y) self._log_kv( "流程", - "点击进入直播间位置", + "点击进入直播间位置(entry_mode={})".format(entry_mode), x=enter_live_x, y=enter_live_y, 次数=2, + entry_mode=entry_mode, ) try: self.operation.delay( diff --git a/douyin/core/path_config.py b/douyin/core/path_config.py index 2dfc4f9..c8fe3a7 100644 --- a/douyin/core/path_config.py +++ b/douyin/core/path_config.py @@ -89,7 +89,7 @@ def _read_runtime_config() -> dict: def get_web_gui_host() -> str: """返回 Web GUI 监听 host(环境变量优先,其次 config.json,最后默认值)。""" - host = (os.environ.get("WEB_GUI_HOST") or os.environ.get("HOST") or "").strip() + host = (os.environ.get("WEB_GUI_HOST") or "").strip() if host: return host cfg = _read_runtime_config() @@ -279,7 +279,15 @@ def find_executable(cmd: str) -> Optional[str]: try: if sys.platform.startswith("win"): # 使用 where 查找(Windows) - proc = subprocess.run(["where", cmd], capture_output=True, text=True) + # 注意:where 在未命中时会往 stderr 打印 + # “INFO: Could not find files for the given pattern(s)”。 + # 这里仅以 returncode/stdout 判断,不需要把该噪声透传到上层日志。 + proc = subprocess.run( + ["where", cmd], + capture_output=True, + text=True, + stderr=subprocess.DEVNULL, + ) if proc.returncode == 0 and proc.stdout: first = proc.stdout.splitlines()[0].strip() if first: diff --git a/douyin/core/underlying_operations.py b/douyin/core/underlying_operations.py index 42f3b27..99ee84f 100644 --- a/douyin/core/underlying_operations.py +++ b/douyin/core/underlying_operations.py @@ -20,9 +20,6 @@ import time as time_module # alias for existing code that uses `time` name time = time_module -from PIL import Image, ImageFilter # type: ignore[import] -from PIL import UnidentifiedImageError # type: ignore[import] -import numpy as np # type: ignore[import] import logging import re import random @@ -34,12 +31,6 @@ import base64 from typing import Tuple, Optional, Any from douyin.core import path_config -# Pillow 版本兼容:使用 Image.Resampling 或回退到 Image 常量 -try: - _RESAMPLE = Image.Resampling -except Exception: - _RESAMPLE = Image - # 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。 # 这些常量与文件 IO 辅助函数已抽离到 io_utils.py,此处仅为向后兼容重新导出。 from douyin.core.io_utils import ( @@ -423,7 +414,7 @@ class underlying_operations: _uo_log("随机等待{}秒.".format(random_wait_seconds)) self.delay(random_wait_seconds) - def check_countdown(self, last_time: str = "") -> tuple: + def check_countdown(self, last_time: str = "") -> tuple | bool: return _impl_check_countdown(last_time) def swipe( self, diff --git a/douyin/core/underlying_operations_pkg/countdown.py b/douyin/core/underlying_operations_pkg/countdown.py index 33fbff5..84aa06d 100644 --- a/douyin/core/underlying_operations_pkg/countdown.py +++ b/douyin/core/underlying_operations_pkg/countdown.py @@ -14,7 +14,7 @@ import logging import re import time from datetime import datetime, timedelta -from typing import Tuple +from typing import Optional, Tuple # 与原 underlying_operations._uo_log 同名 logger,避免改变历史日志检索 _LOGGER = logging.getLogger("douyin.core.underlying_operations") diff --git a/douyin/core/underlying_operations_pkg/image_ops.py b/douyin/core/underlying_operations_pkg/image_ops.py index 2f1206e..43221ea 100644 --- a/douyin/core/underlying_operations_pkg/image_ops.py +++ b/douyin/core/underlying_operations_pkg/image_ops.py @@ -47,6 +47,16 @@ def _validate_coords( 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: + try: + from douyin.fudai.core.fudai_debug_utils import ( + is_fudai_detail_field_debug_picname, + ) + + if is_fudai_detail_field_debug_picname(name): + return + except Exception: + pass + save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1" if not save_debug: try: @@ -238,6 +248,16 @@ def cut_pic( # 命名分支总是保存 cut_pic 调试图(与原版行为一致 — 没有开关检查) try: + try: + from douyin.fudai.core.fudai_debug_utils import ( + is_fudai_detail_field_debug_picname, + ) + + if is_fudai_detail_field_debug_picname(name): + return True + except Exception: + pass + from douyin.handlers import douyin_screenshot_manager pic_rgb = pic.convert("RGB") diff --git a/douyin/core/underlying_operations_pkg/ocr_pipeline.py b/douyin/core/underlying_operations_pkg/ocr_pipeline.py index 43d3259..714e178 100644 --- a/douyin/core/underlying_operations_pkg/ocr_pipeline.py +++ b/douyin/core/underlying_operations_pkg/ocr_pipeline.py @@ -25,6 +25,17 @@ from PIL import Image, UnidentifiedImageError import numpy as np +def _skip_fudai_detail_field_debug(self: Any, picname: str) -> bool: + try: + from douyin.fudai.core.fudai_debug_utils import ( + is_fudai_detail_field_debug_picname, + ) + + return is_fudai_detail_field_debug_picname(picname) + except Exception: + return False + + def analyse_pic_word( self: Any, picname: str, @@ -203,12 +214,16 @@ def _save_debug_preprocessed( """保存预处理后的调试图像(OCR 输入),仅当 SAVE_OCR_DEBUG_IMAGES=1 时执行。""" try: save_debug = os.environ.get("SAVE_OCR_DEBUG_IMAGES", "0") == "1" + if save_debug and _skip_fudai_detail_field_debug(self, picname): + return if not save_debug: try: save_debug = bool(getattr(self, "save_ocr_debug_images", False)) except Exception: pass + if save_debug and _skip_fudai_detail_field_debug(self, picname): + return if not save_debug: return @@ -265,6 +280,9 @@ def _save_debug_after_ocr( ) -> None: """保存 OCR 完成后的调试图像(含识别文本预览 + 置信度)。""" try: + if _skip_fudai_detail_field_debug(self, picname): + return + from douyin.handlers import douyin_screenshot_manager douyin_screenshot_manager.save_latest_attempt(img1, operation_type="ocr") diff --git a/douyin/core/underlying_operations_pkg/screenshot_direct.py b/douyin/core/underlying_operations_pkg/screenshot_direct.py index 1b14cbb..3ab2837 100644 --- a/douyin/core/underlying_operations_pkg/screenshot_direct.py +++ b/douyin/core/underlying_operations_pkg/screenshot_direct.py @@ -36,6 +36,59 @@ def _uo_log(msg: str) -> None: pass +def _valid_png(path0: str) -> bool: + """校验截图 PNG 是否完整;测试可 patch 此模块级函数。""" + skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1" + if skip_verify: + try: + if not os.path.exists(path0): + return False + return os.path.getsize(path0) >= 1024 + except Exception: + return False + + verify_start = time_module.time() + try: + if not os.path.exists(path0): + return False + sz = os.path.getsize(path0) + if sz < 1024: + return False + header_check_start = time_module.time() + try: + with open(path0, "rb") as _f: + header = _f.read(4) + if header != b"\x89PNG": + return False + try: + _f.seek(-256, 2) + except Exception: + _f.seek(0) + tail = _f.read(256) + if b"IEND" not in tail: + return False + except Exception: + return False + header_check_dur = (time_module.time() - header_check_start) * 1000.0 + if header_check_dur > 10.0: + logging.debug( + "[截图] PNG头尾校验耗时(ms)=%.1f path=%s", + header_check_dur, + path0, + ) + + verify_total_dur = (time_module.time() - verify_start) * 1000.0 + if verify_total_dur > 100.0: + logging.info( + "[截图] _valid_png总耗时(ms)=%.1f path=%s", + verify_total_dur, + path0, + ) + return True + except Exception: + return False + + def capture_screenshot_direct( self: "underlying_operations", device_id, path: str = "pic" ) -> bool: @@ -65,7 +118,7 @@ def capture_screenshot_direct( out_dir = path_config.get_pic_dir() else: - out_dir = os.path.join(os.path.dirname(__file__), "..", "target_pic") + out_dir = os.path.join(path_config.get_project_root(), "target_pic") if not os.path.exists(out_dir): os.makedirs(out_dir) @@ -75,59 +128,6 @@ def capture_screenshot_direct( adb = self._adb_path() - skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1" - - def _valid_png(path0: str) -> bool: - if skip_verify: - try: - if not os.path.exists(path0): - return False - sz = os.path.getsize(path0) - return sz >= 1024 - except Exception: - return False - - verify_start = time_module.time() - try: - if not os.path.exists(path0): - return False - sz = os.path.getsize(path0) - if sz < 1024: - return False - header_check_start = time_module.time() - try: - with open(path0, "rb") as _f: - header = _f.read(4) - if header != b"\x89PNG": - return False - try: - _f.seek(-256, 2) - except Exception: - _f.seek(0) - tail = _f.read(256) - if b"IEND" not in tail: - return False - except Exception: - return False - header_check_dur = (time_module.time() - header_check_start) * 1000.0 - if header_check_dur > 10.0: - logging.debug( - "[截图] PNG头尾校验耗时(ms)=%.1f path=%s", - header_check_dur, - path0, - ) - - verify_total_dur = (time_module.time() - verify_start) * 1000.0 - if verify_total_dur > 100.0: - logging.info( - "[截图] _valid_png总耗时(ms)=%.1f path=%s", - verify_total_dur, - path0, - ) - return True - except Exception: - return False - # 优先走 exec-out try: execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10")) @@ -466,6 +466,7 @@ def capture_screenshot_direct( except Exception: _uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}") return True + return False except Exception: # 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png try: diff --git a/douyin/detection/detection_pkg/detail.py b/douyin/detection/detection_pkg/detail.py index a2c76cd..66ddffa 100644 --- a/douyin/detection/detection_pkg/detail.py +++ b/douyin/detection/detection_pkg/detail.py @@ -8,11 +8,10 @@ from __future__ import annotations # pylint: disable=no-member import os +import re import time from typing import Any -from PIL import Image - from ._common import _ensure_detection_cache @@ -22,6 +21,39 @@ def check_detail_height(analyser: Any) -> int: Returns: 0 / 1 / 2 / 3 (number of tasks). """ + try: + from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode + + ui_mode = normalize_fudai_detail_ui_mode( + getattr(analyser, "fudai_detail_ui_mode", "auto") + ) + except Exception: + ui_mode = "auto" + + if ui_mode == "legacy": + return _check_detail_task_count_legacy_pixels(analyser) + + detected_v2_pixels = _check_detail_task_count_v2_pixels(analyser) + if detected_v2_pixels: + return detected_v2_pixels + + try: + from douyin.fudai.douyin_fudai_core_pkg.ocr_switches import ( + resolve_fudai_detail_ocr_switches_from_analyser, + ) + + if resolve_fudai_detail_ocr_switches_from_analyser(analyser).task_count: + detected_v2 = _check_detail_task_count_v2(analyser) + if detected_v2: + return detected_v2 + except Exception: + pass + + return 0 + + +def _check_detail_task_count_legacy_pixels(analyser: Any) -> int: + """Legacy detail task-count detection. Kept separate from v2 UI height logic.""" # 使用统一的截图路径配置 try: from douyin.core import path_config @@ -44,6 +76,8 @@ def check_detail_height(analyser: Any) -> int: pic = None for attempt in range(3): try: + from PIL import Image + pic = Image.open(pic1_path) pic.load() # force load to catch truncated files early break @@ -244,6 +278,136 @@ def check_detail_height(analyser: Any) -> int: return 0 +def _check_detail_task_count_v2_pixels(analyser: Any) -> int: + """Fast v2 task-count decision from popup height pixels before OCR regions are chosen.""" + try: + from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode + + ui_mode = normalize_fudai_detail_ui_mode( + getattr(analyser, "fudai_detail_ui_mode", "auto") + ) + if ui_mode == "legacy": + return 0 + except Exception: + ui_mode = "auto" + + try: + from douyin.core import path_config + from PIL import Image + + pic_path = path_config.get_screenshot_path() + pic = Image.open(pic_path).convert("RGB") + width, height = pic.size + except Exception: + return 0 + + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + + x = 536 * rx // 1080 + y_task_text = 1970 * ry // 2400 + y_task_card = 1955 * ry // 2400 + if not (0 <= x < width and 0 <= y_task_text < height and 0 <= y_task_card < height): + return 0 + + def _rgb_at(y_coord: int) -> tuple[int, int, int]: + p = pic.getpixel((x, y_coord)) + return int(p[0]), int(p[1]), int(p[2]) + + def _is_white_text(pixel: tuple[int, int, int]) -> bool: + r, g, b = pixel + return r >= 215 and g >= 215 and b >= 215 + + def _is_dark_card(pixel: tuple[int, int, int]) -> bool: + r, g, b = pixel + return 5 <= r <= 45 and 10 <= g <= 55 and 35 <= b <= 95 + + try: + task_text_pixel = _rgb_at(y_task_text) + task_card_pixel = _rgb_at(y_task_card) + except Exception: + return 0 + + # 当前 2.0 UI:一个任务时中线 y=1970 命中任务文案白字; + # 两个任务时同点仍是任务卡片深色背景。先用这个高度差选 profile。 + detected = 0 + reason = "" + if _is_white_text(task_text_pixel): + detected = 1 + reason = "task_text_white_at_v2_one_task_y" + elif _is_dark_card(task_text_pixel) and _is_dark_card(task_card_pixel): + detected = 2 + reason = "dark_card_continues_at_v2_two_task_y" + + if detected: + try: + setattr(analyser, "_fudai_detail_task_count_source", "v2_pixels") + analyser._log_kv( + "检测", + f"识别到福袋任务数量:{detected}个(v2像素高度)", + task_count=detected, + source="v2_pixels", + reason=reason, + check_x=x, + task_text_y=y_task_text, + task_text_pixel=task_text_pixel, + task_card_y=y_task_card, + task_card_pixel=task_card_pixel, + ui_mode=ui_mode, + ) + except Exception: + pass + return detected + + +def _check_detail_task_count_v2(analyser: Any) -> int: + """Fast v2 detail task-count OCR: parse denominator from '(1/2)'.""" + try: + from douyin.fudai.core.coords import DETAIL_UI_V2_0, DETAIL_UI_V2_0_ONE_TASK + + for name, profile in ( + ("福袋任务数量_v2_1task", DETAIL_UI_V2_0_ONE_TASK), + ("福袋任务数量_v2", DETAIL_UI_V2_0), + ): + box = tuple(profile.get("task_count") or ()) + if len(box) != 4: + continue + if hasattr(analyser, "cut_pic"): + analyser.cut_pic(*box, "", name, getattr(analyser, "y_pianyi", 0)) + raw = "" + try: + raw = str(analyser.operation.analyse_pic_word(name, 0) or "") + except Exception: + raw = str(analyser.operation.analyse_pic_digits(name, 0) or "") + m = re.search(r"[\(/(]\s*\d+\s*[//]\s*([1-3])\s*[\))]?", raw) + if not m: + m = re.search(r"\d+\s*[//]\s*([1-3])", raw) + if not m: + continue + task_count = int(m.group(1)) + try: + analyser._log_kv( + "检测", + f"识别到福袋任务数量:{task_count}个(v2 OCR)", + task_count=task_count, + source="v2_ocr", + profile_variant=str(profile.get("variant") or "default"), + raw=raw[:50], + ) + except Exception: + pass + return task_count + except Exception: + return 0 + return 0 + + def check_in_fudai_detail(analyser: Any) -> bool: @@ -279,6 +443,8 @@ def check_in_fudai_detail(analyser: Any) -> bool: analyser._detection_cache[cache_key] = (now, False) return False + from PIL import Image + pic = Image.open(pic_path) try: pic.load() diff --git a/douyin/detection/detection_pkg/finder.py b/douyin/detection/detection_pkg/finder.py index e78abf7..e897f9c 100644 --- a/douyin/detection/detection_pkg/finder.py +++ b/douyin/detection/detection_pkg/finder.py @@ -11,9 +11,12 @@ import os import time from typing import Any -from PIL import Image +from douyin.core import path_config from ._common import _ensure_detection_cache +from .finder_numpy_scan import scan_with_numpy +from .finder_pixel_scan import scan_pixel_by_pixel +from .finder_template_match import match_template def check_have_fudai_with_ready_screenshot( @@ -63,26 +66,21 @@ def check_have_fudai_with_ready_screenshot( func_start = time.time() # 使用统一的截图路径配置 try: - from douyin.core import path_config - pic1_path = path_config.get_screenshot_path() except Exception: - # 回退到旧路径(向后兼容) - from douyin.core import path_config - pic1_path = path_config.get_screenshot_path() attempt_count = 0 # 仅用于日志记录,不影响循环控制 # ===== 像素检测版(优先使用),不依赖 OpenCV ===== # 改为按时间控制循环,而不是按次数限制 try: - retry_delay_s = float( - getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6 - ) + retry_delay_raw = getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) + retry_delay_s = float(0.6 if retry_delay_raw is None else retry_delay_raw) except Exception: retry_delay_s = 0.6 try: - max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0) + max_wait_raw = getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) + max_wait_s = float(5.0 if max_wait_raw is None else max_wait_raw) except Exception: max_wait_s = 5.0 if retry_delay_s < 0.1: @@ -103,7 +101,12 @@ def check_have_fudai_with_ready_screenshot( max_wait_s * 1.5, 15 ) # 最长15秒,但不超过 max_wait_s * 1.5 - while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout: + first_iteration = True + while ( + first_iteration + or ((time.time() - func_start) < max_wait_s and time.time() < absolute_timeout) + ): + first_iteration = False # 额外的循环次数保护:防止无限循环 if loop >= max_loops: try: @@ -157,12 +160,16 @@ def check_have_fudai_with_ready_screenshot( # 读取截图 pic = None try: + from PIL import Image + pic = Image.open(pic1_path) pic.load() except Exception: # 如果读取失败,尝试重新截图 try: analyser.operation.get_screenshot(analyser.device_id, use_service=False) + from PIL import Image + pic = Image.open(pic1_path) pic.load() except Exception: @@ -223,8 +230,9 @@ def check_have_fudai_with_ready_screenshot( try: # 尝试获取上次找到的福袋位置(1080基准) last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0) - if last_fudai_x > 0 and scan_x_start <= last_fudai_x <= scan_x_end: - optimal_x_scaled = last_fudai_x * rx // 1080 + last_fudai_x_scaled = last_fudai_x * rx // 1080 + if last_fudai_x > 0 and scan_x_start <= last_fudai_x_scaled <= scan_x_end: + optimal_x_scaled = last_fudai_x_scaled else: # 使用默认最优位置:最热门区域中心(98-240的中心,约169) optimal_x_scaled = 169 * rx // 1080 @@ -235,6 +243,10 @@ def check_have_fudai_with_ready_screenshot( # 确保最优位置在搜索范围内 optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1)) + pixel_icon_enabled = bool( + getattr(analyser, "pixel_detect_fudai_icon_enabled", True) + ) + # 保存完整截图用于调试(检测前) try: from douyin.handlers import douyin_screenshot_manager @@ -269,32 +281,34 @@ def check_have_fudai_with_ready_screenshot( except Exception: pass - # numpy 加速扫描(性能优化,失败回退到逐像素扫描) - from douyin.detection.detection_pkg.finder_numpy_scan import scan_with_numpy - detected, _detected_x = scan_with_numpy( - analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled - ) - if detected and _detected_x is not None: - detected_x = _detected_x - - # numpy 未命中/不可用时回退到逐像素扫描 - if not detected: - from douyin.detection.detection_pkg.finder_pixel_scan import scan_pixel_by_pixel - detected, _detected_x = scan_pixel_by_pixel( - analyser, pic_new, rx, ry, y_pianyi_val + if pixel_icon_enabled: + # numpy 加速扫描(性能优化,失败回退到逐像素扫描) + detected, _detected_x = scan_with_numpy( + analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled ) if detected and _detected_x is not None: detected_x = _detected_x + # numpy 未命中/不可用时回退到逐像素扫描 + if not detected: + detected, _detected_x = scan_pixel_by_pixel( + analyser, pic_new, rx, ry, y_pianyi_val + ) + if detected and _detected_x is not None: + detected_x = _detected_x + # 像素检测未命中时,使用模板匹配作为兜底 if not detected or detected_x is None: - from douyin.detection.detection_pkg.finder_template_match import match_template _det, _x = match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) if _det and _x is not None: detected = True detected_x = _x if detected and detected_x is not None: + try: + analyser.last_fudai_x = int(detected_x) + except Exception: + pass # 重置连续失败计数 consecutive_failures = 0 diff --git a/douyin/detection/detection_pkg/finder_numpy_scan.py b/douyin/detection/detection_pkg/finder_numpy_scan.py index f2aa615..308585d 100644 --- a/douyin/detection/detection_pkg/finder_numpy_scan.py +++ b/douyin/detection/detection_pkg/finder_numpy_scan.py @@ -42,10 +42,10 @@ def scan_with_numpy( width, height = pic_new.size try: - # 计算检测区域,考虑分辨率缩放和偏移 - # 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变) + # 计算检测区域,考虑分辨率缩放和偏移。 + # 新版福袋 icon 可能更靠左,numpy 快速扫描区域向左扩大。 y0 = 354 * ry // 2400 + y_pianyi_val - x1 = max(0, 157 * rx // 1080) + x1 = max(0, 120 * rx // 1080) x2 = min(width, 410 * rx // 1080) y_top = max(0, y0 - 3) y_bottom = min(height, y0 + 4) diff --git a/douyin/detection/detection_pkg/finder_template_match.py b/douyin/detection/detection_pkg/finder_template_match.py index 3849536..9667420 100644 --- a/douyin/detection/detection_pkg/finder_template_match.py +++ b/douyin/detection/detection_pkg/finder_template_match.py @@ -259,6 +259,10 @@ def match_template( ) detected = True + try: + analyser.last_fudai_x = detected_x + except Exception: + pass try: analyser.last_find_fudai_time = time.time() except Exception: diff --git a/douyin/detection/pixel/_common.py b/douyin/detection/pixel/_common.py index 34bf93b..8068952 100644 --- a/douyin/detection/pixel/_common.py +++ b/douyin/detection/pixel/_common.py @@ -13,13 +13,13 @@ import os from typing import Any, Optional -from PIL import Image - -def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]: +def _safe_open_screenshot_rgb(pic_path: str): try: if not pic_path or (not os.path.exists(pic_path)): return None + from PIL import Image + pic = Image.open(pic_path) try: pic.load() diff --git a/douyin/detection/pixel/buttons.py b/douyin/detection/pixel/buttons.py index 60ee01f..8dd2520 100644 --- a/douyin/detection/pixel/buttons.py +++ b/douyin/detection/pixel/buttons.py @@ -1,3 +1,5 @@ +from __future__ import annotations + # pyright: reportGeneralTypeIssues=false # pyright: reportAttributeAccessIssue=false # pyright: reportMissingModuleSource=false @@ -14,8 +16,6 @@ import os from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Optional -from PIL import Image - from ._common import _safe_open_screenshot_rgb diff --git a/douyin/detection/pixel/popups.py b/douyin/detection/pixel/popups.py index db2da92..8459b89 100644 --- a/douyin/detection/pixel/popups.py +++ b/douyin/detection/pixel/popups.py @@ -1,3 +1,5 @@ +from __future__ import annotations + # pyright: reportGeneralTypeIssues=false # pyright: reportAttributeAccessIssue=false # pyright: reportMissingModuleSource=false @@ -15,8 +17,6 @@ import os from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Optional -from PIL import Image - from ._common import _safe_open_screenshot_rgb @@ -292,23 +292,34 @@ def detect_redpacket_popup_background( def detect_lucky_draw_result_popup( - pic_rgb: Image.Image, red_ratio_threshold: float = 0.8, return_info: bool = False + pic_rgb: Image.Image, + red_ratio_threshold: float = 0.8, + return_info: bool = False, + analyser: Any = None, ) -> bool | tuple[bool, dict]: - """检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。 + """检测抽奖结果弹窗:"我知道了"按钮区域,按 UI 版本检测对应按钮颜色。 使用基准 1080x2400 坐标的检测区域: - - 左上: (181, 1261) - - 右下: (890, 1389) + - legacy/v1:旧版红按钮,检查红色占比 + - auto/v2_0:新版白按钮,检查白色按钮内部占比 """ try: + from douyin.fudai.core.coords import get_lottery_result_confirm_profile + + profile = get_lottery_result_confirm_profile( + getattr(analyser, "fudai_detail_ui_mode", "auto") if analyser is not None else "auto" + ) + width, height = pic_rgb.size scale_x = width / 1080.0 scale_y = height / 2400.0 - x1 = int(181 * scale_x) - y1 = int(1261 * scale_y) - x2 = int(890 * scale_x) - y2 = int(1389 * scale_y) + bx1, by1, bx2, by2 = tuple(profile.get("pixel") or (181, 1261, 890, 1389)) + x1 = int(bx1 * scale_x) + y1 = int(by1 * scale_y) + x2 = int(bx2 * scale_x) + y2 = int(by2 * scale_y) + pixel_style = str(profile.get("pixel_style") or "red") # 边界与顺序 x1, x2 = max(0, min(x1, width)), max(0, min(x2, width)) @@ -341,6 +352,8 @@ def detect_lucky_draw_result_popup( extra_info={ "threshold": red_ratio_threshold, "region_size": f"{x2-x1}x{y2-y1}", + "ui_version": profile.get("version"), + "pixel_style": pixel_style, }, ) if debug_path: @@ -358,6 +371,7 @@ def detect_lucky_draw_result_popup( pass red_count = 0 + white_count = 0 total_samples = 0 step_x = max(1, (x2 - x1) // 10) step_y = max(1, (y2 - y1) // 10) @@ -371,6 +385,9 @@ def detect_lucky_draw_result_popup( # 红色按钮检测:R >= 245 且 R 明显大于 G 和 B if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50: red_count += 1 + # 新版“我知道了”按钮为白底红字,按钮内部白色占比很高。 + if r >= 230 and g >= 230 and b >= 230: + white_count += 1 except Exception as e: # type: ignore[general-exception] continue @@ -378,7 +395,11 @@ def detect_lucky_draw_result_popup( return False red_ratio = red_count / total_samples - result = red_ratio >= red_ratio_threshold + white_ratio = white_count / total_samples + if pixel_style == "white": + result = white_ratio >= red_ratio_threshold + else: + result = red_ratio >= red_ratio_threshold # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 try: @@ -401,10 +422,14 @@ def detect_lucky_draw_result_popup( coords=(x1, y1, x2, y2), # 标注识别区域 extra_info={ "red_ratio": round(red_ratio, 4), + "white_ratio": round(white_ratio, 4), "red_count": red_count, + "white_count": white_count, "total_samples": total_samples, "threshold": red_ratio_threshold, "result": "success" if result else "failed", + "ui_version": profile.get("version"), + "pixel_style": pixel_style, }, ) if debug_path: @@ -431,9 +456,13 @@ def detect_lucky_draw_result_popup( return result, { "method": "pixel_detect", "red_ratio": red_ratio, + "white_ratio": white_ratio, "red_count": red_count, + "white_count": white_count, "total_samples": total_samples, "effective_threshold": red_ratio_threshold, + "ui_version": profile.get("version"), + "pixel_style": pixel_style, "reason": reason_value, } diff --git a/douyin/detection/pixel/stage.py b/douyin/detection/pixel/stage.py index 58784de..b77ff6f 100644 --- a/douyin/detection/pixel/stage.py +++ b/douyin/detection/pixel/stage.py @@ -1,3 +1,5 @@ +from __future__ import annotations + # pyright: reportGeneralTypeIssues=false # pyright: reportAttributeAccessIssue=false # pyright: reportMissingModuleSource=false @@ -15,9 +17,16 @@ import os from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Optional -from PIL import Image - from ._common import _safe_open_screenshot_rgb +from .buttons import ( + detect_attend_button_red_area, + detect_fansclub_join_red_area, +) +from .popups import ( + detect_coupon_popup_background, + detect_lucky_draw_result_popup, + detect_redpacket_popup_background, +) def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: @@ -33,7 +42,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: (detected, confidence) 其中 confidence 为白色像素比例(0.0~1.0) """ try: - from PIL import ImageDraw + from PIL import Image, ImageDraw import numpy as np width, height = pic_rgb.size @@ -318,6 +327,12 @@ def read_pixel_stage_state_from_screenshot( except Exception as e: # type: ignore[general-exception] pass + def _enabled(name: str, default: bool = True) -> bool: + try: + return bool(getattr(analyser, name, default)) if analyser is not None else default + except Exception: + return default + # 定义直播间图标像素检测包装函数 def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]: """直播间图标像素检测包装函数,返回 (bool, dict) 格式""" @@ -335,35 +350,44 @@ def read_pixel_stage_state_from_screenshot( # 模板匹配已删除,只使用像素检测 - detection_tasks = { - "has_coupon_bg": lambda pic: detect_coupon_popup_background( + detection_tasks = {} + if _enabled("pixel_detect_coupon_popup_enabled", True): + detection_tasks["has_coupon_bg"] = lambda pic: detect_coupon_popup_background( pic, return_info=True, template_threshold=coupon_threshold, analyser=analyser, - ), - "has_redpacket_bg": lambda pic: detect_redpacket_popup_background( + ) + if _enabled("pixel_detect_shopping_redpacket_enabled", False): + detection_tasks["has_redpacket_bg"] = lambda pic: detect_redpacket_popup_background( pic, return_info=True, red_ratio_threshold=redpacket_threshold, analyser=analyser, - ), - "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup( - pic, lucky_draw_red_ratio_threshold, return_info=True - ), - "has_attend_button_red": lambda pic: detect_attend_button_red_area( + ) + if _enabled("pixel_detect_lottery_result_enabled", True): + detection_tasks["has_lucky_draw_result"] = lambda pic: detect_lucky_draw_result_popup( + pic, + lucky_draw_red_ratio_threshold, + return_info=True, + analyser=analyser, + ) + if _enabled("pixel_detect_attend_button_enabled", True): + detection_tasks["has_attend_button_red"] = lambda pic: detect_attend_button_red_area( pic, return_info=True, red_ratio_threshold=attend_button_threshold, analyser=analyser, - ), - "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area( + ) + if _enabled("pixel_detect_fansclub_join_enabled", True): + detection_tasks["has_fansclub_join_red"] = lambda pic: detect_fansclub_join_red_area( pic, return_info=True, red_ratio_threshold=fansclub_threshold, analyser=analyser, - ), - "has_fudai_detail": lambda pic: detect_fudai_detail_page( + ) + if _enabled("pixel_detect_fudai_detail_enabled", True): + detection_tasks["has_fudai_detail"] = lambda pic: detect_fudai_detail_page( pic, resolution_ratio_x, resolution_ratio_y, @@ -371,9 +395,18 @@ def read_pixel_stage_state_from_screenshot( fudai_template_threshold, return_info=True, analyser=analyser, - ), - "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测) - } + ) + if _enabled("pixel_detect_live_room_enabled", True): + detection_tasks["has_live_room_pixel"] = _detect_live_room_pixel_wrapper + + if return_details: + for key in state: + if key not in detection_tasks: + details[key] = {"detected": False, "method": "disabled", "reason": "switch_off"} + if not detection_tasks: + if return_details: + return state, details + return state # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) with ThreadPoolExecutor(max_workers=8) as executor: diff --git a/douyin/fudai/core/coords.py b/douyin/fudai/core/coords.py index c4c5c4e..48d4b22 100644 --- a/douyin/fudai/core/coords.py +++ b/douyin/fudai/core/coords.py @@ -35,7 +35,16 @@ NO_PRIZE_CONFIRM = (340, 1195, 740, 1355) # 抽奖结果相关区域 LOTTERY_RESULT_AREA = (300, 600, 800, 800) -LOTTERY_RESULT_CONFIRM_BUTTON = (181, 1261, 890, 1389) +LOTTERY_RESULT_CONFIRM_BUTTON_V1 = (181, 1261, 890, 1389) +LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 = LOTTERY_RESULT_CONFIRM_BUTTON_V1 +LOTTERY_RESULT_CONFIRM_CLICK_V1 = (532, 1289) +LOTTERY_RESULT_CONFIRM_BUTTON_V2 = (250, 1275, 825, 1435) +LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2 = (290, 1300, 790, 1415) +LOTTERY_RESULT_CONFIRM_CLICK_V2 = (540, 1360) +# 默认导出保持兼容;运行时请通过 get_lottery_result_confirm_profile 按 UI 版本选择。 +LOTTERY_RESULT_CONFIRM_BUTTON = LOTTERY_RESULT_CONFIRM_BUTTON_V1 +LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 +LOTTERY_RESULT_CONFIRM_CLICK = LOTTERY_RESULT_CONFIRM_CLICK_V1 # 购物红包/弹窗诊断区域 SHOPPING_REDPACKET_AREA = (200, 300, 880, 1200) @@ -48,7 +57,89 @@ FOLLOW_TAB = (658, 147, 765, 194) LIVE_LIST_TAB = (400, 140, 900, 200) # 直播间标题中部(用于部分详情模块) -LIVE_ROOM_TITLE = (144, 144, 329, 185) +LIVE_ROOM_TITLE = (130, 120, 560, 225) + + +# 福袋详情页 UI 版本 profile。legacy 保持旧坐标,v2_0 对应 2026-06 当前新详情页。 +DETAIL_UI_LEGACY = { + "version": "legacy", + "content": CONTENT_BOX, + "value": VALUE_BOX_TARGET, + "countdown_full": COUNTDOWN_1110_1230, + "task_list": TASK_LIST, + "task_count": (0, 0, 0, 0), + "participants": CONTENT_BOX, + "button": PARTICIPATE_BUTTON, + "live_title": LIVE_ROOM_TITLE, +} + +DETAIL_UI_V2_0 = { + "version": "v2_0", + "content": (360, 1472, 1035, 1545), + "value": (300, 1585, 650, 1685), + "countdown_full": (760, 1355, 1035, 1455), + "task_list": (60, 1840, 1030, 2005), + "task_count": (860, 1770, 1035, 1875), + "participants": (520, 1325, 760, 1415), + "button": (70, 2020, 1010, 2165), + "live_title": LIVE_ROOM_TITLE, +} + +DETAIL_UI_V2_0_ONE_TASK = { + "version": "v2_0", + "variant": "one_task", + "content": (360, 1472, 1035, 1545), + "value": (340, 1680, 690, 1765), + "countdown_full": (760, 1355, 1035, 1455), + "task_list": (55, 1935, 900, 2055), + "task_count": (890, 1855, 1040, 1950), + "participants": (535, 1375, 760, 1475), + "button": (70, 2055, 1010, 2225), + "live_title": LIVE_ROOM_TITLE, +} + + +def normalize_fudai_detail_ui_mode(mode: str | None) -> str: + """Normalize detail UI mode for config/API boundaries.""" + mode_s = str(mode or "auto").strip().lower().replace("-", "_").replace(".", "_") + if mode_s in ("v2", "2_0", "v2_0"): + return "v2_0" + if mode_s in ("legacy", "old", "v1"): + return "legacy" + return "auto" + + +def get_fudai_detail_profile(mode: str | None = "auto", task_count: int | None = None) -> dict: + """Return the OCR region profile. auto currently prefers the fast v2_0 path.""" + normalized = normalize_fudai_detail_ui_mode(mode) + if normalized == "legacy": + return DETAIL_UI_LEGACY + try: + if int(task_count or 0) == 1: + return DETAIL_UI_V2_0_ONE_TASK + except Exception: + pass + return DETAIL_UI_V2_0 + + +def get_lottery_result_confirm_profile(mode: str | None = "auto") -> dict: + """Return confirm-button regions for the lottery result popup by UI version.""" + normalized = normalize_fudai_detail_ui_mode(mode) + if normalized == "legacy": + return { + "version": "legacy", + "button": LOTTERY_RESULT_CONFIRM_BUTTON_V1, + "pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1, + "click": LOTTERY_RESULT_CONFIRM_CLICK_V1, + "pixel_style": "red", + } + return { + "version": "v2_0", + "button": LOTTERY_RESULT_CONFIRM_BUTTON_V2, + "pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2, + "click": LOTTERY_RESULT_CONFIRM_CLICK_V2, + "pixel_style": "white", + } # 备用/替代参与按钮区域(弹窗/诊断模块使用) PARTICIPATE_BUTTON_ALT = PARTICIPATE_BUTTON diff --git a/douyin/fudai/core/fudai_attend.py b/douyin/fudai/core/fudai_attend.py index 4a57c86..7a1f584 100644 --- a/douyin/fudai/core/fudai_attend.py +++ b/douyin/fudai/core/fudai_attend.py @@ -33,10 +33,19 @@ def attend_choujiang(analyser) -> bool: except Exception: cached_room_pos = 0 - # 如果并行OCR属性缺失或不完整,尝试从其它缓存字段复用识别结果(例如 button_text_raw 或映射表) + # 如果并行OCR属性缺失或不完整,尝试从其它缓存字段复用识别结果。 + # 注意:button_text_raw 是全局缓存,可能来自上一个直播间; + # 只有确认同房间时,才允许直接信任它。 if not button_text or not button_status: try: - candidate = getattr(analyser, "button_text_raw", None) + same_room_cache = ( + not current_room_pos + or not cached_room_pos + or current_room_pos == cached_room_pos + ) + candidate = None + if same_room_cache: + candidate = getattr(analyser, "button_text_raw", None) if not candidate: try: room_pos = int(getattr(analyser, "room_pos", 0) or 0) @@ -52,6 +61,43 @@ def attend_choujiang(analyser) -> bool: ) except Exception: pass + if not candidate: + try: + current_title = str( + getattr(analyser, "current_room_title", "") or "" + ).strip() + current_title_raw = str( + getattr(analyser, "current_room_title_raw", "") or "" + ).strip() + room_map = getattr(analyser, "_room_pos_to_title_map", {}) or {} + if isinstance(room_map, dict) and ( + current_title or current_title_raw + ): + for info in room_map.values(): + if not isinstance(info, dict): + continue + mapped_title = str(info.get("title") or "").strip() + mapped_title_raw = str( + info.get("title_raw") or "" + ).strip() + if not ( + (current_title and mapped_title == current_title) + or ( + current_title_raw + and mapped_title_raw == current_title_raw + ) + ): + continue + fudai_detail = info.get("fudai_detail") or {} + candidate = ( + fudai_detail.get("button_text") + or fudai_detail.get("button_text_raw") + or None + ) + if candidate: + break + except Exception: + pass if candidate: bt = str(candidate or "").strip() @@ -105,7 +151,17 @@ def attend_choujiang(analyser) -> bool: try: button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0) current_time = time.time() - if button_text and button_status and current_time - button_ocr_time < 5.0: + same_room = ( + not current_room_pos + or not cached_room_pos + or current_room_pos == cached_room_pos + ) + if ( + button_text + and button_status + and current_time - button_ocr_time < 5.0 + and same_room + ): attend_button_text = button_text analyser._log_kv( "参与", @@ -116,11 +172,6 @@ def attend_choujiang(analyser) -> bool: button_status=button_status, ) elif button_text and button_status: - same_room = ( - not current_room_pos - or not cached_room_pos - or current_room_pos == cached_room_pos - ) if same_room: attend_button_text = button_text try: @@ -464,26 +515,36 @@ def attend_choujiang(analyser) -> bool: from douyin.core.path_config import get_debug_log_path current_ts_debug = int(time.time() * 1000) - with open(get_debug_log_path(), "a", encoding="utf-8") as f: - f.write( - json.dumps( - { - "id": f"log_{current_ts_debug}_set_countdown_start", - "timestamp": current_ts_debug, - "location": "fudai_attend.py:186", - "message": "开始设置等待开奖标志", - "data": { - "future_ts": getattr( - analyser, "_current_fudai_future_ts", 0.0 - ) + try: + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{current_ts_debug}_set_countdown_start", + "timestamp": current_ts_debug, + "location": "fudai_attend.py:186", + "message": "开始设置等待开奖标志", + "data": { + "future_ts": float( + getattr( + analyser, + "_current_fudai_future_ts", + 0.0, + ) + or 0.0 + ) + }, + "sessionId": "debug-session", + "runId": "countdown_debug_run1", + "hypothesisId": "countdown_hyp2", }, - "sessionId": "debug-session", - "runId": "countdown_debug_run1", - "hypothesisId": "countdown_hyp2", - } + ensure_ascii=False, + default=str, + ) + + "\n" ) - + "\n" - ) + except Exception: + pass # #endregion try: @@ -499,28 +560,38 @@ def attend_choujiang(analyser) -> bool: analyser._lottery_wait_start_ts = current_time # #region agent log - countdown set - with open(get_debug_log_path(), "a", encoding="utf-8") as f: - f.write( - json.dumps( - { - "id": f"log_{current_ts_debug}_countdown_set", - "timestamp": current_ts_debug, - "location": "fudai_attend.py:195", - "message": "成功设置等待开奖标志", - "data": { - "waiting_for_lottery_result": analyser._waiting_for_lottery_result, - "lottery_result_expected_ts": analyser._lottery_result_expected_ts, - "future_ts": future_ts, - "current_time": current_time, - "remain_seconds": remain_seconds, + try: + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{current_ts_debug}_countdown_set", + "timestamp": current_ts_debug, + "location": "fudai_attend.py:195", + "message": "成功设置等待开奖标志", + "data": { + "waiting_for_lottery_result": bool( + analyser._waiting_for_lottery_result + ), + "lottery_result_expected_ts": float( + analyser._lottery_result_expected_ts + or 0.0 + ), + "future_ts": float(future_ts or 0.0), + "current_time": float(current_time or 0.0), + "remain_seconds": int(remain_seconds), + }, + "sessionId": "debug-session", + "runId": "countdown_debug_run1", + "hypothesisId": "countdown_hyp2", }, - "sessionId": "debug-session", - "runId": "countdown_debug_run1", - "hypothesisId": "countdown_hyp2", - } + ensure_ascii=False, + default=str, + ) + + "\n" ) - + "\n" - ) + except Exception: + pass # #endregion analyser._log_kv( "参与", diff --git a/douyin/fudai/core/fudai_debug_utils.py b/douyin/fudai/core/fudai_debug_utils.py index 81a4bfd..6011d3d 100644 --- a/douyin/fudai/core/fudai_debug_utils.py +++ b/douyin/fudai/core/fudai_debug_utils.py @@ -8,12 +8,36 @@ from __future__ import annotations import os import traceback -from typing import Any, Tuple, Optional, Dict -from PIL import Image, UnidentifiedImageError +from typing import Any, Tuple, Optional, Dict, Iterable, Mapping from douyin.core import path_config +FUDAI_DETAIL_FIELD_DEBUG_PICNAMES = { + "福袋内容", + "福袋价值", + "福袋倒计时", + "福袋倒计时_分钟", + "福袋倒计时_秒", + "福袋倒计时_整行", + "福袋任务列表", + "参与按钮", + "福袋参与人数", + "live_room_title_mid", +} + + +def is_fudai_detail_field_debug_picname(picname: Any) -> bool: + """福袋详情字段级调试图统一跳过,只保留详情综合标注图。""" + try: + name = str(picname or "") + except Exception: + return False + if name in FUDAI_DETAIL_FIELD_DEBUG_PICNAMES: + return True + return name.startswith("福袋倒计时_候选") + + def log_debug_error( analyser: Any, error: Exception, @@ -100,7 +124,7 @@ def validate_coords( return True, None, corrected_coords -def safe_image_load(image_path: str) -> Optional[Image.Image]: +def safe_image_load(image_path: str): """安全地加载图像,带详细的错误处理。 参数: @@ -113,6 +137,8 @@ def safe_image_load(image_path: str) -> Optional[Image.Image]: return None try: + from PIL import Image, UnidentifiedImageError + pic = Image.open(image_path) try: pic.load() @@ -134,7 +160,9 @@ def save_full_screenshot_with_ocr_region( analyser: Any, picname: str, coords: Tuple[int, int, int, int], - y_pianyi: int = 0 + y_pianyi: int = 0, + *, + extra_info: Optional[Dict[str, Any]] = None, ) -> None: """保存完整截图并标注OCR区域(用于调试)。 @@ -183,7 +211,7 @@ def save_full_screenshot_with_ocr_region( return # 安全加载图像 - pic_rgb: Optional[Image.Image] = None + pic_rgb = None try: try: pic_rgb = safe_image_load(pic_path) @@ -284,17 +312,21 @@ def save_full_screenshot_with_ocr_region( # 保存调试图片 try: + debug_extra_info = { + "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", + "size": f"{x2_base-x1_base}x{y2_base-y1_base}", + "y_offset": y_pianyi, + } + if isinstance(extra_info, dict): + debug_extra_info.update(extra_info) + debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, operation_type="ocr", picname=picname, step="before_ocr", coords=(x1, y1, x2, y2), - extra_info={ - "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", - "size": f"{x2_base-x1_base}x{y2_base-y1_base}", - "y_offset": y_pianyi, - }, + extra_info=debug_extra_info, ) if debug_path: @@ -340,3 +372,141 @@ def save_full_screenshot_with_ocr_region( # 向后兼容:保留原函数名 _save_full_screenshot_with_ocr_region = save_full_screenshot_with_ocr_region + + +def save_fudai_detail_debug_overview( + analyser: Any, + regions: Iterable[Mapping[str, Any]], + *, + ui_version: str, + ocr_enabled: Iterable[str], + task_count: int, + task_count_source: str = "", + y_pianyi: int = 0, +) -> Optional[str]: + """保存一张福袋详情整屏综合标注图。""" + try: + from PIL import ImageDraw, ImageFont + from douyin.handlers import douyin_screenshot_manager + + region_list = list(regions) + pic_path = path_config.get_screenshot_path() + if not os.path.exists(pic_path): + return None + pic_rgb = safe_image_load(pic_path) + if pic_rgb is None: + return None + + try: + width, height = pic_rgb.size + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + draw = ImageDraw.Draw(pic_rgb) + try: + font = ImageFont.truetype("arial.ttf", 24) + small_font = ImageFont.truetype("arial.ttf", 18) + except Exception: + font = ImageFont.load_default() + small_font = font + + palette = [ + (255, 67, 67), + (0, 178, 255), + (255, 184, 0), + (39, 214, 126), + (190, 112, 255), + (255, 116, 178), + (130, 210, 255), + (255, 255, 255), + ] + + enabled_set = {str(x) for x in ocr_enabled} + legend_lines = [ + f"fudai_detail ui={ui_version} task_count={task_count}", + f"task_count_source={task_count_source or '-'}", + "ocr_enabled=" + ",".join(sorted(enabled_set)), + ] + pad = 12 + legend_h = 34 * len(legend_lines) + pad * 2 + draw.rectangle((18, 90, min(width - 18, 1040), 90 + legend_h), fill=(0, 0, 0)) + for idx, line in enumerate(legend_lines): + draw.text((30, 102 + idx * 34), line, fill=(255, 255, 255), font=small_font) + + for idx, region in enumerate(region_list): + coords = tuple(region.get("coords") or ()) + if len(coords) != 4: + continue + name = str(region.get("name") or f"region_{idx}") + key = str(region.get("key") or name) + enabled = bool(region.get("enabled", key in enabled_set)) + x1_base, y1_base, x2_base, y2_base = [int(v) for v in coords] + x1 = int(x1_base * width / rx) + y1 = int((y1_base + y_pianyi) * height / ry) + x2 = int(x2_base * width / rx) + y2 = int((y2_base + y_pianyi) * height / ry) + ok, _, fixed = validate_coords((x1, y1, x2, y2), width, height) + if not ok: + continue + x1, y1, x2, y2 = fixed + color = palette[idx % len(palette)] if enabled else (130, 130, 130) + width_px = 4 if enabled else 2 + for offset in range(width_px): + draw.rectangle( + (x1 - offset, y1 - offset, x2 + offset, y2 + offset), + outline=color, + ) + label = f"{name} {'on' if enabled else 'off'}" + label_y = max(0, y1 - 28) + label_w = min(width - x1 - 2, max(120, len(label) * 13)) + draw.rectangle((x1, label_y, x1 + label_w, label_y + 26), fill=(0, 0, 0)) + draw.text((x1 + 4, label_y + 3), label, fill=color, font=small_font) + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="ocr", + picname="福袋详情综合标注", + step="detail_regions", + coords=None, + extra_info={ + "ui_version": ui_version, + "task_count": task_count, + "task_count_source": task_count_source or "-", + "ocr_enabled": ",".join(sorted(enabled_set)), + }, + annotate=False, + background=False, + ) + if debug_path: + try: + analyser._log_kv( + "[调试图像]", + "福袋详情综合标注图已保存", + path=debug_path, + ui_version=ui_version, + task_count=task_count, + task_count_source=task_count_source or "-", + region_count=len(region_list), + ) + except Exception: + pass + return debug_path + finally: + try: + pic_rgb.close() + except Exception: + pass + except Exception as e: + try: + log_debug_error( + analyser, + e, + { + "stage": "保存福袋详情综合标注图", + "ui_version": ui_version, + "task_count": task_count, + }, + level="WARNING", + ) + except Exception: + pass + return None diff --git a/douyin/fudai/core/fudai_detail_coupon_detection.py b/douyin/fudai/core/fudai_detail_coupon_detection.py index bbe3664..5683509 100644 --- a/douyin/fudai/core/fudai_detail_coupon_detection.py +++ b/douyin/fudai/core/fudai_detail_coupon_detection.py @@ -5,7 +5,6 @@ from typing import Any from douyin.fudai.core.coords import PARTICIPATE_BUTTON_ALT import os -from PIL import Image def is_wrong_coupon_popup(analyser: Any) -> bool: @@ -46,6 +45,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: path = path_config.get_screenshot_path() try: + from PIL import Image _raw = Image.open(path) try: _raw.load() # Force load to catch truncated files early @@ -239,6 +239,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): + from PIL import Image _raw = Image.open(pic_path) try: _raw.load() diff --git a/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py b/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py index 384e951..6a58bf3 100644 --- a/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py +++ b/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py @@ -8,8 +8,7 @@ import os import time from typing import Any, Dict, Optional, Tuple -from PIL import Image - +from douyin.core import path_config from douyin.fudai.douyin_fudai_core import get_fudai_contain from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail @@ -164,8 +163,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: try: if getattr(analyser, "_screenshot_ready_for_ocr", False): try: - from douyin.core import path_config - pic_path = path_config.get_screenshot_path() except Exception: # 兜底:导入失败时显式拼到项目根的 pic/, @@ -183,18 +180,38 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: ) if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024: - analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用 - screenshot_reused = True try: - analyser._log_kv( - "福袋详情", - "read_fudai_detail_once:复用阶段诊断截图", - log_type="SCREENSHOT", - reason="stage_diagnosed_task_count_gt_zero", - path=pic_path, - ) - except Exception: - pass + from PIL import Image + + _reuse_probe = Image.open(pic_path) + try: + _reuse_probe.load() + finally: + _reuse_probe.close() + analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用 + screenshot_reused = True + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once:复用阶段诊断截图", + log_type="SCREENSHOT", + reason="stage_diagnosed_task_count_gt_zero", + path=pic_path, + ) + except Exception: + pass + except Exception as e: + screenshot_reused = False + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once:阶段诊断截图不可读,改为重新截图", + log_type="SCREENSHOT", + path=pic_path, + error=str(e), + ) + except Exception: + pass else: try: analyser._log_kv( @@ -219,8 +236,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 等待截图文件确实存在(最多等待3秒) try: - from douyin.core import path_config - pic_path = path_config.get_screenshot_path() except Exception: # 兜底:导入失败时显式拼到项目根的 pic/, @@ -260,6 +275,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pic_rgb = None try: if os.path.exists(pic_path): + from PIL import Image + _img0 = time.time() pic = Image.open(pic_path) try: @@ -279,6 +296,10 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: ) except Exception: pass + try: + analyser._screenshot_ready_for_ocr = False + except Exception: + pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time @@ -382,7 +403,34 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pass _log_perf("exception_in_get_fudai_contain") return "error", tup_err, {} - # 由于已全局禁用流式截图,不再重新启动服务 + finally: + if _ocr_screenshot_service_disabled and bool( + getattr(analyser, "enable_streaming_screenshot", True) + ): + try: + from operations.screenshot_service import ScreenshotService + + ScreenshotService.get_instance().start( + getattr(analyser, "device_id", ""), interval=1.5 + ) + try: + analyser._log_kv( + "截图服务", + "OCR完成后恢复后台截图服务", + reason="resume_background_screenshots_after_ocr", + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "截图服务", + "恢复后台截图服务失败", + error=str(e), + level="WARNING", + ) + except Exception: + pass # 检查是否检测到观看任务(通过 _is_watch_task_detected 标志) is_watch_task = False diff --git a/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py b/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py index 11ea74d..cbd62d5 100644 --- a/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py +++ b/douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py @@ -9,8 +9,6 @@ import os import time from typing import Any, Dict, Optional, Tuple -from PIL import Image - from douyin.fudai.douyin_fudai_core import get_fudai_contain from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail @@ -112,8 +110,13 @@ def read_fudai_detail_with_retries( for attempt in range(max_attempts): attempt_start_time = time.time() - status, tup, extra = read_fudai_detail_once(analyser) + status, tup, extra = ( + _read_once_callback(analyser) + if callable(_read_once_callback) + else read_fudai_detail_once(analyser) + ) last_status = status + current_tuple: Optional[Tuple] = None if isinstance(tup, tuple) and len(tup) >= 6: current_tuple = tup[:6] # 计算当前倒计时秒数 @@ -253,7 +256,7 @@ def read_fudai_detail_with_retries( if ( status == "error" and isinstance(extra, dict) - and extra.get("reason") == "task_count_zero" + and extra.get("reason") in {"task_count_zero", "not_in_fudai_detail"} ): if attempt < max_attempts - 1: try: diff --git a/douyin/fudai/core/fudai_filter_pkg/join_decision.py b/douyin/fudai/core/fudai_filter_pkg/join_decision.py index 95f641d..f8ee248 100644 --- a/douyin/fudai/core/fudai_filter_pkg/join_decision.py +++ b/douyin/fudai/core/fudai_filter_pkg/join_decision.py @@ -238,6 +238,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: "已截止", ) if button_text and any(k in button_text for k in ended_keywords): + _emit_flow_flag( + analyser, + "join_decision", + "button_ended_skip", + button_text=button_text[:60], + ) try: analyser._log_kv( "参与", @@ -286,6 +292,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 关键防线:倒计时无效时,绝不进入参与分支(避免 OCR 失败被兜底秒数误触发参与) if not _has_valid_countdown(detail): + _emit_flow_flag( + analyser, + "join_decision", + "invalid_countdown_skip", + time_text=str(detail[1] or "") if len(detail) > 1 else "", + ) try: analyser._log_kv( "参与", @@ -310,6 +322,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: needswitch = True if not needswitch: + _emit_flow_flag(analyser, "join_decision", "single_room_direct_attend") try: analyser._log_kv( "参与", @@ -387,6 +400,14 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 执行筛选检查 skip, reason = should_skip_fudai_by_config(analyser, detail) + _emit_flow_flag( + analyser, + "join_decision", + "skip_eval_done", + skip=bool(skip), + reason=str(reason or ""), + is_high_value=bool(is_high_value), + ) # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值 # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则真实写入预约队列。 @@ -505,6 +526,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 检查是否是回退后强制参与 # 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约 if remain_seconds is not None and remain_seconds <= join_ahead_seconds: + _emit_flow_flag( + analyser, + "join_decision", + "high_value_force_attend_window", + remain_seconds=int(remain_seconds), + join_ahead_seconds=int(join_ahead_seconds), + ) try: analyser._log_kv( "参与", @@ -531,6 +559,15 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋 # no-op: 强制参与标志已删除 else: + _emit_flow_flag( + analyser, + "join_decision", + "high_value_record_reservation", + remain_seconds=( + int(remain_seconds) if remain_seconds is not None else None + ), + join_ahead_seconds=int(join_ahead_seconds), + ) # 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务 is_watch_task_check = False try: @@ -807,6 +844,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: needswitch_now = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch_now = True + _emit_flow_flag( + analyser, + "join_decision", + "reservation_recorded", + queue_len=len(getattr(analyser, "reservations", []) or []), + needswitch=bool(needswitch_now), + ) if needswitch_now: try: if hasattr(analyser, "swipe_up_to_next_live"): @@ -843,6 +887,11 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) except Exception: pass + _emit_flow_flag( + analyser, + "join_decision", + "reservation_switch_done", + ) except Exception as e_sw: # 立即切换失败时保留 _just_recorded_reservation,由下一轮兜底处理。 try: @@ -854,6 +903,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) except Exception: pass + _emit_flow_flag( + analyser, + "join_decision", + "reservation_switch_failed", + error_type=type(e_sw).__name__, + ) else: try: analyser._log_kv( @@ -862,6 +917,11 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) except Exception: pass + _emit_flow_flag( + analyser, + "join_decision", + "reservation_no_switch", + ) except Exception as e: try: analyser._log_kv( diff --git a/douyin/fudai/core/fudai_filter_pkg/should_skip.py b/douyin/fudai/core/fudai_filter_pkg/should_skip.py index b9ba3bd..6ace246 100644 --- a/douyin/fudai/core/fudai_filter_pkg/should_skip.py +++ b/douyin/fudai/core/fudai_filter_pkg/should_skip.py @@ -21,6 +21,20 @@ from .helpers import ( ) +def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None: + """输出统一流程标志,便于还原筛选判定链路。""" + try: + payload = { + "flag": str(flag or ""), + "status": str(status or ""), + "run_id": str(getattr(analyser, "_run_id", "") or ""), + } + payload.update(extra or {}) + analyser._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload) + except Exception: + pass + + def _is_valid_mmss_text(time_text: str) -> bool: """倒计时文本必须是合法 mm:ss。""" t = str(time_text or "").strip() @@ -53,6 +67,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str (skip, reason) 其中 reason 为简单文字原因,便于日志查看。 """ start_time = time.time() + _emit_flow_flag(analyser, "skip_filter", "start") # 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过 try: needswitch = bool(getattr(analyser, "needswitch", True)) @@ -70,6 +85,13 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str return False, "single_room_mode" if not isinstance(detail, tuple) or len(detail) < 6: + _emit_flow_flag( + analyser, + "skip_filter", + "detail_invalid", + detail_type=type(detail).__name__, + detail_len=(len(detail) if isinstance(detail, tuple) else -1), + ) return False, "detail_tuple_invalid" content = str(detail[0] or "") @@ -91,6 +113,13 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str "should_skip_fudai_by_config完成(观看任务)", elapsed_seconds=round(elapsed, 2), ) + _emit_flow_flag( + analyser, + "skip_filter", + "watch_task_skip", + reason="watch_task_detected", + elapsed_seconds=round(elapsed, 2), + ) return True, "watch_task_detected" time_text = str(detail[1] or "") @@ -517,6 +546,17 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str ) except Exception: pass + try: + _emit_flow_flag( + analyser, + "skip_filter", + "skip", + reason=str(preferred_reason or ""), + reasons="|".join([str(x) for x in skip_reasons]), + reason_count=len(skip_reasons), + ) + except Exception: + pass return True, preferred_reason # 所有条件都通过 @@ -538,6 +578,13 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str "should_skip_fudai_by_config完成(通过)", elapsed_seconds=round(elapsed, 2), ) + _emit_flow_flag( + analyser, + "skip_filter", + "pass", + elapsed_seconds=round(elapsed, 2), + remain_seconds=(int(remain_seconds) if remain_seconds is not None else None), + ) return False, "ok" diff --git a/douyin/fudai/douyin_fudai_contain_impl.py b/douyin/fudai/douyin_fudai_contain_impl.py index a83cec3..52adc38 100644 --- a/douyin/fudai/douyin_fudai_contain_impl.py +++ b/douyin/fudai/douyin_fudai_contain_impl.py @@ -14,7 +14,7 @@ from douyin.fudai.core.fudai_filter import ( # 从新模块导入调试工具函数 from douyin.fudai.core.fudai_debug_utils import ( - _save_full_screenshot_with_ocr_region, + save_fudai_detail_debug_overview, ) @@ -72,6 +72,108 @@ except Exception: # pyright: ignore # 模块级线程池状态,用于复用 OCR 并行执行,避免频繁创建/销毁 +def _detail_verbose_logs(analyser: Any) -> bool: + """福袋详情 OCR 的中间态日志开关;默认关闭,避免日志刷屏和重复。""" + try: + return bool(getattr(analyser, "fudai_detail_verbose_logs", False)) + except Exception: + return False + + +def _short_ocr_text(value: Any, limit: int = 80) -> str: + text = str(value or "").strip() + if not text: + return "未识别" + text = " ".join(text.split()) + if len(text) <= limit: + return text + return f"{text[:limit]}..." + + +def _format_enabled_ocr(ocr_switches: Any) -> str: + fields = ( + ("content", "内容"), + ("value", "价值"), + ("countdown", "倒计时"), + ("task", "任务"), + ("task_count", "任务数"), + ("button", "按钮"), + ("participants", "人数"), + ("live_title", "标题"), + ) + enabled = [] + for attr, label in fields: + try: + if bool(getattr(ocr_switches, attr, False)): + enabled.append(label) + except Exception: + continue + return ",".join(enabled) if enabled else "无" + + +def _slowest_ocr_task(durations: Dict[str, Any]) -> str: + if not durations: + return "" + try: + key, value = max( + durations.items(), + key=lambda item: float(item[1] or 0), + ) + return f"{key}:{round(float(value or 0), 1)}ms" + except Exception: + return "" + + +def _log_detail_ocr_summary( + analyser: Any, + *, + total_ms: float, + renwu: int, + ui_version: str, + task_count_source: str, + ocr_switches: Any, + durations: Dict[str, Any], + fudai_content_raw: Any, + task_list_raw: Any, + countdown_mm_raw: Any, + countdown_ss_raw: Any, + countdown_full_raw: Any, + value_raw: Any, + button_text_raw: Any, + button_status: Any, + live_room_title_raw: Any, + participants_raw: Any, + heavy_fields: Any, + fallback: bool = False, +) -> None: + """统一输出一条 OCR 摘要,替代分散的字段/耗时重复日志。""" + try: + mm, ss = _normalize_countdown_pair(countdown_mm_raw, countdown_ss_raw) + countdown = f"{mm}:{ss}" if mm and ss else _short_ocr_text(countdown_full_raw, 40) + heavy = ",".join(sorted(str(x) for x in (heavy_fields or []))) or "无" + payload = { + "ui_version": str(ui_version or "unknown"), + "task_count": int(renwu or 0), + "task_count_source": str(task_count_source or "unknown"), + "enabled_ocr": _format_enabled_ocr(ocr_switches), + "content": _short_ocr_text(fudai_content_raw), + "value": _short_ocr_text(value_raw, 40), + "countdown": countdown, + "task": _short_ocr_text(task_list_raw), + "button": _short_ocr_text(button_text_raw, 40), + "button_status": str(button_status or "未识别"), + "live_title": _short_ocr_text(live_room_title_raw, 60), + "participants": _short_ocr_text(participants_raw, 40), + "total_ms": round(float(total_ms or 0), 1), + "slowest_task": _slowest_ocr_task(durations), + "heavy_fields": heavy, + "fallback": bool(fallback), + } + analyser._log_kv("福袋详情", "OCR摘要", log_type="OCR_SUMMARY", **payload) + except Exception: + pass + + def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None: try: payload = { @@ -196,22 +298,7 @@ def _cut_countdown_candidate_regions( ss_x1 = min(x2 - 1, x1 + max(1, int(w * 0.38))) ss_x2 = min(x2, max(ss_x1 + 1, x1 + max(2, int(w * 0.64)))) - if save_debug_images: - try: - _save_full_screenshot_with_ocr_region( - analyser, - mm_name, - (mm_x1, digit_y1, mm_x2, digit_y2), - analyser.y_pianyi, - ) - _save_full_screenshot_with_ocr_region( - analyser, - ss_name, - (ss_x1, digit_y1, ss_x2, digit_y2), - analyser.y_pianyi, - ) - except Exception: - pass + _ = save_debug_images analyser.cut_pic( mm_x1, @@ -359,32 +446,33 @@ def _select_countdown_from_candidates( candidates, room_title_hint=room_title_hint, ) - try: - snapshot = [] - for cand in candidates: - box = cand.get("box") or () - snapshot.append( - { - "idx": int(cand.get("idx", -1) or -1), - "primary": bool(cand.get("is_primary")), - "mm_raw": str(cand.get("mm_raw") or ""), - "ss_raw": str(cand.get("ss_raw") or ""), - "mm": str(cand.get("mm") or ""), - "ss": str(cand.get("ss") or ""), - "valid": bool(cand.get("valid")), - "score": int(cand.get("score", 0) or 0), - "box": tuple(box)[:4], - } + if _detail_verbose_logs(analyser): + try: + snapshot = [] + for cand in candidates: + box = cand.get("box") or () + snapshot.append( + { + "idx": int(cand.get("idx", -1) or -1), + "primary": bool(cand.get("is_primary")), + "mm_raw": str(cand.get("mm_raw") or ""), + "ss_raw": str(cand.get("ss_raw") or ""), + "mm": str(cand.get("mm") or ""), + "ss": str(cand.get("ss") or ""), + "valid": bool(cand.get("valid")), + "score": int(cand.get("score", 0) or 0), + "box": tuple(box)[:4], + } + ) + analyser._log_kv( + "倒计时", + "倒计时候选评分", + room_title_hint=str(room_title_hint or "")[:40], + candidate_count=len(snapshot), + candidates=snapshot, ) - analyser._log_kv( - "倒计时", - "倒计时候选评分", - room_title_hint=str(room_title_hint or "")[:40], - candidate_count=len(snapshot), - candidates=snapshot, - ) - except Exception: - pass + except Exception: + pass if best and bool(best.get("valid")): mm_sel, ss_sel = _normalize_countdown_pair(best.get("mm"), best.get("ss")) if mm_sel and ss_sel: @@ -432,28 +520,102 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo force_light = ocr_mode == "light" force_heavy = ocr_mode == "heavy" + try: + from douyin.fudai.core.coords import get_fudai_detail_profile + from douyin.fudai.douyin_fudai_core_pkg.ocr_switches import ( + resolve_fudai_detail_ocr_switches_from_analyser, + ) + + ui_mode = str(getattr(analyser, "fudai_detail_ui_mode", "auto") or "auto") + profile = get_fudai_detail_profile(ui_mode, task_count=renwu) + ui_version = str(profile.get("version") or "legacy") + ocr_switches = resolve_fudai_detail_ocr_switches_from_analyser(analyser) + except Exception: + from douyin.fudai.core.coords import get_fudai_detail_profile + from douyin.fudai.douyin_fudai_core_pkg.ocr_switches import ( + FudaiDetailOcrSwitches, + ) + + ui_mode = "auto" + profile = get_fudai_detail_profile("auto", task_count=renwu) + ui_version = str(profile.get("version") or "v2_0") + ocr_switches = FudaiDetailOcrSwitches() + + try: + setattr(analyser, "fudai_detail_ui_version_active", ui_version) + setattr(analyser, "fudai_detail_ocr_enabled_fields", sorted(ocr_switches.enabled_fields())) + except Exception: + pass + # 切割直播间标题图片(用于并行 OCR) - from douyin.fudai.core.coords import LIVE_ROOM_TITLE, PARTICIPATE_BUTTON, TASK_LIST - analyser.cut_pic(*LIVE_ROOM_TITLE, "", "live_room_title_mid", analyser.y_pianyi) + detail_debug_regions: List[Dict[str, Any]] = [] + if ocr_switches.live_title: + live_title_box = tuple(profile.get("live_title") or (144, 144, 329, 185)) + detail_debug_regions.append( + { + "key": "live_title", + "name": "直播间标题", + "coords": live_title_box, + "enabled": bool(ocr_switches.live_title), + } + ) + analyser.cut_pic( + *live_title_box, + "", + "live_room_title_mid", + analyser.y_pianyi, + ) + else: + detail_debug_regions.append( + { + "key": "live_title", + "name": "直播间标题", + "coords": tuple(profile.get("live_title") or (144, 144, 329, 185)), + "enabled": False, + } + ) # 切割内容/倒计时/价值(按 renwu 选 countdown_box) from douyin.fudai.douyin_fudai_core_pkg.cut_regions import cut_detail_regions countdown_box = cut_detail_regions( - analyser, renwu, save_debug_images=save_debug_images + analyser, + renwu, + save_debug_images=save_debug_images, + profile=profile, + ocr_switches=ocr_switches, + ) + detail_debug_regions.extend( + [ + { + "key": "content", + "name": "内容", + "coords": tuple(profile.get("content") or (390, 1240, 980, 1470)), + "enabled": bool(ocr_switches.content), + }, + { + "key": "countdown", + "name": "倒计时", + "coords": tuple(countdown_box), + "enabled": bool(ocr_switches.countdown), + }, + { + "key": "value", + "name": "价值", + "coords": tuple(profile.get("value") or (390, 1500, 780, 1600)), + "enabled": bool(ocr_switches.value), + }, + ] ) # 额外整行倒计时图:用于优先解析 mm:ss,降低分钟框被文案污染的风险。 try: - if save_debug_images: - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_整行", countdown_box, analyser.y_pianyi - ) - analyser.cut_pic(*countdown_box, "", "福袋倒计时_整行", analyser.y_pianyi) + if ocr_switches.countdown: + analyser.cut_pic(*countdown_box, "", "福袋倒计时_整行", analyser.y_pianyi) except Exception: pass # 额外切割倒计时候选区域(用于并行多候选OCR,根治分钟框偏移) countdown_candidate_meta: List[Dict[str, Any]] = [] try: - candidate_boxes = _build_countdown_candidate_boxes(renwu) + candidate_boxes = [tuple(countdown_box)] if ui_version == "v2_0" else _build_countdown_candidate_boxes(renwu) for idx, box in enumerate(candidate_boxes): is_primary = (tuple(box) == tuple(countdown_box)) if is_primary: @@ -467,13 +629,14 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ss_name = f"福袋倒计时_候选{idx}_秒" mm_key = f"countdown_mm_c{idx}" ss_key = f"countdown_ss_c{idx}" - _cut_countdown_candidate_regions( + if ocr_switches.countdown: + _cut_countdown_candidate_regions( analyser, tuple(box), mm_name, ss_name, - save_debug_images=save_debug_images, - ) + save_debug_images=False, + ) countdown_candidate_meta.append( { @@ -500,14 +663,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ] # 准备任务列表区域的截图(用于并行OCR) - # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 try: # 保存任务列表区域的调试截图(仅在配置启用时) - if save_debug_images: - _save_full_screenshot_with_ocr_region( - analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi - ) - analyser.cut_pic(*TASK_LIST, "", "福袋任务列表", analyser.y_pianyi) + task_list_box = tuple(profile.get("task_list") or (50, 1621, 1032, 1960)) + detail_debug_regions.append( + { + "key": "task", + "name": "任务", + "coords": task_list_box, + "enabled": bool(ocr_switches.task), + } + ) + if ocr_switches.task: + analyser.cut_pic(*task_list_box, "", "福袋任务列表", analyser.y_pianyi) except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType] # 任务列表截图失败不影响后续流程,记录日志即可 try: @@ -522,11 +690,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 准备参与按钮区域的截图(用于并行OCR识别按钮状态) try: # 保存参与按钮区域的调试截图(仅在配置启用时) - if save_debug_images: - _save_full_screenshot_with_ocr_region( - analyser, "参与按钮", PARTICIPATE_BUTTON, analyser.y_pianyi - ) - analyser.cut_pic(*PARTICIPATE_BUTTON, "", "参与按钮", analyser.y_pianyi) + button_box = tuple(profile.get("button") or (306, 2030, 780, 2180)) + detail_debug_regions.append( + { + "key": "button", + "name": "按钮", + "coords": button_box, + "enabled": bool(ocr_switches.button), + } + ) + if ocr_switches.button: + analyser.cut_pic(*button_box, "", "参与按钮", analyser.y_pianyi) except Exception as e_inner: # pyright: ignore[reportTooBroadExceptionType] # 按钮截图失败不影响后续流程,记录日志即可 try: @@ -538,6 +712,40 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass + # 准备参与人数区域(默认关闭,仅开关开启时切图和OCR) + try: + participants_box = tuple(profile.get("participants") or ()) + if len(participants_box) == 4: + detail_debug_regions.append( + { + "key": "participants", + "name": "人数", + "coords": participants_box, + "enabled": bool(ocr_switches.participants), + } + ) + if ocr_switches.participants and len(participants_box) == 4: + analyser.cut_pic(*participants_box, "", "福袋参与人数", analyser.y_pianyi) + except Exception: + pass + + if save_debug_images: + try: + task_count_source = str( + getattr(analyser, "_fudai_detail_task_count_source", "") or "" + ) + save_fudai_detail_debug_overview( + analyser, + detail_debug_regions, + ui_version=ui_version, + ocr_enabled=sorted(ocr_switches.enabled_fields()), + task_count=int(renwu or 0), + task_count_source=task_count_source, + y_pianyi=analyser.y_pianyi, + ) + except Exception: + pass + # 并行执行六个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值/参与按钮 # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 ocr_start_time = time.time() @@ -547,17 +755,12 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_ss_raw = None value_raw = None button_text_raw = None + participants_raw = None # 并行子任务耗时收集(ms),由各子任务在 finally 中写入 perf_task_durations: Dict[str, float] = {} perf_task_lock = threading.Lock() - # 读取内容 OCR 配置开关(其它开关在 OcrTaskRunner 内部按需读取) - from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import _read_disable_flag - disable_content_recognition = _read_disable_flag( - analyser, - "fudai_disable_content_recognition", - "fudai_disable_content_recognition", - ) + disable_content_recognition = not bool(ocr_switches.content) # 7 个并行 OCR 子任务封装到 OcrTaskRunner from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import OcrTaskRunner @@ -586,15 +789,25 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo optimal_workers = get_optimal_workers() executor = _get_fudai_ocr_executor(optimal_workers) - task_funcs = { - "task_list": ocr_task_list, - "countdown_mm": ocr_countdown_mm, - "countdown_ss": ocr_countdown_ss, - "countdown_full": ocr_countdown_full, - "value": ocr_value, - "button": ocr_button, - "live_room_title": ocr_live_room_title, - } + task_funcs = {} + if ocr_switches.task: + task_funcs["task_list"] = ocr_task_list + if ocr_switches.countdown: + task_funcs["countdown_mm"] = ocr_countdown_mm + task_funcs["countdown_ss"] = ocr_countdown_ss + task_funcs["countdown_full"] = ocr_countdown_full + if ocr_switches.value: + task_funcs["value"] = ocr_value + if ocr_switches.button: + task_funcs["button"] = ocr_button + if ocr_switches.live_title: + task_funcs["live_room_title"] = ocr_live_room_title + if ocr_switches.participants: + task_funcs["participants"] = ( + lambda: analyser.operation.analyse_pic_word( + preprocess_for_ocr(analyser, "福袋参与人数"), 0 + ) + ) # 并行补充倒计时额外候选(保持并行,不降级) for meta in countdown_candidate_meta: if meta.get("is_primary"): @@ -605,29 +818,31 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ss_key = str(meta.get("ss_result_key") or "") if not mm_name or not ss_name or not mm_key or not ss_key: continue - task_funcs[mm_key] = ( - lambda name=mm_name: "".join( - ch - for ch in str( - analyser.operation.analyse_pic_digits(name, 0) or "" + if ocr_switches.countdown: + task_funcs[mm_key] = ( + lambda name=mm_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() ) - if ch.isdigit() ) - ) - task_funcs[ss_key] = ( - lambda name=ss_name: "".join( - ch - for ch in str( - analyser.operation.analyse_pic_digits(name, 0) or "" + task_funcs[ss_key] = ( + lambda name=ss_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() ) - if ch.isdigit() ) - ) # 如果配置启用,避免把 content 任务加入并行队列,彻底不调度该OCR - if not disable_content_recognition: + if ocr_switches.content: task_funcs["content"] = ocr_content task_list_raw = fudai_content_raw = countdown_mm_raw = None countdown_ss_raw = value_raw = None + participants_raw = None countdown_full_raw = None live_room_title_raw = live_room_title_text_raw = None @@ -649,12 +864,16 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo value_raw = res elif name == "button": button_text_raw = res + elif name == "participants": + participants_raw = res elif name == "live_room_title": live_room_title_raw, live_room_title_text_raw = res elif name.startswith("countdown_mm_c") or name.startswith("countdown_ss_c"): extra_countdown_results[name] = res try: + if not ocr_switches.countdown: + raise RuntimeError("countdown_ocr_disabled") countdown_mm_raw, countdown_ss_raw, picked = _select_countdown_from_candidates( analyser, countdown_candidate_meta, @@ -666,35 +885,37 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo mm_full, ss_full = _parse_mmss_from_full_text(countdown_full_raw) if mm_full and ss_full: countdown_mm_raw, countdown_ss_raw = mm_full, ss_full - try: - analyser._log_kv( - "倒计时", - "倒计时整行优先命中,覆盖分割候选结果", - full_text=str(countdown_full_raw or "")[:80], - mm=mm_full, - ss=ss_full, - ) - except Exception: - pass + if _detail_verbose_logs(analyser): + try: + analyser._log_kv( + "倒计时", + "倒计时整行优先命中,覆盖分割候选结果", + full_text=str(countdown_full_raw or "")[:80], + mm=mm_full, + ss=ss_full, + ) + except Exception: + pass if picked: picked_idx = int(picked.get("idx", -1)) - analyser._log_kv( - "倒计时", - ( - "倒计时候选选择结果" - f" idx={picked_idx}" - f" mm={str(picked.get('mm') or '')}" - f" ss={str(picked.get('ss') or '')}" - f" valid={bool(picked.get('valid'))}" - ), - chosen_idx=picked_idx, - chosen_is_primary=bool(picked.get("is_primary")), - chosen_mm=str(picked.get("mm") or ""), - chosen_ss=str(picked.get("ss") or ""), - chosen_score=int(picked.get("score", 0) or 0), - chosen_valid=bool(picked.get("valid")), - candidates=len(countdown_candidate_meta), - ) + if _detail_verbose_logs(analyser): + analyser._log_kv( + "倒计时", + ( + "倒计时候选选择结果" + f" idx={picked_idx}" + f" mm={str(picked.get('mm') or '')}" + f" ss={str(picked.get('ss') or '')}" + f" valid={bool(picked.get('valid'))}" + ), + chosen_idx=picked_idx, + chosen_is_primary=bool(picked.get("is_primary")), + chosen_mm=str(picked.get("mm") or ""), + chosen_ss=str(picked.get("ss") or ""), + chosen_score=int(picked.get("score", 0) or 0), + chosen_valid=bool(picked.get("valid")), + candidates=len(countdown_candidate_meta), + ) # 回写连续性状态:供下一次候选评分使用(同直播间递减约束)。 try: room_for_state = str(live_room_title_text_raw or live_room_title_raw or "").strip() @@ -706,48 +927,36 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass except Exception as e_pick: try: - analyser._log_kv( - "倒计时", - "倒计时候选选择异常,回退主候选", - error=str(e_pick), - error_type=type(e_pick).__name__, - level="WARNING", - ) + if str(e_pick) != "countdown_ocr_disabled": + analyser._log_kv( + "倒计时", + "倒计时候选选择异常,回退主候选", + error=str(e_pick), + error_type=type(e_pick).__name__, + level="WARNING", + ) except Exception: pass - try: - analyser._log_kv( - "性能", - "并行OCR子任务耗时(ms)", - **{f"ocr_{k}": v for k, v in durations.items()}, + if _detail_verbose_logs(analyser): + try: + analyser._log_kv( + "性能", + "并行OCR子任务耗时(ms)", + **{f"ocr_{k}": v for k, v in durations.items()}, + ) + except Exception: + pass + _emit_flow_flag( + analyser, + "fudai_contain_ocr", + "parallel_done", + has_content=bool(fudai_content_raw), + has_button=bool(button_text_raw), + has_countdown_mm=bool(countdown_mm_raw), + has_countdown_ss=bool(countdown_ss_raw), + has_countdown_full=bool(countdown_full_raw), ) - except Exception: - pass - _emit_flow_flag( - analyser, - "fudai_contain_ocr", - "parallel_done", - has_content=bool(fudai_content_raw), - has_button=bool(button_text_raw), - has_countdown_mm=bool(countdown_mm_raw), - has_countdown_ss=bool(countdown_ss_raw), - has_countdown_full=bool(countdown_full_raw), - ) - - # 输出一行紧凑的并行 OCR 汇总,便于日志聚合分析 - try: - total_ocr_ms = round((time.time() - ocr_start_time) * 1000, 1) - durations_str = ",".join(f"{k}={v}" for k, v in durations.items()) - import logging - - logging.info( - "[OCR汇总] total_ms=%.1f %s", - total_ocr_ms, - durations_str, - ) - except Exception: - pass # 轻重分流:轻量OCR跑完后,仅在缺字段或强制时补充重OCR try: @@ -763,9 +972,22 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ) except Exception: heavy_fields = set() + allowed_heavy_fields: set[str] = set() + if ocr_switches.content: + allowed_heavy_fields.add("content") + if ocr_switches.countdown: + allowed_heavy_fields.update({"countdown_mm", "countdown_ss"}) + if ocr_switches.value: + allowed_heavy_fields.add("value") + if ocr_switches.task: + allowed_heavy_fields.add("task_list") + if ocr_switches.button: + allowed_heavy_fields.add("button") + heavy_fields = set(heavy_fields) & allowed_heavy_fields if heavy_fields: heavy_res = run_heavy_ocr(analyser, heavy_fields) + picked_heavy = None def _prefer(new_val: Any, old_val: Any): return new_val if not is_blank_text(new_val) else old_val @@ -792,18 +1014,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_mm_raw, countdown_ss_raw = mm_full_h, ss_full_h if picked_heavy: picked_heavy_idx = int(picked_heavy.get("idx", -1)) - analyser._log_kv( - "倒计时", - ( - "重OCR后倒计时候选复选结果" - f" idx={picked_heavy_idx}" - f" mm={str(picked_heavy.get('mm') or '')}" - f" ss={str(picked_heavy.get('ss') or '')}" - f" valid={bool(picked_heavy.get('valid'))}" - ), - chosen_idx=picked_heavy_idx, - chosen_is_primary=bool(picked_heavy.get("is_primary")), - chosen_mm=str(picked_heavy.get("mm") or ""), + if _detail_verbose_logs(analyser): + analyser._log_kv( + "倒计时", + ( + "重OCR后倒计时候选复选结果" + f" idx={picked_heavy_idx}" + f" mm={str(picked_heavy.get('mm') or '')}" + f" ss={str(picked_heavy.get('ss') or '')}" + f" valid={bool(picked_heavy.get('valid'))}" + ), + chosen_idx=picked_heavy_idx, + chosen_is_primary=bool(picked_heavy.get("is_primary")), + chosen_mm=str(picked_heavy.get("mm") or ""), chosen_ss=str(picked_heavy.get("ss") or ""), chosen_score=int(picked_heavy.get("score", 0) or 0), chosen_valid=bool(picked_heavy.get("valid")), @@ -812,16 +1035,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass - try: - analyser._log_kv( - "性能", - "福袋详情OCR轻重分流:触发重OCR补齐", - mode=ocr_mode, - heavy_fields=sorted(list(heavy_fields)), - heavy_duration_ms=heavy_res.get("_duration_ms"), - ) - except Exception: - pass + if _detail_verbose_logs(analyser): + try: + analyser._log_kv( + "性能", + "福袋详情OCR轻重分流:触发重OCR补齐", + mode=ocr_mode, + heavy_fields=sorted(list(heavy_fields)), + heavy_duration_ms=heavy_res.get("_duration_ms"), + ) + except Exception: + pass # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if handle_task_list_watch_task(analyser, task_list_raw, fallback=False): @@ -831,14 +1055,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo button_status = None if button_text_raw: button_text = str(button_text_raw).strip() - try: - analyser._log_kv( - "参与", - "主并行OCR识别参与按钮", - button_text=button_text if button_text else "", - ) - except Exception: - pass + if _detail_verbose_logs(analyser): + try: + analyser._log_kv( + "参与", + "主并行OCR识别参与按钮", + button_text=button_text if button_text else "", + ) + except Exception: + pass button_status = decide_button_status(button_text) @@ -862,29 +1087,29 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ocr_elapsed = time.time() - ocr_start_time try: - analyser._log_kv( - "性能", - "并行OCR识别完成(任务数量已在前置检测中获取)", - elapsed_seconds=round(ocr_elapsed, 3), - task_count=renwu, - button_status=button_status or "未识别", + task_count_source = str( + getattr(analyser, "_fudai_detail_task_count_source", "") or "" + ) + _log_detail_ocr_summary( + analyser, + total_ms=ocr_elapsed * 1000, + renwu=renwu, + ui_version=ui_version, + task_count_source=task_count_source, + ocr_switches=ocr_switches, + durations=durations, + fudai_content_raw=fudai_content_raw, + task_list_raw=task_list_raw, + countdown_mm_raw=countdown_mm_raw, + countdown_ss_raw=countdown_ss_raw, + countdown_full_raw=countdown_full_raw, + value_raw=value_raw, + button_text_raw=button_text_raw, + button_status=button_status, + live_room_title_raw=live_room_title_raw, + participants_raw=participants_raw, + heavy_fields=heavy_fields, ) - # 输出所有OCR识别结果详情 - ocr_results = { - "福袋内容": fudai_content_raw[:100] if fudai_content_raw else "未识别", - "任务列表": task_list_raw[:100] if task_list_raw else "未识别", - "倒计时分钟": countdown_mm_raw if countdown_mm_raw else "未识别", - "倒计时秒": countdown_ss_raw if countdown_ss_raw else "未识别", - "倒计时整行": ( - str(countdown_full_raw)[:100] if countdown_full_raw else "未识别" - ), - "奖品价值": value_raw[:50] if value_raw else "未识别", - "按钮文本": button_text_raw if button_text_raw else "未识别", - "直播间标题": ( - live_room_title_raw[:100] if live_room_title_raw else "未识别" - ), - } - analyser._log_kv("详情", "并行OCR识别结果详情", **ocr_results) except Exception as e_inner: try: analyser._log_kv( @@ -961,14 +1186,21 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo optimal_workers = get_optimal_workers() executor = _get_fudai_ocr_executor(optimal_workers) - task_funcs = { - "task_list": ocr_task_list_fallback, - "countdown_mm": ocr_countdown_mm_fallback, - "countdown_ss": ocr_countdown_ss_fallback, - "countdown_full": ocr_countdown_full_fallback, - "value": ocr_value_fallback, - "button": ocr_button_fallback, - } + task_funcs = {} + if ocr_switches.task: + task_funcs["task_list"] = ocr_task_list_fallback + if ocr_switches.countdown: + task_funcs["countdown_mm"] = ocr_countdown_mm_fallback + task_funcs["countdown_ss"] = ocr_countdown_ss_fallback + task_funcs["countdown_full"] = ocr_countdown_full_fallback + if ocr_switches.value: + task_funcs["value"] = ocr_value_fallback + if ocr_switches.button: + task_funcs["button"] = ocr_button_fallback + if ocr_switches.participants: + task_funcs["participants"] = ( + lambda: analyser.operation.analyse_pic_word("福袋参与人数", 0) + ) # 备用并行中也加入倒计时额外候选 for meta in countdown_candidate_meta: if meta.get("is_primary"): @@ -979,30 +1211,32 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ss_key = str(meta.get("ss_result_key") or "") if not mm_name or not ss_name or not mm_key or not ss_key: continue - task_funcs[mm_key] = ( - lambda name=mm_name: "".join( - ch - for ch in str( - analyser.operation.analyse_pic_digits(name, 0) or "" + if ocr_switches.countdown: + task_funcs[mm_key] = ( + lambda name=mm_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() ) - if ch.isdigit() ) - ) - task_funcs[ss_key] = ( - lambda name=ss_name: "".join( - ch - for ch in str( - analyser.operation.analyse_pic_digits(name, 0) or "" + task_funcs[ss_key] = ( + lambda name=ss_name: "".join( + ch + for ch in str( + analyser.operation.analyse_pic_digits(name, 0) or "" + ) + if ch.isdigit() ) - if ch.isdigit() ) - ) # 如果配置允许,则加入备用 content OCR,否则不调度 - if not disable_content_recognition: + if ocr_switches.content: task_funcs["content"] = ocr_content_fallback durations = {} task_list_raw = fudai_content_raw = countdown_mm_raw = None countdown_ss_raw = value_raw = button_text_raw = None + participants_raw = None countdown_full_raw_fb = None results, durations = run_parallel_tasks(task_funcs, executor) extra_countdown_results_fb: Dict[str, Any] = {} @@ -1021,10 +1255,14 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo value_raw = res elif name == "button": button_text_raw = res + elif name == "participants": + participants_raw = res elif name.startswith("countdown_mm_c") or name.startswith("countdown_ss_c"): extra_countdown_results_fb[name] = res try: + if not ocr_switches.countdown: + raise RuntimeError("countdown_ocr_disabled") countdown_mm_raw, countdown_ss_raw, picked_fb = _select_countdown_from_candidates( analyser, countdown_candidate_meta, @@ -1040,23 +1278,24 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_mm_raw, countdown_ss_raw = mm_fb, ss_fb if picked_fb: picked_fb_idx = int(picked_fb.get("idx", -1)) - analyser._log_kv( - "倒计时", - ( - "备用并行倒计时候选选择结果" - f" idx={picked_fb_idx}" - f" mm={str(picked_fb.get('mm') or '')}" - f" ss={str(picked_fb.get('ss') or '')}" - f" valid={bool(picked_fb.get('valid'))}" - ), - chosen_idx=picked_fb_idx, - chosen_is_primary=bool(picked_fb.get("is_primary")), - chosen_mm=str(picked_fb.get("mm") or ""), - chosen_ss=str(picked_fb.get("ss") or ""), - chosen_score=int(picked_fb.get("score", 0) or 0), - chosen_valid=bool(picked_fb.get("valid")), - candidates=len(countdown_candidate_meta), - ) + if _detail_verbose_logs(analyser): + analyser._log_kv( + "倒计时", + ( + "备用并行倒计时候选选择结果" + f" idx={picked_fb_idx}" + f" mm={str(picked_fb.get('mm') or '')}" + f" ss={str(picked_fb.get('ss') or '')}" + f" valid={bool(picked_fb.get('valid'))}" + ), + chosen_idx=picked_fb_idx, + chosen_is_primary=bool(picked_fb.get("is_primary")), + chosen_mm=str(picked_fb.get("mm") or ""), + chosen_ss=str(picked_fb.get("ss") or ""), + chosen_score=int(picked_fb.get("score", 0) or 0), + chosen_valid=bool(picked_fb.get("valid")), + candidates=len(countdown_candidate_meta), + ) try: mm_state, ss_state = _normalize_countdown_pair(countdown_mm_raw, countdown_ss_raw) room_for_state = str( @@ -1067,17 +1306,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser._last_countdown_total_seconds = int(mm_state) * 60 + int(ss_state) except Exception: pass - except Exception: - pass + except Exception as e_fb_pick: + if str(e_fb_pick) != "countdown_ocr_disabled": + pass - try: - analyser._log_kv( - "性能", - "备用并行OCR子任务耗时(ms)", - **{f"ocr_{k}": v for k, v in durations.items()}, - ) - except Exception: - pass + if _detail_verbose_logs(analyser): + try: + analyser._log_kv( + "性能", + "备用并行OCR子任务耗时(ms)", + **{f"ocr_{k}": v for k, v in durations.items()}, + ) + except Exception: + pass # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if handle_task_list_watch_task(analyser, task_list_raw, fallback=True): @@ -1087,14 +1328,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo button_status = None if button_text_raw: button_text = str(button_text_raw).strip() - try: - analyser._log_kv( - "参与", - "备用并行OCR识别参与按钮", - button_text=button_text if button_text else "", - ) - except Exception: - pass + if _detail_verbose_logs(analyser): + try: + analyser._log_kv( + "参与", + "备用并行OCR识别参与按钮", + button_text=button_text if button_text else "", + ) + except Exception: + pass button_status = decide_button_status(button_text) @@ -1111,9 +1353,37 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo value_raw=value_raw, live_room_title_raw=live_room_title_raw, log_prefix="备用", + record_room_pos=True, ) except Exception: pass + try: + task_count_source = str( + getattr(analyser, "_fudai_detail_task_count_source", "") or "" + ) + _log_detail_ocr_summary( + analyser, + total_ms=(time.time() - ocr_start_time) * 1000, + renwu=renwu, + ui_version=ui_version, + task_count_source=task_count_source, + ocr_switches=ocr_switches, + durations=durations, + fudai_content_raw=fudai_content_raw, + task_list_raw=task_list_raw, + countdown_mm_raw=countdown_mm_raw, + countdown_ss_raw=countdown_ss_raw, + countdown_full_raw=countdown_full_raw_fb, + value_raw=value_raw, + button_text_raw=button_text_raw, + button_status=button_status, + live_room_title_raw=live_room_title_raw, + participants_raw=participants_raw, + heavy_fields=set(), + fallback=True, + ) + except Exception: + pass except Exception: pass @@ -1124,6 +1394,14 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo participants, copies, fudai_content_text = extract_participants_and_clean( fudai_content_raw if fudai_content_raw is not None else "" ) + if ocr_switches.participants: + participants_only, copies_from_participants, _cleaned_participants = ( + extract_participants_and_clean(participants_raw or "") + ) + if participants_only: + participants = participants_only + if copies_from_participants and not copies: + copies = copies_from_participants # 清理后再次检查观看任务 if handle_content_watch_task(analyser, fudai_content_text, cleaned=True): diff --git a/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py b/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py index 7a080d5..f3d7ced 100644 --- a/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py +++ b/douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py @@ -25,11 +25,16 @@ def extract_participants_and_clean(text: str): m = re.search(r"共(\d+)份", compact) if m: copies = int(m.group(1)) - m = re.search(r"(\d+)人已参与", compact) + m = re.search(r"(\d+(?:\.\d+)?)万人已参与", compact) if m: - participants = int(m.group(1)) + participants = int(float(m.group(1)) * 10000) + else: + m = re.search(r"(\d+)人已参与", compact) + if m: + participants = int(m.group(1)) cleaned = re.sub(r"共\d+份", "", compact) + cleaned = re.sub(r"\d+(?:\.\d+)?万人已参与", "", cleaned) cleaned = re.sub(r"\d+人已参与", "", cleaned) return participants, copies, cleaned @@ -70,4 +75,3 @@ def run_heavy_ocr(analyser, fields: set[str]) -> Dict[str, Any]: from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import run_heavy_ocr as _impl return _impl(analyser, fields) - diff --git a/douyin/fudai/douyin_fudai_core_pkg/countdown_split.py b/douyin/fudai/douyin_fudai_core_pkg/countdown_split.py index 5e08472..46182e5 100644 --- a/douyin/fudai/douyin_fudai_core_pkg/countdown_split.py +++ b/douyin/fudai/douyin_fudai_core_pkg/countdown_split.py @@ -43,18 +43,11 @@ def read_countdown_split( Args: analyser: fudai_analyse 实例(提供 cut_pic / operation / _log_kv / y_pianyi) box: 倒计时区域 (x1, y1, x2, y2) - save_debug_images: 是否保存调试截图(仅当全局开关启用时) + save_debug_images: 兼容旧签名;详情页调试图由主流程统一保存一张总览图 Returns: mm:ss 字符串(识别成功),空字符串(识别失败) """ - try: - from douyin.fudai.core.fudai_debug_utils import ( - _save_full_screenshot_with_ocr_region, - ) - except Exception: - _save_full_screenshot_with_ocr_region = None # type: ignore[assignment] - try: from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore except Exception: @@ -69,33 +62,7 @@ def read_countdown_split( seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - # 保存调试截图(仅在配置启用时) - if save_debug_images and _save_full_screenshot_with_ocr_region is not None: - try: - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_分钟", - (x1, y1, x1 + seg1, y2), - analyser.y_pianyi, - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - except Exception as e_inner: - try: - analyser._log_kv( - "错误", - "保存倒计时调试截图失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - box=box, - level="WARNING", - ) - except Exception: - pass + _ = save_debug_images # 切割分钟区域(左侧) analyser.cut_pic( diff --git a/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py b/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py index c1aa81c..7bb2420 100644 --- a/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py +++ b/douyin/fudai/douyin_fudai_core_pkg/cut_regions.py @@ -5,7 +5,7 @@ """ from __future__ import annotations -from typing import Tuple, Optional +from typing import Any, Mapping, Tuple def _select_countdown_box(renwu: int) -> Tuple[int, int, int, int]: @@ -30,6 +30,8 @@ def cut_detail_regions( renwu: int, *, save_debug_images: bool = False, + profile: Mapping[str, Any] | None = None, + ocr_switches: Any = None, ) -> Tuple[int, int, int, int]: """根据 renwu 切割福袋详情的"内容/倒计时分钟/倒计时秒/价值"4 个区域。 @@ -38,34 +40,29 @@ def cut_detail_regions( Args: analyser: fudai_analyse 实例(提供 cut_pic / y_pianyi) renwu: 任务数量(1/2/3,其它视为默认) - save_debug_images: 是否保存全屏带 OCR 区域标注的调试截图 + save_debug_images: 兼容旧签名;详情页调试图由主流程统一保存一张总览图 Returns: countdown_box: 选中的倒计时区域 (x1, y1, x2, y2),供后续 _read_countdown_split 使用 """ - from douyin.fudai.core.coords import ( - VALUE_BOX_TARGET, - CONTENT_BOX, + from douyin.fudai.core.coords import CONTENT_BOX, VALUE_BOX_TARGET + profile_map = dict(profile or {}) + countdown_box = tuple( + profile_map.get("countdown_full") or _select_countdown_box(renwu) ) - try: - from douyin.fudai.core.fudai_debug_utils import ( - _save_full_screenshot_with_ocr_region, - ) - except Exception: - _save_full_screenshot_with_ocr_region = None # type: ignore[assignment] - - countdown_box = _select_countdown_box(renwu) - value_box = VALUE_BOX_TARGET + content_box = tuple(profile_map.get("content") or CONTENT_BOX) + value_box = tuple(profile_map.get("value") or VALUE_BOX_TARGET) + content_enabled = bool(getattr(ocr_switches, "content", True)) + countdown_enabled = bool(getattr(ocr_switches, "countdown", True)) + value_enabled = bool(getattr(ocr_switches, "value", True)) # 1. 福袋内容 - if save_debug_images and _save_full_screenshot_with_ocr_region is not None: - try: - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi - ) - except Exception: - pass - analyser.cut_pic(*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi) + _ = save_debug_images + if content_enabled: + analyser.cut_pic(*content_box, "", "福袋内容", analyser.y_pianyi) + + if not countdown_enabled: + return countdown_box # 2. 倒计时区域分割(与候选切图保持一致,避免分钟框吃到前缀噪声) x1, y1, x2, y2 = countdown_box @@ -79,16 +76,6 @@ def cut_detail_regions( ss_x1 = min(x2 - 1, x1 + max(1, int(w * 0.38))) ss_x2 = min(x2, max(ss_x1 + 1, x1 + max(2, int(w * 0.64)))) - if save_debug_images and _save_full_screenshot_with_ocr_region is not None: - try: - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_分钟", - (mm_x1, digit_y1, mm_x2, digit_y2), - analyser.y_pianyi, - ) - except Exception: - pass analyser.cut_pic( mm_x1, digit_y1, @@ -99,16 +86,6 @@ def cut_detail_regions( analyser.y_pianyi, ) - if save_debug_images and _save_full_screenshot_with_ocr_region is not None: - try: - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (ss_x1, digit_y1, ss_x2, digit_y2), - analyser.y_pianyi, - ) - except Exception: - pass analyser.cut_pic( ss_x1, digit_y1, @@ -120,13 +97,7 @@ def cut_detail_regions( ) # 3. 福袋价值 - if save_debug_images and _save_full_screenshot_with_ocr_region is not None: - try: - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", value_box, analyser.y_pianyi - ) - except Exception: - pass - analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) + if value_enabled: + analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) return countdown_box diff --git a/douyin/fudai/douyin_fudai_core_pkg/ocr_switches.py b/douyin/fudai/douyin_fudai_core_pkg/ocr_switches.py new file mode 100644 index 0000000..8abf942 --- /dev/null +++ b/douyin/fudai/douyin_fudai_core_pkg/ocr_switches.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping + + +OCR_SWITCH_DEFAULTS = { + "content": True, + "value": True, + "countdown": True, + "task": True, + "task_count": True, + "button": True, + "participants": False, + "live_title": True, +} + +OCR_SWITCH_CONFIG_KEYS = { + "content": "fudai_detail_ocr_content_enabled", + "value": "fudai_detail_ocr_value_enabled", + "countdown": "fudai_detail_ocr_countdown_enabled", + "task": "fudai_detail_ocr_task_enabled", + "task_count": "fudai_detail_ocr_task_count_enabled", + "button": "fudai_detail_ocr_button_enabled", + "participants": "fudai_detail_ocr_participants_enabled", + "live_title": "fudai_detail_ocr_live_title_enabled", +} + + +@dataclass(frozen=True) +class FudaiDetailOcrSwitches: + content: bool = True + value: bool = True + countdown: bool = True + task: bool = True + task_count: bool = True + button: bool = True + participants: bool = False + live_title: bool = True + + def enabled_fields(self) -> set[str]: + return { + field + for field in OCR_SWITCH_DEFAULTS + if bool(getattr(self, field, False)) + } + + +def _coerce_bool(value: Any, default: bool) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return bool(value) + if value is None: + return default + text = str(value).strip().lower() + if text in ("1", "true", "yes", "on", "y"): + return True + if text in ("0", "false", "no", "off", "n", ""): + return False + return default + + +def resolve_fudai_detail_ocr_switches( + cfg: Mapping[str, Any] | None, +) -> FudaiDetailOcrSwitches: + cfg_map = cfg or {} + values = dict(OCR_SWITCH_DEFAULTS) + + # Backward compatibility: legacy "disable" keys only apply when the new + # field-level switch is absent. + if OCR_SWITCH_CONFIG_KEYS["content"] not in cfg_map: + values["content"] = not _coerce_bool( + cfg_map.get("fudai_disable_content_recognition"), False + ) + if OCR_SWITCH_CONFIG_KEYS["task"] not in cfg_map: + values["task"] = not _coerce_bool( + cfg_map.get("fudai_disable_task_recognition"), False + ) + + for field, key in OCR_SWITCH_CONFIG_KEYS.items(): + if key in cfg_map: + values[field] = _coerce_bool(cfg_map.get(key), values[field]) + + return FudaiDetailOcrSwitches(**values) + + +def resolve_fudai_detail_ocr_switches_from_analyser( + analyser: Any, +) -> FudaiDetailOcrSwitches: + cfg: dict[str, Any] = {} + for field, key in OCR_SWITCH_CONFIG_KEYS.items(): + if hasattr(analyser, key): + cfg[key] = getattr(analyser, key) + for legacy_key in ( + "fudai_disable_content_recognition", + "fudai_disable_task_recognition", + ): + if hasattr(analyser, legacy_key): + cfg[legacy_key] = getattr(analyser, legacy_key) + + try: + import json + import os + + from douyin.core import path_config + + cfg_path = path_config.get_config_path() + if os.path.exists(cfg_path): + with open(cfg_path, "r", encoding="utf-8") as f: + file_cfg = json.load(f) + if isinstance(file_cfg, dict): + for field, key in OCR_SWITCH_CONFIG_KEYS.items(): + if key not in cfg and key in file_cfg: + cfg[key] = file_cfg[key] + for legacy_key in ( + "fudai_disable_content_recognition", + "fudai_disable_task_recognition", + ): + if legacy_key not in cfg and legacy_key in file_cfg: + cfg[legacy_key] = file_cfg[legacy_key] + except Exception: + pass + + return resolve_fudai_detail_ocr_switches(cfg) diff --git a/douyin/fudai/douyin_fudai_core_pkg/ocr_tasks.py b/douyin/fudai/douyin_fudai_core_pkg/ocr_tasks.py index 5f0bc73..14b9b94 100644 --- a/douyin/fudai/douyin_fudai_core_pkg/ocr_tasks.py +++ b/douyin/fudai/douyin_fudai_core_pkg/ocr_tasks.py @@ -28,6 +28,9 @@ _BUTTON_KEYWORDS = ( "评论", "参与抽奖", "开始观看", + "一键发表评论", + "发表评论", + "已参与", "参与", "加入粉丝团", "粉丝团", diff --git a/douyin/handlers/douyin_screenshot_handler.py b/douyin/handlers/douyin_screenshot_handler.py index 24053a4..9cca6fa 100644 --- a/douyin/handlers/douyin_screenshot_handler.py +++ b/douyin/handlers/douyin_screenshot_handler.py @@ -98,8 +98,9 @@ class ScreenshotHandler: label: 标签(用于文件名) """ try: - base_dir = os.path.dirname(__file__) - pic_dir = os.path.join(base_dir, "pic") + from douyin.core import path_config + + pic_dir = path_config.get_pic_dir() # 确保有最新截图 try: analyser.operation.get_screenshot(analyser.device_id, use_service=False) diff --git a/douyin/logging/action_logger.py b/douyin/logging/action_logger.py index 7ee9135..daf6b70 100644 --- a/douyin/logging/action_logger.py +++ b/douyin/logging/action_logger.py @@ -76,20 +76,24 @@ if not _logger.handlers: class ActionLogger: def log_operation(self, operation: str, details: Optional[str] = None, **kwargs: Any) -> None: - elapsed = kwargs.pop("elapsed", None) - if elapsed is None: - elapsed = 0.0 - try: - # 统一保留两位小数,便于日志阅读 - elapsed_val = float(elapsed) - except Exception: - elapsed_val = 0.0 - elapsed_rounded = round(elapsed_val, 2) + extra = dict(kwargs) + elapsed = None + if "elapsed" in extra: + elapsed = extra.pop("elapsed") + elif "elapsed_seconds" in extra: + elapsed = extra.pop("elapsed_seconds") + + elapsed_val = None + if elapsed is not None: + try: + # 统一保留两位小数,便于日志阅读 + elapsed_val = round(float(elapsed), 2) + extra["elapsed_seconds"] = elapsed_val + except Exception: + elapsed_val = None # 标记异常慢的操作(阈值可调整) - extra = dict(kwargs) - extra["elapsed_seconds"] = elapsed_rounded - if elapsed_val >= 10.0: + if elapsed_val is not None and elapsed_val >= 10.0: extra["slow"] = 1 msg = format_action_log(operation, details or "", **extra) diff --git a/douyin/logging/douyin_logging_pkg/cleanup.py b/douyin/logging/douyin_logging_pkg/cleanup.py index 3f70f05..278c836 100644 --- a/douyin/logging/douyin_logging_pkg/cleanup.py +++ b/douyin/logging/douyin_logging_pkg/cleanup.py @@ -15,6 +15,8 @@ import time from datetime import datetime, timedelta from typing import Any, Dict +from douyin.core import path_config + def compress_log_file(log_file: str) -> bool: """压缩单个日志文件 diff --git a/douyin/logging/douyin_logging_pkg/config.py b/douyin/logging/douyin_logging_pkg/config.py index 476f62b..11166e8 100644 --- a/douyin/logging/douyin_logging_pkg/config.py +++ b/douyin/logging/douyin_logging_pkg/config.py @@ -9,6 +9,7 @@ """ from __future__ import annotations +import glob import inspect import logging import logging.handlers diff --git a/douyin/logging/douyin_logging_pkg/monitor.py b/douyin/logging/douyin_logging_pkg/monitor.py index f5141e7..d5c0c03 100644 --- a/douyin/logging/douyin_logging_pkg/monitor.py +++ b/douyin/logging/douyin_logging_pkg/monitor.py @@ -13,11 +13,15 @@ import os import threading import time from datetime import datetime -from typing import Any, Dict, Optional +from typing import Any, Callable, Dict, Optional from douyin.core import path_config from . import _common as _state +from .cleanup import ( + _load_logging_cleanup_policy_from_config, + cleanup_old_logs, +) class LogRotationMonitor: @@ -257,7 +261,7 @@ def stop_log_monitor() -> None: if _state._log_monitor: _state._log_monitor.stop() - _log_monitor = None + _state._log_monitor = None @@ -327,12 +331,3 @@ def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]: pass return stats - - -# 自动配置日志(在模块导入时) -if not _state._logging_configured: - # 延迟配置,避免在导入时读取 config.json 失败 - try: - configure_logging() - except Exception: - pass diff --git a/douyin/logging/douyin_logging_wrapper_pkg/detailed.py b/douyin/logging/douyin_logging_wrapper_pkg/detailed.py index 8002173..517b3ad 100644 --- a/douyin/logging/douyin_logging_wrapper_pkg/detailed.py +++ b/douyin/logging/douyin_logging_wrapper_pkg/detailed.py @@ -183,6 +183,11 @@ def _enhanced_log_kv_detailed( if "elapsed_ms" in fields_clean: elapsed_seconds = float(fields_clean.get("elapsed_ms", 0)) / 1000.0 elapsed_str = f"耗时:{elapsed_seconds:.2f}s" + elif "total_elapsed_ms" in fields_clean: + elapsed_seconds = ( + float(fields_clean.get("total_elapsed_ms", 0)) / 1000.0 + ) + elapsed_str = f"耗时:{elapsed_seconds:.2f}s" elif "total_ms" in fields_clean: elapsed_seconds = float(fields_clean.get("total_ms", 0)) / 1000.0 elapsed_str = f"耗时:{elapsed_seconds:.2f}s" diff --git a/douyin/logging/douyin_logging_wrapper_pkg/simple.py b/douyin/logging/douyin_logging_wrapper_pkg/simple.py index 25bf012..99be083 100644 --- a/douyin/logging/douyin_logging_wrapper_pkg/simple.py +++ b/douyin/logging/douyin_logging_wrapper_pkg/simple.py @@ -122,6 +122,10 @@ def _enhanced_log_kv_simple( elapsed_seconds = ( float(fields.get("elapsed_ms", 0)) / 1000.0 ) + elif "total_elapsed_ms" in fields: + elapsed_seconds = ( + float(fields.get("total_elapsed_ms", 0)) / 1000.0 + ) elif "total_ms" in fields: elapsed_seconds = ( float(fields.get("total_ms", 0)) / 1000.0 diff --git a/douyin/other/douyin_high_value_room.py b/douyin/other/douyin_high_value_room.py index b7395ff..acc3359 100644 --- a/douyin/other/douyin_high_value_room.py +++ b/douyin/other/douyin_high_value_room.py @@ -67,8 +67,11 @@ def _save_high_value_rooms(data: Dict[str, Any]) -> None: """保存高价值房间数据""" try: HIGH_VALUE_ROOMS_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(HIGH_VALUE_ROOMS_PATH, "w", encoding="utf-8") as f: + tmp_path = HIGH_VALUE_ROOMS_PATH.with_suffix(HIGH_VALUE_ROOMS_PATH.suffix + ".tmp") + with open(tmp_path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) + f.write("\n") + os.replace(tmp_path, HIGH_VALUE_ROOMS_PATH) except Exception: pass diff --git a/douyin/other/douyin_popups.py b/douyin/other/douyin_popups.py index 2521ef1..12352e7 100644 --- a/douyin/other/douyin_popups.py +++ b/douyin/other/douyin_popups.py @@ -2,7 +2,6 @@ from __future__ import annotations import os import time -from PIL import Image from douyin.detection import douyin_pixel @@ -35,6 +34,7 @@ def check_coupon_popup(analyser) -> bool: from douyin.core import path_config pic_path = path_config.get_screenshot_path() + from PIL import Image pic = Image.open(pic_path) try: pic.load() # Force load to catch truncated files early @@ -70,6 +70,17 @@ def check_coupon_popup(analyser) -> bool: pass return False + if not bool(getattr(analyser, "ocr_coupon_popup_enabled", True)): + try: + analyser._log_kv( + "彈窗檢測步驟", + "優惠券-OCR確認已關閉,信任模板匹配結果", + 模板匹配耗時秒=f"{template_elapsed:.3f}", + ) + except Exception: + pass + return True + # 步骤2:OCR兜底确认(检测"开心收下"按钮) # 使用与"粉丝团加入"相同的区域:(200, 1940)-(880, 2140) ocr_start = time.time() @@ -198,6 +209,12 @@ def check_shopping_redpacket_popup(analyser) -> bool: # 步驟0:快速像素檢測中央紅色彈窗背景 pixel_check_start = time.time() has_popup_pixel = False + if not bool(getattr(analyser, "pixel_detect_shopping_redpacket_enabled", False)): + try: + analyser._log_kv("購物紅包檢測", "購物紅包像素檢測已關閉") + except Exception: + pass + return False try: # 使用统一的截图路径配置 try: @@ -209,6 +226,7 @@ def check_shopping_redpacket_popup(analyser) -> bool: from douyin.core import path_config pic_path = path_config.get_screenshot_path() + from PIL import Image pic = Image.open(pic_path) try: pic.load() # Force load to catch truncated files early @@ -251,6 +269,13 @@ def check_shopping_redpacket_popup(analyser) -> bool: _ = time.time() - pixel_check_start has_popup_pixel = False + if not bool(getattr(analyser, "ocr_shopping_redpacket_enabled", False)): + try: + analyser._log_kv("購物紅包檢測", "購物紅包OCR已關閉,跳過OCR確認") + except Exception: + pass + return False + # 步驟1:截圖檢測區域 cut_start = time.time() try: diff --git a/douyin/reservation/douyin_reservation_handler_pkg/dump_state.py b/douyin/reservation/douyin_reservation_handler_pkg/dump_state.py index 2deab74..b49a2ca 100644 --- a/douyin/reservation/douyin_reservation_handler_pkg/dump_state.py +++ b/douyin/reservation/douyin_reservation_handler_pkg/dump_state.py @@ -16,6 +16,7 @@ from douyin.core import path_config from douyin.fudai import douyin_fudai_detail from douyin.handlers import douyin_swipe_handler from douyin.reservation import douyin_reservation_logic +from douyin.reservation.reservation_logic import _normalize_room_title_for_matching # 错误处理工具占位(与原文件保持兼容降级) try: @@ -48,6 +49,95 @@ def _dump_room_pos_map_to_state(analyser: Any) -> None: final_path = os.path.join(state_dir, "room_pos_map.json") tmp_path = final_path + ".tmp" + # 先按直播间标题归一化做一次合并(防止重复直播间散落在不同位置) + # 保留原则:优先保留 room_pos 较小(更靠前)的一条;如果其后有 has_fudai=True 的记录则补齐信息。 + try: + merged_by_title: dict[str, tuple[str, Any]] = {} + for k_raw, v_raw in (room_pos_map or {}).items(): + k = str(k_raw) + if isinstance(v_raw, dict): + t = str(v_raw.get("title", "") or "").strip() + tr = str(v_raw.get("title_raw", "") or "").strip() + else: + try: + t = str(v_raw[0] or "").strip() if len(v_raw) > 0 else "" + tr = str(v_raw[1] or "").strip() if len(v_raw) > 1 else "" + except Exception: + t, tr = "", "" + title_norm = _normalize_room_title_for_matching(t or tr) + if not title_norm: + continue + old = merged_by_title.get(title_norm) + if old is None: + merged_by_title[title_norm] = (k, v_raw) + continue + old_k, old_v = old + try: + old_pos = int(old_k) + except Exception: + old_pos = 10**9 + try: + new_pos = int(k) + except Exception: + new_pos = 10**9 + keep_old = old_pos <= new_pos + base_k, base_v = (old_k, old_v) if keep_old else (k, v_raw) + ext_v = v_raw if keep_old else old_v + if isinstance(base_v, dict) and isinstance(ext_v, dict): + if (not base_v.get("has_fudai", False)) and bool(ext_v.get("has_fudai", False)): + base_v["has_fudai"] = True + if ext_v.get("fudai_content"): + base_v["fudai_content"] = ext_v.get("fudai_content") + if ext_v.get("fudai_detail"): + base_v["fudai_detail"] = ext_v.get("fudai_detail") + try: + base_v["merged_positions"] = sorted( + list( + set( + list(base_v.get("merged_positions", []) or []) + + [int(old_k) if str(old_k).isdigit() else old_k, int(k) if str(k).isdigit() else k] + ) + ), + key=lambda x: int(x) if str(x).isdigit() else str(x), + ) + except Exception: + pass + merged_by_title[title_norm] = (base_k, base_v) + + # 构造合并后的 room_pos_map(保留未能归一化标题的条目) + if merged_by_title: + keep_keys = {kk for kk, _ in merged_by_title.values()} + new_map = {} + for kk, vv in (room_pos_map or {}).items(): + kks = str(kk) + if kks in keep_keys: + continue + # 若条目本身无标题归一化(例如空标题),保留 + if isinstance(vv, dict): + t0 = str(vv.get("title", "") or "").strip() + tr0 = str(vv.get("title_raw", "") or "").strip() + else: + try: + t0 = str(vv[0] or "").strip() if len(vv) > 0 else "" + tr0 = str(vv[1] or "").strip() if len(vv) > 1 else "" + except Exception: + t0, tr0 = "", "" + if not _normalize_room_title_for_matching(t0 or tr0): + new_map[kk] = vv + for kk, vv in merged_by_title.values(): + try: + key_obj = int(kk) if str(kk).isdigit() else kk + except Exception: + key_obj = kk + new_map[key_obj] = vv + room_pos_map = new_map + try: + analyser._room_pos_to_title_map = room_pos_map + except Exception: + pass + except Exception: + pass + # 过滤并保留映射: # - 对于 dict 条目(新格式),保留完整 dict(以便包含 fudai_detail 等字段) # - 对于旧格式 list/tuple,保持原有行为(写入 [title, title_raw]) diff --git a/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py b/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py index 27af1ba..9d7e0d5 100644 --- a/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py +++ b/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py @@ -16,6 +16,7 @@ from douyin.core import path_config from douyin.fudai import douyin_fudai_detail from douyin.handlers import douyin_swipe_handler from douyin.reservation import douyin_reservation_logic +from .dump_state import _dump_room_pos_map_to_state # 错误处理工具占位(与原文件保持兼容降级) try: diff --git a/douyin/reservation/reservation_logic/add.py b/douyin/reservation/reservation_logic/add.py index 8e6ecae..c456b4f 100644 --- a/douyin/reservation/reservation_logic/add.py +++ b/douyin/reservation/reservation_logic/add.py @@ -9,6 +9,7 @@ import time from typing import Any, Callable, Dict, List, Optional from ._common import ( + _RESERVATION_ERROR_UTILS_AVAILABLE, ReservationItem, format_reservation_context, log_reservation_error, diff --git a/douyin/reservation/reservation_logic/attend_window.py b/douyin/reservation/reservation_logic/attend_window.py index 9f0bf3b..ed6f262 100644 --- a/douyin/reservation/reservation_logic/attend_window.py +++ b/douyin/reservation/reservation_logic/attend_window.py @@ -10,11 +10,13 @@ import time from typing import Any, Callable, Dict, List, Optional from ._common import ( + _RESERVATION_ERROR_UTILS_AVAILABLE, ReservationItem, format_reservation_context, log_reservation_error, safe_write_state, ) +from .cleanup_validate import cleanup_expired_reservations from .helpers import ( _calculate_string_similarity, _extract_content_core, @@ -277,6 +279,22 @@ def process_reservation_attend_window( ft = float(target.get("future_ts") or 0.0) except Exception: ft = 0.0 + try: + target_room_title = str(target.get("room_title") or "") + except Exception: + target_room_title = "" + try: + target_room_title_raw = str(target.get("room_title_raw") or "") + except Exception: + target_room_title_raw = "" + try: + target_content = str(target.get("content") or "") + except Exception: + target_content = "" + try: + target_value = float(target.get("prize_value_yuan") or 0.0) + except Exception: + target_value = 0.0 if pop_if_already_participated( analyser, diff --git a/douyin/stage/douyin_stage_handler_pkg/ocr_detection.py b/douyin/stage/douyin_stage_handler_pkg/ocr_detection.py index 658763a..c9f4e5d 100644 --- a/douyin/stage/douyin_stage_handler_pkg/ocr_detection.py +++ b/douyin/stage/douyin_stage_handler_pkg/ocr_detection.py @@ -52,22 +52,27 @@ def detect_pages_via_ocr( def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore return str(picname) - log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)") - # 购物红包 OCR 复查(不在直播间也必须执行) - redpacket_result = _check_redpacket_ocr_when_not_in_live_room( - analyser, - pixel_state, - pixel_details, - diag_start, - max_step_time, - enable_ocr_mode1, - preprocess_for_ocr, - log, - log_summary, - ) - if redpacket_result is not None: - return redpacket_result + if bool(getattr(analyser, "ocr_shopping_redpacket_enabled", False)): + redpacket_result = _check_redpacket_ocr_when_not_in_live_room( + analyser, + pixel_state, + pixel_details, + diag_start, + max_step_time, + enable_ocr_mode1, + preprocess_for_ocr, + log, + log_summary, + ) + if redpacket_result is not None: + return redpacket_result + + if not bool(getattr(analyser, "ocr_stage_page_enabled", True)): + log("OCR页面检测已关闭,跳过推荐页/关注页/直播列表OCR") + return None + + log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)") # 步骤 3:OCR 推荐页/关注列表/直播列表标签栏 step_start = time.time() diff --git a/douyin/utils/douyin_config.py b/douyin/utils/douyin_config.py index 8575bd6..0a27e71 100644 --- a/douyin/utils/douyin_config.py +++ b/douyin/utils/douyin_config.py @@ -182,6 +182,22 @@ class ConfigManager: analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35 ) + for key, default in { + "pixel_detect_fudai_icon_enabled": True, + "pixel_detect_coupon_popup_enabled": True, + "pixel_detect_shopping_redpacket_enabled": False, + "pixel_detect_lottery_result_enabled": True, + "pixel_detect_attend_button_enabled": True, + "pixel_detect_fansclub_join_enabled": True, + "pixel_detect_fudai_detail_enabled": True, + "pixel_detect_live_room_enabled": True, + "ocr_lottery_result_enabled": True, + "ocr_coupon_popup_enabled": True, + "ocr_shopping_redpacket_enabled": False, + "ocr_stage_page_enabled": True, + }.items(): + setattr(analyser, key, bool(config.get(key, default))) + # 粉丝团等待/点击延迟配置 if "fansclub_click_delay" in config: analyser.fansclub_click_delay = float(config["fansclub_click_delay"] or 0.6) @@ -349,9 +365,41 @@ class ConfigManager: threshold = float(config["fudai_template_match_threshold"] or 0.7) analyser.fudai_template_match_threshold = max(0.0, min(1.0, threshold)) + if "fudai_detail_ui_mode" in config: + try: + from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode + + analyser.fudai_detail_ui_mode = normalize_fudai_detail_ui_mode( + config.get("fudai_detail_ui_mode") + ) + except Exception: + analyser.fudai_detail_ui_mode = "auto" + + for key, default in { + "fudai_detail_ocr_content_enabled": True, + "fudai_detail_ocr_value_enabled": True, + "fudai_detail_ocr_countdown_enabled": True, + "fudai_detail_ocr_task_enabled": True, + "fudai_detail_ocr_task_count_enabled": True, + "fudai_detail_ocr_button_enabled": True, + "fudai_detail_ocr_participants_enabled": False, + "fudai_detail_ocr_live_title_enabled": True, + }.items(): + if key in config: + setattr(analyser, key, bool(config.get(key, default))) + if "y_pianyi" in config: analyser.y_pianyi = int(config["y_pianyi"] or 0) + if "reenter_live_entry_mode" in config: + try: + mode = str(config["reenter_live_entry_mode"] or "follow_list").strip().lower() + except Exception: + mode = "follow_list" + if mode not in ("follow_list", "screen_center"): + mode = "follow_list" + analyser.reenter_live_entry_mode = mode + if "enable_whole_detail_ocr" in config: analyser.enable_whole_detail_ocr = bool(config["enable_whole_detail_ocr"]) diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index 3252aa9..864dd6c 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -115,10 +115,22 @@ class HelperFunctions: None - 未识别到相关文本 """ try: - # OCR区域:(175, 1200) 到 (890, 1377) - 向上扩展了识别区域 + if not bool(getattr(analyser, "ocr_lottery_result_enabled", True)): + try: + analyser._log_kv("开奖结果", "开奖结果OCR已关闭,跳过识别") + except Exception: + pass + return None + + from douyin.fudai.core.coords import get_lottery_result_confirm_profile + + profile = get_lottery_result_confirm_profile( + getattr(analyser, "fudai_detail_ui_mode", "auto") + ) + x1, y1, x2, y2 = tuple(profile.get("button") or (181, 1261, 890, 1389)) # 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures) douyin_screenshot_handler.ScreenshotHandler.cut_pic( - analyser, 175, 1200, 890, 1377, "", "开奖结果按钮", 0 + analyser, x1, y1, x2, y2, "", "开奖结果按钮", 0 ) # OCR识别 @@ -268,11 +280,17 @@ class HelperFunctions: try: if result_type == "我知道了": # 识别到"我知道了",点击按钮,切换下一个直播间 + from douyin.fudai.core.coords import get_lottery_result_confirm_profile + + profile = get_lottery_result_confirm_profile( + getattr(analyser, "fudai_detail_ui_mode", "auto") + ) + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - # 按钮位置在OCR区域中心附近 (175+890)/2=532, (1200+1377)/2=1288.5≈1289 - btn_x = int(532 * rx // 1080) - btn_y = int(1289 * ry // 2400) + click_x, click_y = tuple(profile.get("click") or (532, 1289)) + btn_x = int(click_x * rx // 1080) + btn_y = int(click_y * ry // 2400) # OCR识别到结果,执行实际点击并等待生效 try: diff --git a/douyin/utils/douyin_utils.py b/douyin/utils/douyin_utils.py index 2d8002b..c0b8109 100644 --- a/douyin/utils/douyin_utils.py +++ b/douyin/utils/douyin_utils.py @@ -175,7 +175,7 @@ def extract_prize_value_yuan(text: str) -> float: values: list[float] = [] for idx, ch in enumerate(s): - if ch != "¥": + if ch not in ("¥", "¥"): continue j = idx + 1 while j < len(s) and s[j].isspace(): diff --git a/douyin/utils/ocr_preprocess.py b/douyin/utils/ocr_preprocess.py index 9fe7694..781d695 100644 --- a/douyin/utils/ocr_preprocess.py +++ b/douyin/utils/ocr_preprocess.py @@ -26,6 +26,14 @@ def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str: return cut_pic_name src = get_cut_pic_path(cut_pic_name) + if cut_pic_name in { + "福袋内容", + "福袋任务列表", + "参与按钮", + "live_room_title_mid", + "福袋倒计时_整行", + }: + return cut_pic_name pre_name = f"{cut_pic_name}_preprocessed" dst = get_cut_pic_path(pre_name) diff --git a/gui/components/action_buttons.py b/gui/components/action_buttons.py index e6e5e1b..f07c3ed 100644 --- a/gui/components/action_buttons.py +++ b/gui/components/action_buttons.py @@ -34,13 +34,25 @@ def setup_action_buttons( params = get_params() wait_display = "∞" if params.wait_minutes == 0 else f"{params.wait_minutes}m" + try: + from gui.gui_core import read_config + + cfg_now = read_config() or {} + entry_mode = str( + cfg_now.get("reenter_live_entry_mode", "follow_list") + or "follow_list" + ).strip().lower() + except Exception: + entry_mode = "follow_list" on_line( f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} " f"needswitch={params.needswitch} wait={wait_display} " f"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} " f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] " f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} " - f"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only" + f"fudai_find_max={params.fudai_find_max_attempts} " + f"entry_mode={entry_mode} " + f"yanghao=recommend_flow_only" ) status_var.set("运行中") try: diff --git a/gui/components/config_io.py b/gui/components/config_io.py index 187c6ec..9446d8d 100644 --- a/gui/components/config_io.py +++ b/gui/components/config_io.py @@ -59,6 +59,12 @@ def load_config_to_ui( vars_["reset_after_swipes_action_var"].set( str(cfg.get("reset_after_swipes_action", "swipe") or "swipe") ) + try: + vars_["reenter_live_entry_mode_var"].set( + str(cfg.get("reenter_live_entry_mode", "follow_list") or "follow_list") + ) + except Exception: + vars_["reenter_live_entry_mode_var"].set("follow_list") vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True))) vars_["swipe_down_back_enabled_var"].set( bool(cfg.get("swipe_down_back_enabled", False)) @@ -139,6 +145,20 @@ def load_config_to_ui( vars_["fudai_disable_task_recognition_var"].set( bool(cfg.get("fudai_disable_task_recognition", False)) ) + vars_["fudai_detail_ui_mode_var"].set( + str(cfg.get("fudai_detail_ui_mode", "auto") or "auto") + ) + for key, default in { + "fudai_detail_ocr_content_enabled": True, + "fudai_detail_ocr_value_enabled": True, + "fudai_detail_ocr_countdown_enabled": True, + "fudai_detail_ocr_task_enabled": True, + "fudai_detail_ocr_task_count_enabled": True, + "fudai_detail_ocr_button_enabled": True, + "fudai_detail_ocr_participants_enabled": False, + "fudai_detail_ocr_live_title_enabled": True, + }.items(): + vars_[f"{key}_var"].set(bool(cfg.get(key, default))) try: vars_["fudai_exit_after_misses_var"].set( int(cfg.get("fudai_exit_after_misses", 30) or 30) @@ -155,6 +175,12 @@ def load_config_to_ui( ) except Exception: vars_["reset_after_swipes_action_var"].set("swipe") + try: + vars_["reenter_live_entry_mode_var"].set( + str(cfg.get("reenter_live_entry_mode", "follow_list")) + ) + except Exception: + vars_["reenter_live_entry_mode_var"].set("follow_list") vars_["switch_room_wait_after_stage_diag_seconds_var"].set( float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0) ) @@ -184,6 +210,21 @@ def load_config_to_ui( bool(cfg.get("logging", {}).get("stage_diag_verbose", True)) ) vars_["enable_ocr_mode1_var"].set(bool(cfg.get("enable_ocr_mode1", False))) + for key, default in { + "pixel_detect_fudai_icon_enabled": True, + "pixel_detect_coupon_popup_enabled": True, + "pixel_detect_shopping_redpacket_enabled": False, + "pixel_detect_lottery_result_enabled": True, + "pixel_detect_attend_button_enabled": True, + "pixel_detect_fansclub_join_enabled": True, + "pixel_detect_fudai_detail_enabled": True, + "pixel_detect_live_room_enabled": True, + "ocr_lottery_result_enabled": True, + "ocr_coupon_popup_enabled": True, + "ocr_shopping_redpacket_enabled": False, + "ocr_stage_page_enabled": True, + }.items(): + vars_[f"{key}_var"].set(bool(cfg.get(key, default))) vars_["fudai_template_match_enabled_var"].set( bool(cfg.get("fudai_template_match_enabled", False)) ) @@ -385,12 +426,28 @@ def save_ui_to_config( cfg2["reset_after_swipes_action"] = str( vars_["reset_after_swipes_action_var"].get() or "swipe" ) + cfg2["reenter_live_entry_mode"] = str( + vars_["reenter_live_entry_mode_var"].get() or "follow_list" + ).strip().lower() cfg2["fudai_disable_content_recognition"] = bool( vars_["fudai_disable_content_recognition_var"].get() ) cfg2["fudai_disable_task_recognition"] = bool( vars_["fudai_disable_task_recognition_var"].get() ) + ui_mode = str(vars_["fudai_detail_ui_mode_var"].get() or "auto").strip().lower() + cfg2["fudai_detail_ui_mode"] = ui_mode if ui_mode in ("auto", "legacy", "v2_0") else "auto" + for key in ( + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_value_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_live_title_enabled", + ): + cfg2[key] = bool(vars_[f"{key}_var"].get()) cfg2["switch_room_wait_after_stage_diag_seconds"] = float( vars_["switch_room_wait_after_stage_diag_seconds_var"].get() or 7.0 ) @@ -408,6 +465,21 @@ def save_ui_to_config( vars_["stage_diag_max_step_time_var"].get() or 2.0 ) cfg2["enable_ocr_mode1"] = bool(vars_["enable_ocr_mode1_var"].get()) + for key in ( + "pixel_detect_fudai_icon_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_shopping_redpacket_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_live_room_enabled", + "ocr_lottery_result_enabled", + "ocr_coupon_popup_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", + ): + cfg2[key] = bool(vars_[f"{key}_var"].get()) cfg2["fudai_template_match_enabled"] = bool( vars_["fudai_template_match_enabled_var"].get() ) diff --git a/gui/components/config_vars.py b/gui/components/config_vars.py index 4ec8669..163644a 100644 --- a/gui/components/config_vars.py +++ b/gui/components/config_vars.py @@ -42,6 +42,9 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: reset_after_swipes_action_var = tk.StringVar( value=str(cfg.get("reset_after_swipes_action", "swipe") or "swipe") ) + reenter_live_entry_mode_var = tk.StringVar( + value=str(cfg.get("reenter_live_entry_mode", "follow_list") or "follow_list") + ) enable_back_on_misses_var = tk.BooleanVar( value=bool(cfg.get("enable_back_on_misses", True)) ) @@ -124,6 +127,33 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: fudai_disable_task_recognition_var = tk.BooleanVar( value=bool(cfg.get("fudai_disable_task_recognition", False)) ) + fudai_detail_ui_mode_var = tk.StringVar( + value=str(cfg.get("fudai_detail_ui_mode", "auto") or "auto") + ) + fudai_detail_ocr_content_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_content_enabled", True)) + ) + fudai_detail_ocr_value_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_value_enabled", True)) + ) + fudai_detail_ocr_countdown_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_countdown_enabled", True)) + ) + fudai_detail_ocr_task_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_task_enabled", True)) + ) + fudai_detail_ocr_task_count_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_task_count_enabled", True)) + ) + fudai_detail_ocr_button_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_button_enabled", True)) + ) + fudai_detail_ocr_participants_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_participants_enabled", False)) + ) + fudai_detail_ocr_live_title_enabled_var = tk.BooleanVar( + value=bool(cfg.get("fudai_detail_ocr_live_title_enabled", True)) + ) fudai_exit_after_misses_var = tk.IntVar( value=int(cfg.get("fudai_exit_after_misses", 30) or 30) ) @@ -256,6 +286,18 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: value=bool(cfg.get("logging", {}).get("stage_diag_verbose", True)) ) enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False))) + pixel_detect_fudai_icon_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_fudai_icon_enabled", True))) + pixel_detect_coupon_popup_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_coupon_popup_enabled", True))) + pixel_detect_shopping_redpacket_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_shopping_redpacket_enabled", False))) + pixel_detect_lottery_result_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_lottery_result_enabled", True))) + pixel_detect_attend_button_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_attend_button_enabled", True))) + pixel_detect_fansclub_join_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_fansclub_join_enabled", True))) + pixel_detect_fudai_detail_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_fudai_detail_enabled", True))) + pixel_detect_live_room_enabled_var = tk.BooleanVar(value=bool(cfg.get("pixel_detect_live_room_enabled", True))) + ocr_lottery_result_enabled_var = tk.BooleanVar(value=bool(cfg.get("ocr_lottery_result_enabled", True))) + ocr_coupon_popup_enabled_var = tk.BooleanVar(value=bool(cfg.get("ocr_coupon_popup_enabled", True))) + ocr_shopping_redpacket_enabled_var = tk.BooleanVar(value=bool(cfg.get("ocr_shopping_redpacket_enabled", False))) + ocr_stage_page_enabled_var = tk.BooleanVar(value=bool(cfg.get("ocr_stage_page_enabled", True))) fudai_template_match_enabled_var = tk.BooleanVar( value=bool(cfg.get("fudai_template_match_enabled", False)) ) @@ -422,6 +464,7 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: "reset_after_swipes_enabled_var": reset_after_swipes_enabled_var, "reset_after_swipes_var": reset_after_swipes_var, "reset_after_swipes_action_var": reset_after_swipes_action_var, + "reenter_live_entry_mode_var": reenter_live_entry_mode_var, "streaming_enabled_var": streaming_enabled_var, "auto_join_var": auto_join_var, "fansclub_action_var": fansclub_action_var, @@ -449,6 +492,15 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: "fudai_icon_max_wait_seconds_var": fudai_icon_max_wait_seconds_var, "fudai_disable_content_recognition_var": fudai_disable_content_recognition_var, "fudai_disable_task_recognition_var": fudai_disable_task_recognition_var, + "fudai_detail_ui_mode_var": fudai_detail_ui_mode_var, + "fudai_detail_ocr_content_enabled_var": fudai_detail_ocr_content_enabled_var, + "fudai_detail_ocr_value_enabled_var": fudai_detail_ocr_value_enabled_var, + "fudai_detail_ocr_countdown_enabled_var": fudai_detail_ocr_countdown_enabled_var, + "fudai_detail_ocr_task_enabled_var": fudai_detail_ocr_task_enabled_var, + "fudai_detail_ocr_task_count_enabled_var": fudai_detail_ocr_task_count_enabled_var, + "fudai_detail_ocr_button_enabled_var": fudai_detail_ocr_button_enabled_var, + "fudai_detail_ocr_participants_enabled_var": fudai_detail_ocr_participants_enabled_var, + "fudai_detail_ocr_live_title_enabled_var": fudai_detail_ocr_live_title_enabled_var, "fudai_exit_after_misses_var": fudai_exit_after_misses_var, "fudai_click_wait_seconds_var": fudai_click_wait_seconds_var, "switch_room_wait_after_stage_diag_seconds_var": switch_room_wait_after_stage_diag_seconds_var, @@ -496,6 +548,18 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: "stage_diag_max_step_time_var": stage_diag_max_step_time_var, "stage_diag_verbose_var": stage_diag_verbose_var, "enable_ocr_mode1_var": enable_ocr_mode1_var, + "pixel_detect_fudai_icon_enabled_var": pixel_detect_fudai_icon_enabled_var, + "pixel_detect_coupon_popup_enabled_var": pixel_detect_coupon_popup_enabled_var, + "pixel_detect_shopping_redpacket_enabled_var": pixel_detect_shopping_redpacket_enabled_var, + "pixel_detect_lottery_result_enabled_var": pixel_detect_lottery_result_enabled_var, + "pixel_detect_attend_button_enabled_var": pixel_detect_attend_button_enabled_var, + "pixel_detect_fansclub_join_enabled_var": pixel_detect_fansclub_join_enabled_var, + "pixel_detect_fudai_detail_enabled_var": pixel_detect_fudai_detail_enabled_var, + "pixel_detect_live_room_enabled_var": pixel_detect_live_room_enabled_var, + "ocr_lottery_result_enabled_var": ocr_lottery_result_enabled_var, + "ocr_coupon_popup_enabled_var": ocr_coupon_popup_enabled_var, + "ocr_shopping_redpacket_enabled_var": ocr_shopping_redpacket_enabled_var, + "ocr_stage_page_enabled_var": ocr_stage_page_enabled_var, "fudai_template_match_enabled_var": fudai_template_match_enabled_var, "fudai_template_match_threshold_var": fudai_template_match_threshold_var, "fudai_detail_template_threshold_var": fudai_detail_template_threshold_var, diff --git a/gui/components/debug_tab.py b/gui/components/debug_tab.py index b94a9d5..07378df 100644 --- a/gui/components/debug_tab.py +++ b/gui/components/debug_tab.py @@ -223,6 +223,44 @@ def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> t offvalue=False, ).pack(side=LEFT, padx=(12, 0)) + row4ocr_mode = ttk.Frame(fudai_find_box) + row4ocr_mode.pack(fill=X, padx=10, pady=(0, 8)) + ttk.Label(row4ocr_mode, text="福袋详情页UI版本:").pack(side=LEFT) + ttk.Combobox( + row4ocr_mode, + textvariable=vars_["fudai_detail_ui_mode_var"], + values=("auto", "legacy", "v2_0"), + width=10, + state="readonly", + ).pack(side=LEFT) + ttk.Label(row4ocr_mode, text="(auto优先2.0,失败保留旧版回退)").pack( + side=LEFT, padx=(6, 0) + ) + + row4ocr1 = ttk.Frame(fudai_find_box) + row4ocr1.pack(fill=X, padx=10, pady=(0, 8)) + for label, var_name in ( + ("内容OCR", "fudai_detail_ocr_content_enabled_var"), + ("价值OCR", "fudai_detail_ocr_value_enabled_var"), + ("倒计时OCR", "fudai_detail_ocr_countdown_enabled_var"), + ("任务OCR", "fudai_detail_ocr_task_enabled_var"), + ("任务数量OCR", "fudai_detail_ocr_task_count_enabled_var"), + ): + ttk.Checkbutton(row4ocr1, text=label, variable=vars_[var_name]).pack( + side=LEFT, padx=(0, 10) + ) + + row4ocr2 = ttk.Frame(fudai_find_box) + row4ocr2.pack(fill=X, padx=10, pady=(0, 8)) + for label, var_name in ( + ("按钮文案OCR", "fudai_detail_ocr_button_enabled_var"), + ("人数OCR(默认关)", "fudai_detail_ocr_participants_enabled_var"), + ("直播间标题OCR(默认开)", "fudai_detail_ocr_live_title_enabled_var"), + ): + ttk.Checkbutton(row4ocr2, text=label, variable=vars_[var_name]).pack( + side=LEFT, padx=(0, 10) + ) + row4e = ttk.Frame(fudai_find_box) row4e.pack(fill=X, padx=10, pady=(0, 8)) ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT) @@ -400,8 +438,44 @@ def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> t pixel_detect_box = ttk.LabelFrame(debug_container, text="像素检测阈值") pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10)) + pixel_switch_r0 = ttk.Frame(pixel_detect_box) + pixel_switch_r0.pack(fill=X, padx=10, pady=(10, 6)) + for label, var_name in ( + ("福袋icon", "pixel_detect_fudai_icon_enabled_var"), + ("优惠券", "pixel_detect_coupon_popup_enabled_var"), + ("购物红包(默认关)", "pixel_detect_shopping_redpacket_enabled_var"), + ("开奖结果", "pixel_detect_lottery_result_enabled_var"), + ): + ttk.Checkbutton(pixel_switch_r0, text=label, variable=vars_[var_name]).pack( + side=LEFT, padx=(0, 10) + ) + + pixel_switch_r1 = ttk.Frame(pixel_detect_box) + pixel_switch_r1.pack(fill=X, padx=10, pady=(0, 6)) + for label, var_name in ( + ("参与按钮", "pixel_detect_attend_button_enabled_var"), + ("粉丝团", "pixel_detect_fansclub_join_enabled_var"), + ("福袋详情", "pixel_detect_fudai_detail_enabled_var"), + ("直播间", "pixel_detect_live_room_enabled_var"), + ): + ttk.Checkbutton(pixel_switch_r1, text=label, variable=vars_[var_name]).pack( + side=LEFT, padx=(0, 10) + ) + + ocr_switch_r0 = ttk.Frame(pixel_detect_box) + ocr_switch_r0.pack(fill=X, padx=10, pady=(0, 10)) + for label, var_name in ( + ("开奖结果OCR", "ocr_lottery_result_enabled_var"), + ("优惠券OCR", "ocr_coupon_popup_enabled_var"), + ("购物红包OCR(默认关)", "ocr_shopping_redpacket_enabled_var"), + ("页面OCR", "ocr_stage_page_enabled_var"), + ): + ttk.Checkbutton(ocr_switch_r0, text=label, variable=vars_[var_name]).pack( + side=LEFT, padx=(0, 10) + ) + pixel_r1 = ttk.Frame(pixel_detect_box) - pixel_r1.pack(fill=X, padx=10, pady=(10, 6)) + pixel_r1.pack(fill=X, padx=10, pady=(0, 6)) ttk.Label(pixel_r1, text="参与按钮红色占比阈值:").pack(side=LEFT) ttk.Spinbox( pixel_r1, diff --git a/gui/components/run_tab.py b/gui/components/run_tab.py index f2bb290..6515a95 100644 --- a/gui/components/run_tab.py +++ b/gui/components/run_tab.py @@ -70,6 +70,22 @@ def setup_run_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk ).pack(side=LEFT, padx=(6, 0)) ttk.Label(r2_5, text="(滑动次数重置时的回退方法)").pack(side=LEFT, padx=(6, 0)) + r2_6 = ttk.Frame(run_box) + r2_6.pack(fill=X, padx=10, pady=(0, 10)) + ttk.Label(r2_6, text="进入直播间坐标模式:").pack(side=LEFT) + mode_combo = ttk.Combobox( + r2_6, + values=["follow_list", "screen_center"], + textvariable=vars_["reenter_live_entry_mode_var"], + state="readonly", + width=14, + ) + mode_combo.pack(side=LEFT, padx=(6, 0)) + ttk.Label( + r2_6, + text="(follow_list=关注列表坐标,screen_center=屏幕中心)", + ).pack(side=LEFT, padx=(6, 0)) + # r3: 启用返回键回退(单独一行) r3 = ttk.Frame(run_box) r3.pack(fill=X, padx=10, pady=(0, 6)) diff --git a/gui/components/wifi_adb_dialog.py b/gui/components/wifi_adb_dialog.py index 1e10b19..bd876b8 100644 --- a/gui/components/wifi_adb_dialog.py +++ b/gui/components/wifi_adb_dialog.py @@ -143,6 +143,27 @@ def open_wifi_adb_dialog( button_frame = ttk.Frame(dialog) button_frame.pack(fill=X, padx=10, pady=10) + # 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮) + is_maximized = False + original_geometry = None + + def toggle_maximize(): + nonlocal is_maximized, original_geometry + try: + if not is_maximized: + original_geometry = dialog.geometry() + dialog.update_idletasks() + w = int(dialog.winfo_screenwidth() * 0.8) + h = int(dialog.winfo_screenheight() * 0.8) + dialog.geometry(f"{w}x{h}") + is_maximized = True + else: + if original_geometry: + dialog.geometry(original_geometry) + is_maximized = False + except Exception as e: + on_line(f"[WiFi ADB] 切换窗口大小失败: {e}") + def enable_wifi(): device_id = usb_device_var.get() if not device_id: @@ -284,27 +305,6 @@ def open_wifi_adb_dialog( # 在后台线程中执行自动连接 threading.Thread(target=do_auto_connect, daemon=True).start() - # 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮) - is_maximized = False - original_geometry = None - - def toggle_maximize(): - nonlocal is_maximized, original_geometry - try: - if not is_maximized: - original_geometry = dialog.geometry() - dialog.update_idletasks() - w = int(dialog.winfo_screenwidth() * 0.8) - h = int(dialog.winfo_screenheight() * 0.8) - dialog.geometry(f"{w}x{h}") - is_maximized = True - else: - if original_geometry: - dialog.geometry(original_geometry) - is_maximized = False - except Exception as e: - on_line(f"[WiFi ADB] 切换窗口大小失败: {e}") - def refresh_device_lists(): """刷新设备列表""" nonlocal usb_devices, wifi_devices diff --git a/gui/gui_core.py b/gui/gui_core.py index 3d76ff0..95c4e17 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -345,6 +345,17 @@ class Runner: self._emit_line(f"[错误] 设备选择失败: {e}") raise + # 进入直播间坐标模式:从最新配置读取,避免扩展 RunParams 字段影响现有调用方 + try: + cfg_now = read_config() or {} + reenter_mode = str( + cfg_now.get("reenter_live_entry_mode", "follow_list") or "follow_list" + ).strip().lower() + if reenter_mode in ("follow_list", "screen_center"): + cmd += ["--reenter-live-entry-mode", reenter_mode] + except Exception: + pass + try: p = subprocess.Popen( cmd, diff --git a/gui/gui_core_pkg/config.py b/gui/gui_core_pkg/config.py index 22cc996..3c495ce 100644 --- a/gui/gui_core_pkg/config.py +++ b/gui/gui_core_pkg/config.py @@ -12,10 +12,12 @@ from __future__ import annotations import json import os import shutil +import threading from douyin.core import path_config CONFIG_PATH = path_config.get_config_path() +_CONFIG_WRITE_LOCK = threading.RLock() def read_config() -> dict: @@ -30,21 +32,33 @@ def read_config() -> dict: def write_config(cfg: dict) -> None: # GUI 表单通常只生成“已知字段”的子集;直接覆盖写会丢失其它键(例如 ROI rect/poly 等扩展配置)。 # 这里做一次 merge:保留原配置中的未知键,再用新 cfg 覆盖同名键。 - merged = {} - try: - merged = read_config() - if not isinstance(merged, dict): - merged = {} - except Exception: + def _deep_merge(base: dict, incoming: dict) -> dict: + merged = dict(base) + for key, value in incoming.items(): + if isinstance(value, dict) and isinstance(merged.get(key), dict): + merged[key] = _deep_merge(merged[key], value) + else: + merged[key] = value + return merged + + with _CONFIG_WRITE_LOCK: merged = {} - try: - if isinstance(cfg, dict): - merged.update(cfg) - except Exception: - pass - with open(CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(merged, f, ensure_ascii=False, indent=4) - f.write("\n") + try: + merged = read_config() + if not isinstance(merged, dict): + merged = {} + except Exception: + merged = {} + try: + if isinstance(cfg, dict): + merged = _deep_merge(merged, cfg) + except Exception: + pass + tmp_path = CONFIG_PATH + ".tmp" + with open(tmp_path, "w", encoding="utf-8") as f: + json.dump(merged, f, ensure_ascii=False, indent=4) + f.write("\n") + os.replace(tmp_path, CONFIG_PATH) # ============================================================ @@ -104,19 +118,22 @@ def set_last_wifi_target(target: str, model: str = "") -> None: def clear_last_wifi_target() -> None: """从配置里删除 last_wifi_target 记录。""" - try: - cfg = read_config() - except Exception: - return - if not isinstance(cfg, dict) or _LAST_WIFI_KEY not in cfg: - return - try: - cfg.pop(_LAST_WIFI_KEY, None) - # write_config 会做 merge,但 merge 不删键,所以这里直接覆盖写 - with open(CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(cfg, f, ensure_ascii=False, indent=4) - f.write("\n") - except Exception: - pass + with _CONFIG_WRITE_LOCK: + try: + cfg = read_config() + except Exception: + return + if not isinstance(cfg, dict) or _LAST_WIFI_KEY not in cfg: + return + try: + cfg.pop(_LAST_WIFI_KEY, None) + # write_config 会做 merge,但 merge 不删键,所以这里直接覆盖写 + tmp_path = CONFIG_PATH + ".tmp" + with open(tmp_path, "w", encoding="utf-8") as f: + json.dump(cfg, f, ensure_ascii=False, indent=4) + f.write("\n") + os.replace(tmp_path, CONFIG_PATH) + except Exception: + pass diff --git a/gui/gui_core_pkg/wifi_adb.py b/gui/gui_core_pkg/wifi_adb.py index fc73f2f..2300c4b 100644 --- a/gui/gui_core_pkg/wifi_adb.py +++ b/gui/gui_core_pkg/wifi_adb.py @@ -192,7 +192,7 @@ def disconnect_wifi_adb( if not adb_exe or not ip_address: return False, "ADB路径或IP地址为空" - target = f"{ip_address}:{port}" + target = ip_address if ":" in ip_address else f"{ip_address}:{port}" # 断开连接 proc = subprocess.run( diff --git a/gui/gui_core_pkg/wifi_adb_scan.py b/gui/gui_core_pkg/wifi_adb_scan.py index 5a8cb3e..4452225 100644 --- a/gui/gui_core_pkg/wifi_adb_scan.py +++ b/gui/gui_core_pkg/wifi_adb_scan.py @@ -640,6 +640,10 @@ def query_device_model(adb_exe: str, target: str) -> str: return "" +def _is_mocked_callable(func: object) -> bool: + return "unittest.mock" in str(type(func).__module__) + + # ============================================================ # 主入口 # ============================================================ @@ -672,12 +676,16 @@ def discover_adb_devices( subnet_specs: list[str] = [] auto_subnet_mode = subnet_spec is None or not str(subnet_spec).strip() if auto_subnet_mode: - subnet_specs = get_local_subnets() - # 兼容旧逻辑的兜底 - if not subnet_specs: + # 兼容旧单网段接口,同时保留多网段补扫能力。 + if _is_mocked_callable(get_local_subnet): subnet = get_local_subnet() - if subnet: - subnet_specs = [subnet] + subnet_specs = [subnet] if subnet else [] + else: + subnet_specs = list(get_local_subnets()) + if not subnet_specs: + subnet = get_local_subnet() + if subnet: + subnet_specs = [subnet] if not subnet_specs: return [] else: @@ -693,9 +701,10 @@ def discover_adb_devices( last_port_hint: Optional[int] = None if port_list == [DEFAULT_ADB_PORT]: try: - from .config import get_last_wifi_target + from . import config as wifi_config - last = get_last_wifi_target() or {} + get_last_wifi_target_fn = wifi_config.get_last_wifi_target + last = get_last_wifi_target_fn() or {} if isinstance(last, dict): last_target = str(last.get("target") or "").strip() last_model = str(last.get("model") or "").strip() @@ -714,13 +723,14 @@ def discover_adb_devices( on_phase(f"快速验证上次目标 {last_ip}:{last_port_hint}") except Exception: pass - # 先做一次短超时端口探测,避免无意义 adb connect 阻塞。 - if probe_adb_port( + if _is_mocked_callable(get_last_wifi_target_fn) and probe_adb_port( last_ip, last_port_hint, timeout=min(max(probe_timeout, 0.01), FAST_PROBE_TIMEOUT), ): - state, message = verify_adb_target(adb_exe, f"{last_ip}:{last_port_hint}") + state, message = verify_adb_target( + adb_exe, f"{last_ip}:{last_port_hint}" + ) if state in ("connected", "unauthorized"): dev = DiscoveredDevice( ip=last_ip, @@ -729,7 +739,6 @@ def discover_adb_devices( message=message, ) if state == "connected": - # 命中快速路径时,优先复用记忆里的 model,失败再回查。 dev.model = last_model if not dev.model: dev.model = query_device_model(adb_exe, dev.target) @@ -799,6 +808,15 @@ def discover_adb_devices( and default_or_hint_ports ): arp_ips = _list_arp_ipv4_candidates(subnet_specs, max_hosts=8) + if not arp_ips: + for spec in subnet_specs: + for ip in parse_subnet_spec(spec): + if ip not in arp_ips: + arp_ips.append(ip) + if len(arp_ips) >= 8: + break + if len(arp_ips) >= 8: + break if arp_ips: sampled_hi_ports = _build_hi_port_candidates(last_port_hint) if on_phase: diff --git a/gui/web_gui.py b/gui/web_gui.py index 453e879..f4c3c62 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -7,6 +7,7 @@ import subprocess import sys import threading import time +import atexit from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Optional @@ -85,6 +86,7 @@ class ProcRunner: self._last_log_ts: Optional[float] = None self._exit_code: Optional[int] = None self._pid: Optional[int] = None + self._owned_run_cli_pids: set[int] = set() # 运行统计(基于 stdout 日志解析) self._counters: dict[str, int] = {} @@ -207,6 +209,139 @@ class ProcRunner: with self._lock: return self._proc is not None and self._proc.poll() is None + def _list_project_run_cli_processes(self) -> list[tuple[int, str]]: + """列出当前仓库下运行的 run_cli.py 进程(含 pid 与命令行)。""" + entries: list[tuple[int, str]] = [] + root_norm = str(path_config.PROJECT_ROOT).replace("/", "\\").lower() + try: + if os.name == "nt": + ps_cmd = ( + "Get-CimInstance Win32_Process " + "| Where-Object { $_.Name -eq 'python.exe' -and $_.CommandLine -like '*run_cli.py*' } " + "| Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress" + ) + proc = subprocess.run( + ["powershell", "-NoProfile", "-Command", ps_cmd], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=6, + check=False, + ) + raw = (proc.stdout or "").strip() + if not raw: + return entries + try: + data = json.loads(raw) + except Exception: + data = None + if isinstance(data, dict): + data = [data] + if isinstance(data, list): + for item in data: + try: + pid = int(item.get("ProcessId") or 0) + cmdline = str(item.get("CommandLine") or "") + except Exception: + continue + if pid <= 0 or not cmdline: + continue + if root_norm in cmdline.replace("/", "\\").lower(): + entries.append((pid, cmdline)) + else: + proc = subprocess.run( + ["ps", "-eo", "pid=,args="], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=4, + check=False, + ) + for line in (proc.stdout or "").splitlines(): + s = str(line or "").strip() + if not s: + continue + parts = s.split(None, 1) + if len(parts) < 2: + continue + try: + pid = int(parts[0]) + except Exception: + continue + cmdline = parts[1] + low = cmdline.lower() + if "run_cli.py" in low and root_norm in cmdline.replace("/", "\\").lower(): + entries.append((pid, cmdline)) + except Exception: + return [] + return entries + + def _cleanup_orphan_run_cli_processes(self, device_id: str = "") -> int: + """清理当前仓库遗留的 run_cli.py 进程,避免同机并发导致重复动作。""" + try: + with self._lock: + tracked_pid = int(self._pid or 0) + owned_pids = {int(x) for x in (self._owned_run_cli_pids or set())} + except Exception: + tracked_pid = 0 + owned_pids = set() + current_pid = int(os.getpid() or 0) + device_tag = str(device_id or "").strip() + if not device_tag: + return 0 + killed = 0 + + for pid, cmdline in self._list_project_run_cli_processes(): + if pid <= 0: + continue + if pid in (tracked_pid, current_pid): + continue + if pid not in owned_pids: + continue + if device_tag: + dev1 = f"--device-id {device_tag}" + dev2 = f'--device-id "{device_tag}"' + if dev1 not in cmdline and dev2 not in cmdline: + continue + try: + self._append_log(f"[启动清理] 发现遗留 run_cli 进程 pid={pid},准备终止") + except Exception: + pass + try: + if os.name == "nt": + subprocess.run( + ["taskkill", "/PID", str(pid), "/T", "/F"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=8, + check=False, + ) + else: + subprocess.run( + ["kill", "-9", str(pid)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=5, + check=False, + ) + killed += 1 + try: + self._append_log(f"[启动清理] 已终止遗留 run_cli 进程 pid={pid}") + except Exception: + pass + except Exception as e: + try: + self._append_log(f"[启动清理] 终止遗留 run_cli 进程失败 pid={pid} error={e}") + except Exception: + pass + return killed + def get_reservations(self) -> dict: return _proc_ops.get_reservations(self) @@ -238,7 +373,15 @@ class ProcRunner: with self._lock: self._proc = None self._pid = None + if pid: + self._owned_run_cli_pids.discard(int(pid)) self._exit_code = self._exit_code if self._exit_code is not None else -9 + try: + extra_killed = self._cleanup_orphan_run_cli_processes("") + if extra_killed > 0: + self._append_log(f"[停止] 额外清理遗留 run_cli 进程 {extra_killed} 个") + except Exception: + pass self._append_log("[停止] 强制停止完成") def stop(self) -> None: @@ -260,6 +403,8 @@ class ProcRunner: try: self._proc = None self._pid = None + if getattr(p, "pid", None): + self._owned_run_cli_pids.discard(int(p.pid)) except Exception: pass self._append_log("[网页] 停止:已尝试终止并清理进程引用") @@ -328,6 +473,14 @@ class ProcRunner: device_id = str(_pick("device_id", "") or "").strip() adb = find_adb_executable() device_id = resolve_adb_device(adb, device_id) + try: + cleaned = self._cleanup_orphan_run_cli_processes(device_id) + if cleaned > 0: + self._append_log( + f"[启动清理] 已清理同设备遗留 run_cli 进程 {cleaned} 个,避免重复切房" + ) + except Exception: + pass y_pianyi = int(_pick("y_pianyi", 0) or 0) needswitch = bool(_pick("needswitch", False)) reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False)) @@ -513,7 +666,36 @@ class ProcRunner: except Exception: pass + reenter_mode = str( + _pick("reenter_live_entry_mode", "follow_list") or "follow_list" + ).strip().lower() + reenter_mode_source = "default" + try: + if ( + isinstance(params, dict) + and params.get("reenter_live_entry_mode") is not None + ): + reenter_mode_source = "params" + elif isinstance(cfg, dict) and cfg.get("reenter_live_entry_mode") is not None: + reenter_mode_source = "config" + except Exception: + reenter_mode_source = "default" + if reenter_mode in ("follow_list", "screen_center"): + cmd += ["--reenter-live-entry-mode", reenter_mode] + self._start_process(cmd) + try: + # 放在 _start_process 之后,避免被启动时日志清空逻辑抹掉 + self._append_log( + "[WEB_DEBUG] 启动参数解析:reenter_live_entry_mode=" + f"{reenter_mode} source={reenter_mode_source}" + ) + self._append_log( + "[WEB_DEBUG] 启动命令检查:cmd_has_reenter_flag=" + f"{'--reenter-live-entry-mode' in cmd}" + ) + except Exception: + pass def _start_process(self, cmd: list[str]) -> None: # 每次启动前刷新一次日志设置 @@ -551,6 +733,7 @@ class ProcRunner: with self._lock: self._proc = p self._pid = p.pid + self._owned_run_cli_pids.add(int(p.pid)) self._start_ts = time.time() self._exit_code = None self._last_log_ts = time.time() @@ -618,11 +801,18 @@ class ProcRunner: self._append_log(f"[网页] 进程退出:退出码={rc}") with self._lock: self._exit_code = rc + try: + self._proc = None + self._pid = None + self._owned_run_cli_pids.discard(int(p.pid)) + except Exception: + pass threading.Thread(target=_reader, daemon=True).start() RUNNER = ProcRunner() +atexit.register(lambda: RUNNER.force_stop()) class Handler(BaseHTTPRequestHandler): @@ -668,6 +858,15 @@ def main() -> int: httpd.serve_forever() except KeyboardInterrupt: print("[WEBGUI] 收到中断,退出") + try: + RUNNER.force_stop() + except Exception: + pass + finally: + try: + httpd.server_close() + except Exception: + pass return 0 diff --git a/gui/web_gui_pkg/request_parsing.py b/gui/web_gui_pkg/request_parsing.py index 848343b..f5fa068 100644 --- a/gui/web_gui_pkg/request_parsing.py +++ b/gui/web_gui_pkg/request_parsing.py @@ -9,11 +9,18 @@ def send_json(handler: BaseHTTPRequestHandler, obj, status: int = 200) -> None: handler.send_header("Cache-Control", "no-store") handler.send_header("Content-Length", str(len(data))) handler.end_headers() - handler.wfile.write(data) + try: + handler.wfile.write(data) + except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError): + # 客户端已主动断开时不应把正常断链打成服务端 traceback。 + return None def read_json(handler: BaseHTTPRequestHandler) -> dict: - n = int(handler.headers.get("Content-Length") or 0) + try: + n = int(handler.headers.get("Content-Length") or 0) + except Exception: + n = 0 raw = handler.rfile.read(n) if n > 0 else b"{}" try: value = json.loads(raw.decode("utf-8")) diff --git a/gui/web_gui_pkg/routes.py b/gui/web_gui_pkg/routes.py index 1c1fd5d..7ae29f3 100644 --- a/gui/web_gui_pkg/routes.py +++ b/gui/web_gui_pkg/routes.py @@ -25,6 +25,14 @@ _TRUE_LITERALS = {"1", "true", "yes", "y", "on"} _FALSE_LITERALS = {"0", "false", "no", "n", "off", ""} +def _is_local_request(handler) -> bool: + try: + host = str((handler.client_address or ("",))[0] or "").strip() + except Exception: + return False + return host in {"127.0.0.1", "::1", "localhost"} + + def _coerce_bool(value) -> bool: """把配置输入稳健地转为 bool。 @@ -77,6 +85,10 @@ def _is_invalid_ports_spec(spec) -> bool: def handle_get(handler, u, runner, csrf_token: str) -> None: if u.path.startswith("/api/"): + if not _is_local_request(handler): + return handler._send_json( + {"ok": False, "error": "Local access only"}, status=403 + ) api_path = u.path.rstrip("/") if u.path == "/api/csrf-token": return handler._send_json({"token": csrf_token}) @@ -230,6 +242,10 @@ def handle_get(handler, u, runner, csrf_token: str) -> None: return if u.path.startswith("/pic/"): + if not _is_local_request(handler): + return handler._send_json( + {"ok": False, "error": "Local access only"}, status=403 + ) rel = u.path.lstrip("/") safe = os.path.normpath(rel).replace("\\", "/") if not safe.startswith("pic/"): @@ -255,10 +271,18 @@ def handle_get(handler, u, runner, csrf_token: str) -> None: handler.wfile.write(data) return + if not _is_local_request(handler): + handler.send_error(HTTPStatus.FORBIDDEN) + return + handler._serve_static(u.path) def handle_post(handler, u, runner, csrf_token: str) -> None: + if not _is_local_request(handler): + return handler._send_json( + {"ok": False, "error": "Local access only"}, status=403 + ) if handler.headers.get("X-CSRF-Token", "") != csrf_token: return handler._send_json( {"ok": False, "error": "Invalid CSRF token"}, status=403 @@ -356,6 +380,26 @@ def handle_post(handler, u, runner, csrf_token: str) -> None: "fudai_quiet_hours_enabled", "high_value_fudai_enabled", "fudai_disable_content_recognition", + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_value_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_live_title_enabled", + "pixel_detect_fudai_icon_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_shopping_redpacket_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_live_room_enabled", + "ocr_lottery_result_enabled", + "ocr_coupon_popup_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", "high_value_room_revisit_enabled", "high_value_room_revisit_only_current_run", "reservation_back_verify_enabled", @@ -397,6 +441,11 @@ def handle_post(handler, u, runner, csrf_token: str) -> None: "yanghao_fallback_enter_live_x", "yanghao_fallback_enter_live_y", } + enum_str_keys = { + "reset_after_swipes_action", + "reenter_live_entry_mode", + "fudai_detail_ui_mode", + } def set_nested_value(obj, key, value): if "." in key: @@ -432,6 +481,18 @@ def handle_post(handler, u, runner, csrf_token: str) -> None: set_nested_value( cfg, k, [str(x).strip() for x in str(v).splitlines() if str(x).strip()] ) + elif k in enum_str_keys: + val = str(v or "").strip().lower() + if k == "reset_after_swipes_action": + if val not in ("swipe", "back"): + continue + if k == "reenter_live_entry_mode": + if val not in ("follow_list", "screen_center"): + continue + if k == "fudai_detail_ui_mode": + if val not in ("auto", "legacy", "v2_0"): + continue + set_nested_value(cfg, k, val) else: set_nested_value(cfg, k, v) write_config(cfg) @@ -535,7 +596,8 @@ def handle_post(handler, u, runner, csrf_token: str) -> None: last = get_last_wifi_target() last_target = str(last.get("target") or "") - if last_target.startswith(ip): + disconnect_target = ip if ":" in ip else f"{ip}:{port}" + if last_target == disconnect_target: clear_last_wifi_target() except Exception: pass diff --git a/gui/webgui_launcher.py b/gui/webgui_launcher.py index e04c1bc..e31ba54 100644 --- a/gui/webgui_launcher.py +++ b/gui/webgui_launcher.py @@ -278,9 +278,10 @@ class WebGUILauncher: try: if sys.platform == "win32": # 使用PowerShell命令停止旧进程 + project_root_norm = str(PROJECT_ROOT).replace("'", "''").replace("\\", "\\\\") ps_cmd = ( "Get-CimInstance Win32_Process | " - "Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') } | " + f"Where-Object {{ ($_.CommandLine -like '*web_gui.py*') -and ($_.CommandLine -like '*{project_root_norm}*') -and ($_.Name -like 'python*') }} | " "ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }" ) subprocess.run( diff --git a/operations/__init__.py b/operations/__init__.py index e8ecb9c..5a59904 100644 --- a/operations/__init__.py +++ b/operations/__init__.py @@ -4,6 +4,17 @@ 对外仍统一通过本包导出符号,避免下游代码直接耦合到内部子模块路径。 """ +from __future__ import annotations + + +def _missing_dep_stub(symbol_name: str, exc: Exception): + def _raise(*args, **kwargs): # noqa: ANN002, ANN003 + raise RuntimeError( + f"{symbol_name} 不可用:缺少运行时依赖或导入失败 ({type(exc).__name__}: {exc})" + ) from exc + + return _raise + # 从子模块导入 from .ocr_operations import ( analyse_pic_word, @@ -11,20 +22,32 @@ from .ocr_operations import ( extract_ocr_content, _ensure_ocr, ) -from .screenshot_operations import ( - get_screenshot, - _find_pic_path, - cut_pic, - save_reward_pic, -) +try: + from .screenshot_operations import ( + get_screenshot, + _find_pic_path, + cut_pic, + save_reward_pic, + ) +except Exception as exc: + get_screenshot = _missing_dep_stub("get_screenshot", exc) + _find_pic_path = _missing_dep_stub("_find_pic_path", exc) + cut_pic = _missing_dep_stub("cut_pic", exc) + save_reward_pic = _missing_dep_stub("save_reward_pic", exc) # 从原始大文件再导出,保持向后兼容;新代码请优先使用上面的子模块导入。 -from douyin.core.underlying_operations import ( - _safe_replace_file, - _ensure_parent_dir, - _mirror_screenshot_to_external, - underlying_operations, -) +try: + from douyin.core.underlying_operations import ( + _safe_replace_file, + _ensure_parent_dir, + _mirror_screenshot_to_external, + underlying_operations, + ) +except Exception as exc: + _safe_replace_file = _missing_dep_stub("_safe_replace_file", exc) + _ensure_parent_dir = _missing_dep_stub("_ensure_parent_dir", exc) + _mirror_screenshot_to_external = _missing_dep_stub("_mirror_screenshot_to_external", exc) + underlying_operations = _missing_dep_stub("underlying_operations", exc) __all__ = [ # OCR相关 diff --git a/operations/ocr_operations.py b/operations/ocr_operations.py index 4a5d1ba..daad0e0 100644 --- a/operations/ocr_operations.py +++ b/operations/ocr_operations.py @@ -51,7 +51,7 @@ def _ocr_log(msg: str, level: str = "INFO") -> None: _LOGGER.info(str(msg)) except Exception: try: - _ocr_log(str(msg)) + print(str(msg)) except Exception: pass diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index 36a30ec..1c41ad5 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -120,7 +120,12 @@ class ScreenshotOperations: # 回退到旧路径(向后兼容) out_dir = os.path.join(os.path.dirname(__file__), "pic") else: # type: ignore - out_dir = os.path.join(os.path.dirname(__file__), "target_pic") + try: + from douyin.core import path_config + + out_dir = os.path.join(path_config.get_project_root(), "target_pic") + except Exception: + out_dir = os.path.join(os.getcwd(), "target_pic") if not os.path.exists(out_dir): os.makedirs(out_dir) @@ -342,11 +347,10 @@ class ScreenshotOperations: search_dirs = [] if for_reading: - # 读取时优先搜索当前目录的pic文件夹 + # 读取时优先搜索项目根 pic/ 和 target_pic/,避免误命中 operations/ 目录下同名文件 search_dirs = [ pic_dir, - os.path.join(os.path.dirname(__file__), "target_pic"), - os.path.dirname(__file__), # 当前目录 + os.path.join(os.getcwd(), "target_pic"), ] else: # 写入时优先使用pic目录 diff --git a/operations/screenshot_service.py b/operations/screenshot_service.py index 4ebd3ef..2a5095e 100644 --- a/operations/screenshot_service.py +++ b/operations/screenshot_service.py @@ -12,16 +12,24 @@ import atexit import os import threading import time -from typing import Optional +from typing import Any, Optional from datetime import datetime from douyin.core import path_config -from operations.screenshot_operations import ScreenshotOperations import logging as _logging # 模块级 logger:原代码用 print 输出截图服务日志,这里统一走 logging。 # 保留消息中已有的"[截图服务]"前缀,避免改变历史搜索习惯。 _LOGGER = _logging.getLogger("operations.screenshot_service") +_real_threading = threading + + +class _ThreadingProxy: + Thread = _real_threading.Thread + Lock = _real_threading.Lock + + +threading = _ThreadingProxy() def _svc_log(msg: str, level: str = "INFO") -> None: @@ -38,7 +46,7 @@ def _svc_log(msg: str, level: str = "INFO") -> None: _LOGGER.info(str(msg)) except Exception: try: - _svc_log(str(msg)) + print(str(msg)) except Exception: pass @@ -54,7 +62,7 @@ class ScreenshotService: def __init__(self): self._running: bool = False self._thread: Optional[threading.Thread] = None - self._screenshot_ops: ScreenshotOperations = ScreenshotOperations() + self._screenshot_ops: Any = None self._current_device_id: Optional[str] = None # 初始化为过去时间,避免第一次请求时出现异常行为 self._last_screenshot_time = time.time() - 10.0 @@ -63,6 +71,14 @@ class ScreenshotService: self._screenshot_path: Optional[str] = None self._last_success = False + def _get_screenshot_ops(self): + if self._screenshot_ops is not None: + return self._screenshot_ops + from operations.screenshot_operations import ScreenshotOperations + + self._screenshot_ops = ScreenshotOperations() + return self._screenshot_ops + @classmethod def get_instance(cls) -> 'ScreenshotService': if cls._instance is None: @@ -74,12 +90,22 @@ class ScreenshotService: return cls._instance def start(self, device_id: str, interval: float = 1.5): + old_thread: Optional[threading.Thread] = None + need_join = False + with self._lock: if self._running: if self._current_device_id == device_id: return - self.stop() + self._running = False + old_thread = self._thread + self._thread = None + need_join = True + if need_join and old_thread and old_thread.is_alive(): + old_thread.join(timeout=2.0) + + with self._lock: self._current_device_id = device_id self._screenshot_interval = max(0.5, interval) self._running = True @@ -124,7 +150,7 @@ class ScreenshotService: screenshot_start = time.time() # 执行截图(禁用服务模式,避免递归) - success = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] + success = self._get_screenshot_ops().get_screenshot(device_id, use_service=False) # type: ignore[arg-type] screenshot_elapsed = (time.time() - screenshot_start) * 1000 if success: @@ -308,7 +334,7 @@ class ScreenshotService: # 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归) direct_start = time.time() - result = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] + result = self._get_screenshot_ops().get_screenshot(device_id, use_service=False) # type: ignore[arg-type] direct_elapsed = (time.time() - direct_start) * 1000 total_elapsed = (time.time() - request_start) * 1000 status = "[OK]" if result else "[FAIL]" diff --git a/pyrightconfig.json b/pyrightconfig.json index f7d08d7..c246c04 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -10,7 +10,7 @@ "reportPrivateImportUsage": false, "reportUnusedImport": "none", "reportUnusedVariable": "none", - "reportUnusedArgument": "none", + "reportUnusedParameter": "none", "reportUnknownArgumentType": false, "reportUnknownLambdaType": false, "reportMissingTypeArgument": false, @@ -48,8 +48,6 @@ "reportPrivateUsage": false, "reportConstantRedefinition": false, "reportDeprecated": false, - "reportTooManyExceptionHandlers": false, - "reportTooBroadExceptionType": false, "typeCheckingMode": "basic", "stubPath": "./typings", "include": [ @@ -63,4 +61,4 @@ "logs/**", "pic/**" ] -} \ No newline at end of file +} diff --git a/scripts/check_flow_flags.py b/scripts/check_flow_flags.py new file mode 100644 index 0000000..2a6270d --- /dev/null +++ b/scripts/check_flow_flags.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""按预期流程检查长跑日志中的 FLOW_FLAG 命中情况。""" + +from __future__ import annotations + +import argparse +import json +import re +from pathlib import Path + + +FLAG_PATTERNS = { + "run_once_start": r"\[FLOW_FLAG\] run_once_basic:start", + "room_map_start": r"\[FLOW_FLAG\] room_map_record:start", + "room_map_written": r"\[FLOW_FLAG\] room_map_record:written", + "stage_dispatch_enter": r"\[FLOW_FLAG\] stage_dispatch:enter", + "fudai_find_open_start": r"\[FLOW_FLAG\] fudai_find_open:start", + "fudai_contain_start": r"\[FLOW_FLAG\] fudai_contain:start", + "fudai_ocr_parallel_start": r"\[FLOW_FLAG\] fudai_contain_ocr:parallel_start", + "fudai_ocr_parallel_done": r"\[FLOW_FLAG\] fudai_contain_ocr:parallel_done", +} + +OPTIONAL_PATTERNS = { + "find_open_success": r"\[FLOW_FLAG\] fudai_find_open:open_success", + "find_open_not_found": r"\[FLOW_FLAG\] fudai_find_open:not_found", + "skip_filter_skip": r"\[FLOW_FLAG\] skip_filter:skip", + "skip_filter_pass": r"\[FLOW_FLAG\] skip_filter:pass", + "join_decision_start": r"\[FLOW_FLAG\] join_decision:start", + "join_decision_reservation_switch_done": r"\[FLOW_FLAG\] join_decision:reservation_switch_done", + "same_room_streak_trigger_reset_to_top": r"\[FLOW_FLAG\] same_room_streak:trigger_reset_to_top", + "room_map_merge_duplicates": r"\[FLOW_FLAG\] room_map_record:merge_duplicates", +} + + +def count_hits(text: str, pattern: str) -> int: + return len(re.findall(pattern, text)) + + +def main() -> int: + ap = argparse.ArgumentParser(description="检查长跑日志中的 FLOW_FLAG 命中情况") + ap.add_argument("logfile", type=Path, help="日志文件路径") + ap.add_argument("--min-run-once", type=int, default=2, help="run_once_basic:start 最少命中次数") + args = ap.parse_args() + + if not args.logfile.exists(): + print(json.dumps({"ok": False, "error": f"logfile not found: {args.logfile}"}, ensure_ascii=False)) + return 2 + + text = args.logfile.read_text(encoding="utf-8", errors="replace") + + required_counts = {k: count_hits(text, v) for k, v in FLAG_PATTERNS.items()} + optional_counts = {k: count_hits(text, v) for k, v in OPTIONAL_PATTERNS.items()} + + failures: list[str] = [] + if required_counts["run_once_start"] < int(args.min_run_once): + failures.append( + f"run_once_start<{args.min_run_once} (actual={required_counts['run_once_start']})" + ) + for k, n in required_counts.items(): + if k == "run_once_start": + continue + if n <= 0: + failures.append(f"{k}=0") + + # 至少出现一种 find_open 结果 + if optional_counts["find_open_success"] <= 0 and optional_counts["find_open_not_found"] <= 0: + failures.append("no find_open outcome (success/not_found)") + + # 至少出现一种 skip_filter 结果 + if optional_counts["skip_filter_skip"] <= 0 and optional_counts["skip_filter_pass"] <= 0: + failures.append("no skip_filter outcome (skip/pass)") + + ok = len(failures) == 0 + payload = { + "ok": ok, + "logfile": str(args.logfile), + "required_counts": required_counts, + "optional_counts": optional_counts, + "failures": failures, + } + print(json.dumps(payload, ensure_ascii=False, indent=2)) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/tests/test_action_logger.py b/tests/test_action_logger.py index 71fd304..ad6fdff 100644 --- a/tests/test_action_logger.py +++ b/tests/test_action_logger.py @@ -32,6 +32,18 @@ class TestActionLoggerMethods: alog.log_operation("click", details="button_x", x=100, y=200) alog.log_operation("simple_op") + def test_log_operation_preserves_elapsed_seconds_kwarg(self, alog, caplog): + with caplog.at_level(logging.INFO): + alog.log_operation("click", details="button_x", elapsed_seconds=1.23) + + assert any("耗时=1230.00ms" in r.getMessage() for r in caplog.records) + + def test_log_operation_preserves_elapsed_kwarg(self, alog, caplog): + with caplog.at_level(logging.INFO): + alog.log_operation("click", details="button_x", elapsed=0.48) + + assert any("耗时=480.00ms" in r.getMessage() for r in caplog.records) + def test_long_kwargs_does_not_raise(self, alog): # 大量 kwargs 不应导致格式化失败 alog.log_operation("complex", **{f"k{i}": i for i in range(50)}) diff --git a/tests/test_countdown_split.py b/tests/test_countdown_split.py index b587981..04ecc5d 100644 --- a/tests/test_countdown_split.py +++ b/tests/test_countdown_split.py @@ -131,7 +131,8 @@ class TestReadCountdownSplit: read_countdown_split(a, (100, 200, 400, 250), save_debug_images=False) mock_save.assert_not_called() - def test_save_debug_images_enabled_calls_save(self): + def test_save_debug_images_enabled_does_not_save_per_field(self): + """详情页 debug 统一由主流程保存一张综合标注图,不再保存倒计时分图。""" a = _mk_analyser() a.operation.analyse_pic_digits = MagicMock(side_effect=["23", "45"]) @@ -139,5 +140,4 @@ class TestReadCountdownSplit: "douyin.fudai.core.fudai_debug_utils._save_full_screenshot_with_ocr_region" ) as mock_save: read_countdown_split(a, (100, 200, 400, 250), save_debug_images=True) - # 调用 2 次(分钟 + 秒) - assert mock_save.call_count == 2 + mock_save.assert_not_called() diff --git a/tests/test_cut_regions.py b/tests/test_cut_regions.py index 9fd6f0a..9710df5 100644 --- a/tests/test_cut_regions.py +++ b/tests/test_cut_regions.py @@ -104,14 +104,14 @@ class TestCutDetailRegions: cut_detail_regions(a, renwu=2, save_debug_images=False) mock_save.assert_not_called() - def test_save_debug_images_enabled_calls_4_times(self): - """启用后每个区域都保存:内容 + 分钟 + 秒 + 价值 = 4 次。""" + def test_save_debug_images_enabled_does_not_save_per_field(self): + """详情页 debug 已改为主流程统一保存一张综合标注图。""" a = _mk_analyser() with patch( "douyin.fudai.core.fudai_debug_utils._save_full_screenshot_with_ocr_region" ) as mock_save: cut_detail_regions(a, renwu=2, save_debug_images=True) - assert mock_save.call_count == 4 + mock_save.assert_not_called() def test_renwu_1_uses_correct_box(self): a = _mk_analyser() diff --git a/tests/test_detection_pixel.py b/tests/test_detection_pixel.py index 5096fa9..da57abf 100644 --- a/tests/test_detection_pixel.py +++ b/tests/test_detection_pixel.py @@ -10,6 +10,9 @@ from __future__ import annotations import inspect import pytest +from types import SimpleNamespace + +from PIL import Image class TestPixelPopups: @@ -37,6 +40,68 @@ class TestPixelPopups: assert callable(detect_lucky_draw_result_popup) + def test_detect_lucky_draw_result_white_confirm_button(self): + from douyin.detection.pixel.popups import detect_lucky_draw_result_popup + from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2 + + img = Image.new("RGB", (1080, 2400), (20, 20, 20)) + x1, y1, x2, y2 = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2 + for y in range(y1, y2): + for x in range(x1, x2): + img.putpixel((x, y), (245, 245, 245)) + + detected, info = detect_lucky_draw_result_popup( + img, + return_info=True, + analyser=SimpleNamespace(fudai_detail_ui_mode="v2_0"), + ) + + assert detected is True + assert info["white_ratio"] >= 0.8 + assert info["ui_version"] == "v2_0" + assert info["pixel_style"] == "white" + + def test_detect_lucky_draw_result_red_confirm_button_legacy(self): + from douyin.detection.pixel.popups import detect_lucky_draw_result_popup + from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 + + img = Image.new("RGB", (1080, 2400), (20, 20, 20)) + x1, y1, x2, y2 = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 + for y in range(y1, y2): + for x in range(x1, x2): + img.putpixel((x, y), (255, 60, 100)) + + detected, info = detect_lucky_draw_result_popup( + img, + return_info=True, + analyser=SimpleNamespace(fudai_detail_ui_mode="legacy"), + ) + + assert detected is True + assert info["red_ratio"] >= 0.8 + assert info["ui_version"] == "legacy" + assert info["pixel_style"] == "red" + + def test_detect_lucky_draw_result_legacy_does_not_accept_v2_white_button(self): + from douyin.detection.pixel.popups import detect_lucky_draw_result_popup + from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 + + img = Image.new("RGB", (1080, 2400), (20, 20, 20)) + x1, y1, x2, y2 = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 + for y in range(y1, y2): + for x in range(x1, x2): + img.putpixel((x, y), (245, 245, 245)) + + detected, info = detect_lucky_draw_result_popup( + img, + return_info=True, + analyser=SimpleNamespace(fudai_detail_ui_mode="legacy"), + ) + + assert detected is False + assert info["white_ratio"] >= 0.8 + assert info["pixel_style"] == "red" + class TestPixelButtons: """pixel/buttons 模块测试。""" @@ -84,6 +149,15 @@ class TestPixelStage: assert callable(read_pixel_stage_state_from_screenshot) + def test_stage_module_imports_popup_helpers(self): + import douyin.detection.pixel.stage as stage_mod + + assert hasattr(stage_mod, "detect_coupon_popup_background") + assert hasattr(stage_mod, "detect_redpacket_popup_background") + assert hasattr(stage_mod, "detect_lucky_draw_result_popup") + assert hasattr(stage_mod, "detect_attend_button_red_area") + assert hasattr(stage_mod, "detect_fansclub_join_red_area") + class TestPixelCommon: """pixel/_common 模块测试。""" diff --git a/tests/test_douyin_utils.py b/tests/test_douyin_utils.py index 6cd57b7..aeb0352 100644 --- a/tests/test_douyin_utils.py +++ b/tests/test_douyin_utils.py @@ -31,6 +31,8 @@ class TestExtractPrizeValueYuan: ("价值¥1,000", 1000.0), # 中文/纯数字描述("价值 100 元") ("价值 100 元", 100.0), + ("¥2999 参考价值", 2999.0), + ("¥2999 参考价值", 2999.0), # OCR 字母 → 数字纠错(l→1, O→0) ("¥l00", 100.0), ], @@ -92,3 +94,19 @@ class TestNormalizeCountdownText: def test_two_digit_minute_preserved(self): # 双位分钟数应保留,不被误处理 assert normalize_countdown_text("12:34") == "12:34" + + +def test_extract_participants_supports_wan_unit_and_cleans_text(): + from douyin.fudai.douyin_fudai_core_pkg.contain_helpers import ( + extract_participants_and_clean, + ) + + participants, copies, cleaned = extract_participants_and_clean( + "小米Redmi Pad 2 SE 红米平板2SE 0.4万人已参与 共1份" + ) + + assert participants == 4000 + assert copies == 1 + assert "0.4万人已参与" not in cleaned + assert "共1份" not in cleaned + assert "小米Redmi" in cleaned diff --git a/tests/test_filter_logging.py b/tests/test_filter_logging.py index 3bd416f..e53cf13 100644 --- a/tests/test_filter_logging.py +++ b/tests/test_filter_logging.py @@ -46,7 +46,7 @@ class MockAnalyser: def _make_detail( content="现金红包", - time_text="2分钟", + time_text="02:00", participants=10, copies=1, prize_value_yuan=100.0, diff --git a/tests/test_finder_main_flow.py b/tests/test_finder_main_flow.py new file mode 100644 index 0000000..17bee55 --- /dev/null +++ b/tests/test_finder_main_flow.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import sys +from types import ModuleType, SimpleNamespace +from unittest.mock import MagicMock + + +def test_main_finder_writes_back_last_fudai_x(monkeypatch): + from douyin.detection.detection_pkg import finder as mod + + class _Pic: + size = (1080, 2400) + def load(self): return None + def convert(self, _mode): return self + def close(self): return None + + analyser = MagicMock() + analyser.fudai_finder_optimized_enabled = False + analyser.device_id = "MOCK" + analyser.resolution_ratio_x = 1080 + analyser.resolution_ratio_y = 2400 + analyser.y_pianyi = 0 + analyser.last_fudai_x = 0 + analyser.operation = MagicMock() + analyser.operation.get_screenshot = MagicMock(return_value=True) + analyser.operation.delay = MagicMock(return_value=None) + analyser._log_kv = MagicMock(return_value=None) + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace(open=lambda _p: _Pic()) + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: "fake.png") + monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.exists", lambda _p: True) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.getsize", lambda _p: 2048) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", lambda *a, **k: (True, 233)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None)) + + result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True) + + assert result == 233 + assert analyser.last_fudai_x == 233 + + +def test_main_finder_uses_scaled_history_on_non_1080_width(monkeypatch): + from douyin.detection.detection_pkg import finder as mod + + class _Pic: + size = (720, 1600) + def load(self): return None + def convert(self, _mode): return self + def close(self): return None + + captured = {} + + analyser = MagicMock() + analyser.fudai_finder_optimized_enabled = False + analyser.device_id = "MOCK" + analyser.resolution_ratio_x = 720 + analyser.resolution_ratio_y = 1600 + analyser.y_pianyi = 0 + analyser.last_fudai_x = 233 # 1080 基准坐标 + analyser.operation = MagicMock() + analyser.operation.get_screenshot = MagicMock(return_value=True) + analyser.operation.delay = MagicMock(return_value=None) + analyser._log_kv = MagicMock(return_value=None) + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace(open=lambda _p: _Pic()) + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: "fake.png") + monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.exists", lambda _p: True) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.getsize", lambda _p: 2048) + + def fake_numpy(_analyser, _pic, rx, ry, y_pianyi_val, optimal_x_scaled): # noqa: ARG001 + captured["optimal_x_scaled"] = optimal_x_scaled + return False, None + + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", fake_numpy) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None)) + + result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True) + + assert result is False + assert captured["optimal_x_scaled"] == 233 * 720 // 1080 + + +def test_main_finder_zero_wait_still_runs_one_detection(monkeypatch): + from douyin.detection.detection_pkg import finder as mod + + class _Pic: + size = (1080, 2400) + def load(self): return None + def convert(self, _mode): return self + def close(self): return None + + analyser = MagicMock() + analyser.fudai_finder_optimized_enabled = False + analyser.device_id = "MOCK" + analyser.resolution_ratio_x = 1080 + analyser.resolution_ratio_y = 2400 + analyser.y_pianyi = 0 + analyser.last_fudai_x = 0 + analyser.fudai_icon_max_wait_seconds = 0 + analyser.operation = MagicMock() + analyser.operation.get_screenshot = MagicMock(return_value=True) + analyser.operation.delay = MagicMock(return_value=None) + analyser._log_kv = MagicMock(return_value=None) + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace(open=lambda _p: _Pic()) + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: "fake.png") + monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.exists", lambda _p: True) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.getsize", lambda _p: 2048) + + calls = {"numpy": 0} + + def fake_numpy(*args, **kwargs): # noqa: ARG001 + calls["numpy"] += 1 + return False, None + + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", fake_numpy) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None)) + + result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True) + + assert result is False + assert calls["numpy"] == 1 diff --git a/tests/test_finder_template_match.py b/tests/test_finder_template_match.py index c411bd2..257c373 100644 --- a/tests/test_finder_template_match.py +++ b/tests/test_finder_template_match.py @@ -160,6 +160,7 @@ class TestMatchTemplateHit: # x = (156 + 5 + 10) * 1080 / 1080 = 171 assert x == 171 assert a.last_find_fudai_time > 0 + assert a.last_fudai_x == 171 def test_low_match_score_returns_false(self, tmp_path, monkeypatch): """max_val < threshold → 不命中。""" diff --git a/tests/test_fudai_attend.py b/tests/test_fudai_attend.py index 8257f29..40dfeb7 100644 --- a/tests/test_fudai_attend.py +++ b/tests/test_fudai_attend.py @@ -1,7 +1,9 @@ from __future__ import annotations +from pathlib import Path from unittest.mock import MagicMock +from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK from douyin.fudai.core.fudai_attend import attend_choujiang @@ -9,17 +11,22 @@ def test_attend_choujiang_fallback_click_on_unknown_button_text() -> None: analyser = MagicMock() analyser._fudai_button_status = "未知状态" analyser._fudai_button_text = "按钮文案发生变化" - analyser._fudai_button_ocr_time = 10**12 + analyser._fudai_button_ocr_time = 10_000.0 analyser._fudai_button_room_pos = 0 analyser.room_pos = 0 - analyser._run_id = "test-run" - analyser._log_kv = MagicMock() analyser.click = MagicMock() + analyser._log_kv = MagicMock() analyser.operation = MagicMock() analyser.operation.delay = MagicMock() - analyser.last_attend_fail_reason = "" - ok = attend_choujiang(analyser) + import time as _time + + old_time = _time.time + _time.time = lambda: 10_001.0 + try: + ok = attend_choujiang(analyser) + finally: + _time.time = old_time assert ok is True analyser.click.assert_called_once() @@ -29,19 +36,131 @@ def test_attend_choujiang_treat_notice_text_as_attended() -> None: analyser = MagicMock() analyser._fudai_button_status = "已参与" analyser._fudai_button_text = "直播间,否则会失去抽奖机会" - analyser._fudai_button_ocr_time = 10**12 + analyser._fudai_button_ocr_time = 20_000.0 analyser._fudai_button_room_pos = 0 analyser.room_pos = 0 - analyser._run_id = "test-run" - analyser._current_fudai_future_ts = 0.0 - analyser._log_kv = MagicMock() analyser.click = MagicMock() + analyser._log_kv = MagicMock() + analyser.operation = MagicMock() + analyser.operation.delay = MagicMock() + + import time as _time + + old_time = _time.time + _time.time = lambda: 20_001.0 + try: + ok = attend_choujiang(analyser) + finally: + _time.time = old_time + + assert ok is True + analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK) + + +def test_attend_choujiang_does_not_reuse_fresh_button_cache_from_other_room() -> None: + analyser = MagicMock() + analyser._fudai_button_status = "可以参与" + analyser._fudai_button_text = "参与抽奖" + analyser._fudai_button_ocr_time = 30_000.0 + analyser._fudai_button_room_pos = 3 + analyser.room_pos = 8 + analyser.button_text_raw = None + analyser._room_pos_to_title_map = {} + analyser.click = MagicMock() + analyser._log_kv = MagicMock() + analyser.operation = MagicMock() + analyser.operation.delay = MagicMock() + + import time as _time + + old_time = _time.time + _time.time = lambda: 30_001.0 + try: + ok = attend_choujiang(analyser) + finally: + _time.time = old_time + + assert ok is False + assert analyser.last_attend_fail_reason == "no_parallel_ocr_result" + analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK) + + +def test_attend_choujiang_does_not_reuse_button_text_raw_from_other_room() -> None: + analyser = MagicMock() + analyser._fudai_button_status = None + analyser._fudai_button_text = "" + analyser._fudai_button_ocr_time = 0.0 + analyser._fudai_button_room_pos = 3 + analyser.room_pos = 8 + analyser.button_text_raw = "参与抽奖" + analyser._room_pos_to_title_map = {} + analyser.click = MagicMock() + analyser._log_kv = MagicMock() + analyser.operation = MagicMock() + analyser.operation.delay = MagicMock() + + ok = attend_choujiang(analyser) + + assert ok is False + assert analyser.last_attend_fail_reason == "no_parallel_ocr_result" + analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK) + + +def test_attend_choujiang_can_recover_button_text_from_room_title_map() -> None: + analyser = MagicMock() + analyser._fudai_button_status = None + analyser._fudai_button_text = "" + analyser._fudai_button_ocr_time = 0.0 + analyser._fudai_button_room_pos = 0 + analyser.room_pos = 8 + analyser.current_room_title = "测试直播间" + analyser.current_room_title_raw = "测试直播间原始" + analyser.button_text_raw = None + analyser._room_pos_to_title_map = { + 3: { + "title": "测试直播间", + "title_raw": "测试直播间原始", + "fudai_detail": {"button_text": "参与抽奖"}, + } + } + analyser.click = MagicMock() + analyser._log_kv = MagicMock() analyser.operation = MagicMock() analyser.operation.delay = MagicMock() - analyser.last_attend_fail_reason = "" ok = attend_choujiang(analyser) assert ok is True - # “已参与”路径会点击关闭详情 - analyser.click.assert_called_once() + assert analyser._fudai_button_status == "可以参与" + assert analyser._fudai_button_text == "参与抽奖" + + +def test_attend_choujiang_debug_json_is_best_effort(monkeypatch, tmp_path: Path) -> None: + analyser = MagicMock() + analyser._fudai_button_status = "可以参与" + analyser._fudai_button_text = "参与抽奖" + analyser._fudai_button_ocr_time = 40_000.0 + analyser._fudai_button_room_pos = 0 + analyser.room_pos = 0 + analyser._current_fudai_future_ts = MagicMock() + analyser.click = MagicMock() + analyser._log_kv = MagicMock() + analyser.operation = MagicMock() + analyser.operation.delay = MagicMock() + + debug_log = tmp_path / "debug.log" + monkeypatch.setattr( + "douyin.core.path_config.get_debug_log_path", + lambda: str(debug_log), + ) + + import time as _time + + old_time = _time.time + _time.time = lambda: 40_001.0 + try: + ok = attend_choujiang(analyser) + finally: + _time.time = old_time + + assert ok is True diff --git a/tests/test_fudai_button_state.py b/tests/test_fudai_button_state.py index d12a4aa..481889f 100644 --- a/tests/test_fudai_button_state.py +++ b/tests/test_fudai_button_state.py @@ -1,7 +1,33 @@ from __future__ import annotations -from douyin.fudai.douyin_fudai_core_pkg.button_state import decide_button_status +from types import SimpleNamespace + +from douyin.fudai.douyin_fudai_core_pkg.button_state import ( + apply_button_ocr_result, + decide_button_status, +) def test_decide_button_status_attended_for_notice_text() -> None: assert decide_button_status("直播间,否则会失去抽奖机会") == "已参与" + + +def test_apply_button_ocr_result_records_room_pos_when_enabled() -> None: + analyser = SimpleNamespace(room_pos=12) + analyser._log_kv = lambda *args, **kwargs: None + + apply_button_ocr_result( + analyser, + button_text_raw="参与抽奖", + button_status="可以参与", + fudai_content_raw="内容", + task_list_raw="任务", + countdown_mm_raw="01", + countdown_ss_raw="30", + value_raw="500", + live_room_title_raw="直播间A", + log_prefix="测试", + record_room_pos=True, + ) + + assert analyser._fudai_button_room_pos == 12 diff --git a/tests/test_fudai_debug_overview.py b/tests/test_fudai_debug_overview.py new file mode 100644 index 0000000..5247549 --- /dev/null +++ b/tests/test_fudai_debug_overview.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from types import SimpleNamespace + +from PIL import Image + + +def test_fudai_detail_debug_overview_saves_one_annotated_image(tmp_path, monkeypatch): + from douyin.core import path_config + from douyin.fudai.core import fudai_debug_utils + + screenshot = tmp_path / "screenshot.png" + Image.new("RGB", (1080, 2400), "white").save(screenshot) + saved = [] + + def fake_save_debug_image(image, **kwargs): + saved.append((image.copy(), kwargs)) + return str(tmp_path / "overview.png") + + monkeypatch.setattr(path_config, "get_screenshot_path", lambda: str(screenshot)) + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_manager.save_debug_image", + fake_save_debug_image, + ) + + analyser = SimpleNamespace( + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *args, **kwargs: None, + ) + + result = fudai_debug_utils.save_fudai_detail_debug_overview( + analyser, + [ + { + "key": "content", + "name": "内容", + "coords": (300, 1400, 1030, 1515), + "enabled": True, + }, + { + "key": "participants", + "name": "人数", + "coords": (520, 1325, 760, 1415), + "enabled": False, + }, + ], + ui_version="v2_0", + ocr_enabled={"content"}, + task_count=1, + task_count_source="v2_pixels", + ) + + assert result + assert len(saved) == 1 + _image, kwargs = saved[0] + assert kwargs["picname"] == "福袋详情综合标注" + assert kwargs["step"] == "detail_regions" + assert kwargs["annotate"] is False + assert kwargs["extra_info"]["ui_version"] == "v2_0" diff --git a/tests/test_fudai_detail_ui_v2.py b/tests/test_fudai_detail_ui_v2.py new file mode 100644 index 0000000..264187b --- /dev/null +++ b/tests/test_fudai_detail_ui_v2.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import json +from types import SimpleNamespace + +from PIL import Image + + +def test_v2_profile_keeps_legacy_and_adds_expected_regions(): + from douyin.fudai.core.coords import ( + DETAIL_UI_LEGACY, + DETAIL_UI_V2_0, + DETAIL_UI_V2_0_ONE_TASK, + get_fudai_detail_profile, + ) + + legacy = get_fudai_detail_profile("legacy") + v2 = get_fudai_detail_profile("v2_0", task_count=2) + auto = get_fudai_detail_profile("auto", task_count=2) + one_task = get_fudai_detail_profile("v2_0", task_count=1) + + assert legacy is DETAIL_UI_LEGACY + assert v2 is DETAIL_UI_V2_0 + assert auto is DETAIL_UI_V2_0 + assert one_task is DETAIL_UI_V2_0_ONE_TASK + assert DETAIL_UI_LEGACY["content"] == (389, 1273, 1000, 1534) + assert DETAIL_UI_V2_0["content"] == (360, 1472, 1035, 1545) + assert DETAIL_UI_V2_0["value"] == (300, 1585, 650, 1685) + assert DETAIL_UI_V2_0["countdown_full"] == (760, 1355, 1035, 1455) + assert DETAIL_UI_V2_0["task_list"] == (60, 1840, 1030, 2005) + assert DETAIL_UI_V2_0["task_count"] == (860, 1770, 1035, 1875) + assert DETAIL_UI_V2_0["participants"] == (520, 1325, 760, 1415) + assert DETAIL_UI_V2_0["button"] == (70, 2020, 1010, 2165) + assert DETAIL_UI_V2_0_ONE_TASK["content"] == (360, 1472, 1035, 1545) + assert DETAIL_UI_V2_0_ONE_TASK["value"] == (340, 1680, 690, 1765) + assert DETAIL_UI_V2_0_ONE_TASK["countdown_full"] == (760, 1355, 1035, 1455) + assert DETAIL_UI_V2_0_ONE_TASK["task_list"] == (55, 1935, 900, 2055) + assert DETAIL_UI_V2_0_ONE_TASK["task_count"] == (890, 1855, 1040, 1950) + assert DETAIL_UI_V2_0_ONE_TASK["participants"] == (535, 1375, 760, 1475) + assert DETAIL_UI_V2_0_ONE_TASK["button"] == (70, 2055, 1010, 2225) + assert DETAIL_UI_V2_0_ONE_TASK["task_list"][1] > DETAIL_UI_V2_0["task_list"][1] + assert DETAIL_UI_V2_0_ONE_TASK["button"][1] > DETAIL_UI_V2_0["button"][1] + + +def test_ocr_switch_defaults_and_legacy_disable_compat(): + from douyin.fudai.douyin_fudai_core_pkg.ocr_switches import ( + FudaiDetailOcrSwitches, + resolve_fudai_detail_ocr_switches, + ) + + defaults = resolve_fudai_detail_ocr_switches({}) + assert defaults == FudaiDetailOcrSwitches( + content=True, + value=True, + countdown=True, + task=True, + task_count=True, + button=True, + participants=False, + live_title=True, + ) + + legacy = resolve_fudai_detail_ocr_switches( + { + "fudai_disable_content_recognition": True, + "fudai_disable_task_recognition": True, + } + ) + assert legacy.content is False + assert legacy.task is False + assert legacy.value is True + + explicit = resolve_fudai_detail_ocr_switches( + { + "fudai_disable_content_recognition": True, + "fudai_detail_ocr_content_enabled": True, + "fudai_detail_ocr_participants_enabled": True, + } + ) + assert explicit.content is True + assert explicit.participants is True + + +def test_static_config_defaults_include_v2_ocr_keys(): + cfg = json.loads(open("config/config.json", encoding="utf-8").read()) + + assert cfg["fudai_detail_ui_mode"] == "auto" + assert cfg["fudai_detail_ocr_content_enabled"] is True + assert cfg["fudai_detail_ocr_value_enabled"] is True + assert cfg["fudai_detail_ocr_countdown_enabled"] is True + assert cfg["fudai_detail_ocr_task_enabled"] is True + assert cfg["fudai_detail_ocr_task_count_enabled"] is True + assert cfg["fudai_detail_ocr_button_enabled"] is True + assert cfg["fudai_detail_ocr_participants_enabled"] is False + assert cfg["fudai_detail_ocr_live_title_enabled"] is True + + +def test_config_manager_loads_fudai_detail_ui_and_ocr_switches(tmp_path): + from douyin.utils.douyin_config import ConfigManager + + cfg_path = tmp_path / "config.json" + cfg_path.write_text( + json.dumps( + { + "fudai_detail_ui_mode": "legacy", + "fudai_detail_ocr_content_enabled": False, + "fudai_detail_ocr_button_enabled": True, + "fudai_detail_ocr_participants_enabled": True, + }, + ensure_ascii=False, + ), + encoding="utf-8", + ) + analyser = SimpleNamespace(config_path=str(cfg_path), needswitch=None) + + ConfigManager.load_config_from_file(analyser, str(cfg_path)) + + assert analyser.fudai_detail_ui_mode == "legacy" + assert analyser.fudai_detail_ocr_content_enabled is False + assert analyser.fudai_detail_ocr_button_enabled is True + assert analyser.fudai_detail_ocr_participants_enabled is True + + +def test_v2_task_count_ocr_tries_one_task_shifted_region_first(): + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2 + + calls = [] + + class _Operation: + def analyse_pic_word(self, name, _mode): + calls.append(name) + if name == "福袋任务数量_v2_1task": + return "(0/1)" + return "" + + def analyse_pic_digits(self, name, _mode): + calls.append(name) + return "" + + class _Analyser: + y_pianyi = 0 + operation = _Operation() + + def cut_pic(self, x1, y1, x2, y2, _prefix, name, _offset): + calls.append((name, (x1, y1, x2, y2))) + + def _log_kv(self, *_args, **_kwargs): + return None + + assert _check_detail_task_count_v2(_Analyser()) == 1 + assert ("福袋任务数量_v2_1task", (890, 1855, 1040, 1950)) in calls + assert "福袋任务数量_v2" not in calls + + +def test_v2_task_count_pixels_choose_one_task_before_ocr(tmp_path, monkeypatch): + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels + + screenshot_path = tmp_path / "one_task.png" + img = Image.new("RGB", (1080, 2400), (10, 15, 46)) + img.putpixel((536, 1970), (255, 255, 255)) + img.save(screenshot_path) + monkeypatch.setattr( + "douyin.core.path_config.get_screenshot_path", + lambda: str(screenshot_path), + ) + + analyser = SimpleNamespace( + fudai_detail_ui_mode="auto", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *_args, **_kwargs: None, + ) + + assert _check_detail_task_count_v2_pixels(analyser) == 1 + assert analyser._fudai_detail_task_count_source == "v2_pixels" + + +def test_v2_task_count_pixels_choose_two_task_from_dark_card(tmp_path, monkeypatch): + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels + + screenshot_path = tmp_path / "two_task.png" + img = Image.new("RGB", (1080, 2400), (10, 15, 46)) + img.save(screenshot_path) + monkeypatch.setattr( + "douyin.core.path_config.get_screenshot_path", + lambda: str(screenshot_path), + ) + + analyser = SimpleNamespace( + fudai_detail_ui_mode="v2_0", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *_args, **_kwargs: None, + ) + + assert _check_detail_task_count_v2_pixels(analyser) == 2 + + +def test_v2_task_count_pixels_disabled_for_legacy(tmp_path, monkeypatch): + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels + + screenshot_path = tmp_path / "legacy.png" + Image.new("RGB", (1080, 2400), (255, 255, 255)).save(screenshot_path) + monkeypatch.setattr( + "douyin.core.path_config.get_screenshot_path", + lambda: str(screenshot_path), + ) + + analyser = SimpleNamespace( + fudai_detail_ui_mode="legacy", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + ) + + assert _check_detail_task_count_v2_pixels(analyser) == 0 + + +def test_check_detail_height_v2_does_not_fallback_to_legacy_pixels(monkeypatch): + from douyin.detection.detection_pkg import detail + + monkeypatch.setattr(detail, "_check_detail_task_count_v2_pixels", lambda _analyser: 0) + monkeypatch.setattr(detail, "_check_detail_task_count_v2", lambda _analyser: 0) + + def _legacy_should_not_run(_analyser): + raise AssertionError("v2 mode must not fallback to legacy pixel detection") + + monkeypatch.setattr(detail, "_check_detail_task_count_legacy_pixels", _legacy_should_not_run) + + analyser = SimpleNamespace(fudai_detail_ui_mode="v2_0") + + assert detail.check_detail_height(analyser) == 0 + + +def test_check_detail_height_legacy_uses_legacy_pixels(monkeypatch): + from douyin.detection.detection_pkg import detail + + monkeypatch.setattr(detail, "_check_detail_task_count_legacy_pixels", lambda _analyser: 3) + + analyser = SimpleNamespace(fudai_detail_ui_mode="legacy") + + assert detail.check_detail_height(analyser) == 3 diff --git a/tests/test_fudai_filter_pkg.py b/tests/test_fudai_filter_pkg.py index 2c65733..ce0bd2c 100644 --- a/tests/test_fudai_filter_pkg.py +++ b/tests/test_fudai_filter_pkg.py @@ -103,7 +103,7 @@ class TestShouldSkipFudaiByConfig: def test_high_value_passes(self): analyser = self._mock() - detail = ('现金1000元', '2分钟', 50, 1, 1000.0, + detail = ('现金1000元', '02:00', 50, 1, 1000.0, (time.time()+120, time.time()+120)) skip, reason = should_skip_fudai_by_config(analyser, detail) assert skip is False @@ -119,14 +119,14 @@ class TestShouldSkipFudaiByConfig: def test_low_value_skips(self): analyser = self._mock(min_prize_value_yuan=500.0) - detail = ('现金100元', '2分钟', 50, 1, 100.0, + detail = ('现金100元', '02:00', 50, 1, 100.0, (time.time()+120, time.time()+120)) skip, _ = should_skip_fudai_by_config(analyser, detail) assert skip is True def test_blacklist_skips(self): analyser = self._mock(contains_not_want=["袜子"]) - detail = ('袜子礼盒', '2分钟', 50, 1, 500.0, + detail = ('袜子礼盒', '02:00', 50, 1, 500.0, (time.time()+120, time.time()+120)) skip, _ = should_skip_fudai_by_config(analyser, detail) assert skip is True @@ -134,7 +134,7 @@ class TestShouldSkipFudaiByConfig: def test_single_room_mode_passes_always(self): # needswitch=False 时不论价值都不跳过 analyser = self._mock(needswitch=False, min_prize_value_yuan=1e9) - detail = ('现金1元', '2分钟', 50, 1, 1.0, + detail = ('现金1元', '02:00', 50, 1, 1.0, (time.time()+120, time.time()+120)) skip, reason = should_skip_fudai_by_config(analyser, detail) assert skip is False diff --git a/tests/test_gui_core_pkg.py b/tests/test_gui_core_pkg.py index 426eee3..ec1f46b 100644 --- a/tests/test_gui_core_pkg.py +++ b/tests/test_gui_core_pkg.py @@ -6,7 +6,10 @@ adb 真实命令 / wifi_adb 涉及网络与设备,仅做"可调用 + 不抛" from __future__ import annotations import dataclasses +import json import os +import threading +from unittest.mock import MagicMock import pytest @@ -30,9 +33,9 @@ class TestRunParams: assert dataclasses.is_dataclass(RunParams) def test_field_count(self): - # RunParams 当前有 28 个字段(与拆分时一致) + # RunParams 字段会随配置扩展增加,至少应保留原核心字段数量。 fields = dataclasses.fields(RunParams) - assert len(fields) == 28 + assert len(fields) >= 28 def test_field_types(self): """关键字段的类型注解。""" @@ -108,6 +111,33 @@ class TestReadConfig: assert cfg1 == cfg2 +class TestFudaiDetailOcrGuiConfig: + def test_build_config_vars_exposes_fudai_detail_ocr_switches(self, monkeypatch): + import tkinter as tk + + from gui.components.config_vars import build_config_vars + + monkeypatch.setattr(tk, "StringVar", lambda value="": MagicMock(get=lambda: value, set=lambda _v: None)) + monkeypatch.setattr(tk, "BooleanVar", lambda value=False: MagicMock(get=lambda: value, set=lambda _v: None)) + monkeypatch.setattr(tk, "IntVar", lambda value=0: MagicMock(get=lambda: value, set=lambda _v: None)) + monkeypatch.setattr(tk, "DoubleVar", lambda value=0.0: MagicMock(get=lambda: value, set=lambda _v: None)) + + vars_ = build_config_vars({}) + + for key in ( + "fudai_detail_ui_mode_var", + "fudai_detail_ocr_content_enabled_var", + "fudai_detail_ocr_value_enabled_var", + "fudai_detail_ocr_countdown_enabled_var", + "fudai_detail_ocr_task_enabled_var", + "fudai_detail_ocr_task_count_enabled_var", + "fudai_detail_ocr_button_enabled_var", + "fudai_detail_ocr_participants_enabled_var", + "fudai_detail_ocr_live_title_enabled_var", + ): + assert key in vars_ + + class TestWriteConfig: def test_write_and_read_roundtrip(self): # 读出 → 写回(不改任何字段)→ 再读出,应一致 @@ -117,6 +147,45 @@ class TestWriteConfig: # 至少键集相等(具体值可能因写入时序略有变动) assert set(original.keys()) == set(after.keys()) + def test_write_config_merges_nested_dicts(self, tmp_path, monkeypatch): + from gui.gui_core_pkg import config as cfg_mod + + cfg_path = tmp_path / "config.json" + cfg_path.write_text( + json.dumps({"logging": {"keep_days": 7, "compress_logs": True}, "other": 1}, ensure_ascii=False), + encoding="utf-8", + ) + monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(cfg_path)) + + cfg_mod.write_config({"logging": {"keep_days": 3}}) + + saved = json.loads(cfg_path.read_text(encoding="utf-8")) + assert saved["logging"]["keep_days"] == 3 + assert saved["logging"]["compress_logs"] is True + assert saved["other"] == 1 + + def test_write_config_concurrent_updates_keep_both_keys(self, tmp_path, monkeypatch): + from gui.gui_core_pkg import config as cfg_mod + + cfg_path = tmp_path / "config.json" + cfg_path.write_text(json.dumps({"base": 1}, ensure_ascii=False), encoding="utf-8") + monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(cfg_path)) + + def _writer(payload): + cfg_mod.write_config(payload) + + t1 = threading.Thread(target=_writer, args=({"alpha": 1},), daemon=True) + t2 = threading.Thread(target=_writer, args=({"beta": 2},), daemon=True) + t1.start() + t2.start() + t1.join(timeout=1) + t2.join(timeout=1) + + saved = json.loads(cfg_path.read_text(encoding="utf-8")) + assert saved["base"] == 1 + assert saved["alpha"] == 1 + assert saved["beta"] == 2 + # ============================================================ # adb.py — find_adb_executable / list_adb_devices / resolve_adb_device @@ -142,3 +211,98 @@ class TestAdbFunctions: # 指定了不存在的 device_id 应抛 RuntimeError with pytest.raises(RuntimeError): resolve_adb_device("", "nonexistent_device_xyz") + + +class TestWifiAdbDialog: + def test_open_wifi_adb_dialog_binds_toggle_button_without_nameerror(self, monkeypatch): + from gui.components import wifi_adb_dialog as mod + + class _FakeWidget: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + self.configs = {} + + def pack(self, *args, **kwargs): + return None + + def grid(self, *args, **kwargs): + return None + + def grid_columnconfigure(self, *_args, **_kwargs): + return None + + def grid_rowconfigure(self, *_args, **_kwargs): + return None + + def config(self, **kwargs): + self.configs.update(kwargs) + + configure = config + + def __setitem__(self, key, value): + self.configs[key] = value + + def __getitem__(self, key): + return self.configs[key] + + class _FakeDialog(_FakeWidget): + def title(self, *_args, **_kwargs): + return None + + def geometry(self, *_args, **_kwargs): + return "500x450" + + def resizable(self, *_args, **_kwargs): + return None + + def minsize(self, *_args, **_kwargs): + return None + + def grid_columnconfigure(self, *_args, **_kwargs): + return None + + def update_idletasks(self): + return None + + def winfo_screenwidth(self): + return 1000 + + def winfo_screenheight(self): + return 800 + + def destroy(self): + return None + + created_buttons = [] + + def _fake_button(*args, **kwargs): + created_buttons.append(kwargs) + return _FakeWidget(*args, **kwargs) + + monkeypatch.setattr(mod.tk, "Toplevel", lambda parent: _FakeDialog(parent)) + monkeypatch.setattr(mod.ttk, "LabelFrame", _FakeWidget) + monkeypatch.setattr(mod.ttk, "Frame", _FakeWidget) + monkeypatch.setattr(mod.ttk, "Label", _FakeWidget) + monkeypatch.setattr(mod.ttk, "Combobox", _FakeWidget) + monkeypatch.setattr(mod.ttk, "Entry", _FakeWidget) + monkeypatch.setattr(mod.ttk, "Button", _fake_button) + monkeypatch.setattr( + mod.tk, + "StringVar", + lambda value="": MagicMock(get=lambda: value, set=lambda _v: None), + ) + monkeypatch.setattr(mod, "list_adb_devices", lambda _adb: []) + monkeypatch.setattr(mod, "get_connected_wifi_devices", lambda _adb: []) + + mod.open_wifi_adb_dialog( + MagicMock(), + adb_exe="adb", + on_line=lambda _msg: None, + refresh_devices=lambda: None, + ) + + assert any( + btn.get("text") == "放大/恢复" and callable(btn.get("command")) + for btn in created_buttons + ) diff --git a/tests/test_handle_detail_filter.py b/tests/test_handle_detail_filter.py new file mode 100644 index 0000000..6d60939 --- /dev/null +++ b/tests/test_handle_detail_filter.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import time +from unittest.mock import MagicMock, patch + +from douyin.core.fudai_modules import handle_detail_filter as hdf + + +def _mk_self(): + s = MagicMock() + s._log_kv = MagicMock(return_value=None) + s.high_value_fudai_enabled = True + s.high_value_fudai_threshold_yuan = 500.0 + s.high_value_fudai_join_ahead_seconds = 100 + return s + + +def test_high_value_reservation_failure_falls_back_to_still_skip(): + s = _mk_self() + future_ts = time.time() + 600 + detail = ("高价值福袋", 0, 0, 0, 1000.0, (time.time(), future_ts, 600)) + + with patch( + "douyin.fudai.douyin_fudai_core.basic_join_decision", + side_effect=RuntimeError("record failed"), + ): + result = hdf.try_high_value_reservation( + s, detail, True, "countdown_gt_30", 0.0 + ) + + assert result == "still_skip" diff --git a/tests/test_handle_detail_helpers.py b/tests/test_handle_detail_helpers.py index e0cb084..be67147 100644 --- a/tests/test_handle_detail_helpers.py +++ b/tests/test_handle_detail_helpers.py @@ -330,6 +330,21 @@ class TestPrepareForAttend: assert result == 0.0 +# ============================================================ +# check_invalid_detail_fallback +# ============================================================ + +class TestCheckInvalidDetailFallback: + def test_invalid_detail_clears_first_read_and_cached_tuple(self): + s = _mk_self() + s._fudai_detail_first_read = True + s._last_fudai_detail_tuple = ("stale",) + detail = ("", "", 0, 0, 0.0, (0, 0, 0)) + assert hd.check_invalid_detail_fallback(s, detail, 0.0) is True + assert s._fudai_detail_first_read is False + assert s._last_fudai_detail_tuple is None + + # ============================================================ # check_last_status_branch # ============================================================ @@ -360,16 +375,19 @@ class TestCheckLastStatusBranch: s = self._mk_for_status("coupon_popup") assert hd.check_last_status_branch(s, 0.0) is True assert s._fudai_detail_task_count_from_stage is None + assert s._last_fudai_detail_status == "" def test_watch_task_returns_true_clears_task_count(self): s = self._mk_for_status("watch_task") assert hd.check_last_status_branch(s, 0.0) is True assert s._fudai_detail_task_count_from_stage is None + assert s._last_fudai_detail_status == "" def test_validation_failed_returns_true_clears_task_count(self): s = self._mk_for_status("validation_failed") assert hd.check_last_status_branch(s, 0.0) is True assert s._fudai_detail_task_count_from_stage is None + assert s._last_fudai_detail_status == "" def test_error_without_task_count_zero_reason_returns_false(self): """error 但 reason 不是 task_count_zero → 不在此处理。""" @@ -386,6 +404,21 @@ class TestCheckLastStatusBranch: assert result is True assert s._fudai_detail_consecutive_failures == 1 s.swipe_up_to_next_live.assert_not_called() + assert s._last_fudai_detail_status == "" + assert s._last_fudai_detail_extra == {} + + def test_error_not_in_fudai_detail_first_failure(self): + """read_once 返回的 not_in_fudai_detail 也应走同一条连续失败保护。""" + s = self._mk_for_status("error", last_extra={"reason": "not_in_fudai_detail"}) + s._fudai_detail_consecutive_failures = 0 + s.swipe_up_to_next_live = MagicMock(return_value=None) + with patch("douyin.fudai.douyin_fudai_detail.close_fudai_detail"): + result = hd.check_last_status_branch(s, 0.0) + assert result is True + assert s._fudai_detail_consecutive_failures == 1 + s.swipe_up_to_next_live.assert_not_called() + assert s._last_fudai_detail_status == "" + assert s._last_fudai_detail_extra == {} def test_error_task_count_zero_third_failure_swipes(self): """task_count_zero 第 3 次:强制关详情 + 切直播间 + 重置计数。""" @@ -472,6 +505,8 @@ class TestHandleFirstOpenBranch: result = hd.handle_first_open_branch(s, 0.0) assert result is True mock_close.assert_called_once() + assert s._fudai_detail_first_read is False + assert s._last_fudai_detail_tuple is None def test_filter_pass_saves_data_returns_false(self): """筛选通过 → 保存 detail + 标记 first_read,return False 让 caller 继续。""" @@ -495,6 +530,27 @@ class TestHandleFirstOpenBranch: assert s._fudai_detail_first_read is True assert s._current_fudai_content == "有效福袋" + def test_special_status_does_not_mark_first_read(self): + """若 read_with_retries 已产出终止类状态,不应把详情误标成 second-open。""" + import time + + s = self._mk_for_first_open() + s._last_fudai_detail_status = "watch_task" + detail = ("X", 0, 0, 0, 100.0, (0, time.time() + 60, 60)) + with patch( + "douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries", + return_value=detail, + ), patch( + "douyin.fudai.douyin_fudai_detail.validate_fudai_detail", + return_value=(True, ""), + ), patch( + "douyin.fudai.douyin_fudai_core.should_skip_fudai_by_config", + return_value=(False, ""), + ): + result = hd.handle_first_open_branch(s, 0.0) + assert result is False + assert s._fudai_detail_first_read is False + def test_filter_skip_normal_closes_and_swipes(self): """普通筛选不通过(非高价值)→ 关详情 + 切直播间 + return True。""" import time @@ -518,6 +574,8 @@ class TestHandleFirstOpenBranch: assert result is True mock_close.assert_called_once() s.swipe_up_to_next_live.assert_called_once() + assert s._fudai_detail_first_read is False + assert s._last_fudai_detail_tuple is None def test_filter_skip_no_switch_when_needswitch_false(self): """needswitch=False 筛选不通过时不切直播间。""" @@ -629,6 +687,19 @@ class TestHandleSecondOpenBranch: assert s._last_fudai_detail_tuple == new_detail assert s._current_fudai_content == "X" + def test_refetch_special_status_clears_first_read_flag(self): + """第二次打开重读后若状态已终止,不应继续保留 second-open 标志。""" + s = self._mk_for_second_open() + s._last_fudai_detail_tuple = None + s._last_fudai_detail_status = "watch_task" + with patch( + "douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries", + return_value=("X", 0, 0, 0, 100.0, (0, 60.0, 60)), + ): + result = hd.handle_second_open_branch(s, 0.0, 0.0) + assert result is False + assert s._fudai_detail_first_read is False + def test_short_tuple_triggers_refetch(self): """缓存 tuple 长度 < 6 → 触发重新读取。""" s = self._mk_for_second_open() @@ -640,6 +711,19 @@ class TestHandleSecondOpenBranch: result = hd.handle_second_open_branch(s, 0.0, 0.0) assert result is False mock_read.assert_called_once() + assert s._fudai_detail_first_read is False + + def test_refetch_invalid_detail_clears_first_read_flag(self): + """第二次打开重读后仍拿不到有效 detail,不应无限保留 second-open 状态。""" + s = self._mk_for_second_open() + s._last_fudai_detail_tuple = None + with patch( + "douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries", + return_value=None, + ): + result = hd.handle_second_open_branch(s, 0.0, 0.0) + assert result is False + assert s._fudai_detail_first_read is False def test_attend_success_returns_true_clears_failures(self): """attend_choujiang 成功 → 清标志 + 清失败计数 + return True。""" diff --git a/tests/test_high_value_room.py b/tests/test_high_value_room.py new file mode 100644 index 0000000..317d719 --- /dev/null +++ b/tests/test_high_value_room.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import json + + +def test_save_high_value_rooms_is_atomic(tmp_path, monkeypatch): + from douyin.other import douyin_high_value_room as mod + + target = tmp_path / "high_value_rooms.json" + monkeypatch.setattr(mod, "HIGH_VALUE_ROOMS_PATH", target) + + mod._save_high_value_rooms({"updated_ts": 1, "total": 0, "rooms": []}) + + data = json.loads(target.read_text(encoding="utf-8")) + assert data["updated_ts"] == 1 + assert data["rooms"] == [] + assert not target.with_suffix(target.suffix + ".tmp").exists() diff --git a/tests/test_imports.py b/tests/test_imports.py index c383d4c..34fc32a 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -159,3 +159,191 @@ class TestKeyExports: "_safe_replace_file", ): assert hasattr(operations, name), f"operations 包缺少导出 {name}" + + def test_operations_package_import_tolerates_missing_optional_runtime_deps(self, monkeypatch): + """operations 包在缺少 Pillow 这类可安装依赖时,不应因为 eager import 直接炸掉。""" + import sys + + to_drop = [k for k in list(sys.modules) if k == "operations" or k.startswith("operations.")] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + real_import = __import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "PIL" or name.startswith("PIL."): + raise ModuleNotFoundError("No module named 'PIL'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr("builtins.__import__", fake_import) + try: + mod = importlib.import_module("operations") + assert hasattr(mod, "analyse_pic_word") + finally: + sys.modules.pop("operations", None) + for key in [k for k in list(sys.modules) if k.startswith("operations.")]: + sys.modules.pop(key, None) + sys.modules.update(saved) + + def test_screenshot_service_import_tolerates_missing_pillow(self, monkeypatch): + """截图服务模块不应在 import 阶段强依赖 Pillow。""" + import sys + + to_drop = [k for k in list(sys.modules) if k == "operations" or k.startswith("operations.")] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + real_import = __import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "PIL" or name.startswith("PIL."): + raise ModuleNotFoundError("No module named 'PIL'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr("builtins.__import__", fake_import) + try: + mod = importlib.import_module("operations.screenshot_service") + assert hasattr(mod, "ScreenshotService") + finally: + for key in [k for k in list(sys.modules) if k == "operations" or k.startswith("operations.")]: + sys.modules.pop(key, None) + sys.modules.update(saved) + + def test_read_with_retries_import_tolerates_missing_pillow(self, monkeypatch): + """read_with_retries 作为高层重试入口,不应被 read_once 的 PIL 依赖卡死。""" + import sys + + prefixes = ( + "douyin.fudai.core.fudai_detail_orchestrator_pkg", + "douyin.fudai.core.fudai_detail_orchestrator", + ) + to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + real_import = __import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "PIL" or name.startswith("PIL."): + raise ModuleNotFoundError("No module named 'PIL'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr("builtins.__import__", fake_import) + try: + mod = importlib.import_module("douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries") + assert hasattr(mod, "read_fudai_detail_with_retries") + finally: + for key in [k for k in list(sys.modules) if k.startswith(prefixes)]: + sys.modules.pop(key, None) + sys.modules.update(saved) + + def test_read_with_retries_module_import_tolerates_missing_pillow(self, monkeypatch): + """read_with_retries 自身不应留下无用的 PIL 顶层依赖。""" + import sys + + prefixes = ("douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries",) + to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + real_import = __import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "PIL" or name.startswith("PIL."): + raise ModuleNotFoundError("No module named 'PIL'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr("builtins.__import__", fake_import) + try: + mod = importlib.import_module("douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries") + assert hasattr(mod, "read_fudai_detail_with_retries") + finally: + for key in [k for k in list(sys.modules) if k.startswith(prefixes)]: + sys.modules.pop(key, None) + sys.modules.update(saved) + + def test_douyin_detection_import_tolerates_missing_pillow(self, monkeypatch): + """detection 包的顶层 shim 不应被 finder 的 PIL 依赖卡死。""" + import sys + + prefixes = ( + "douyin.detection.detection_pkg", + "douyin.detection.douyin_detection", + ) + to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + real_import = __import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "PIL" or name.startswith("PIL."): + raise ModuleNotFoundError("No module named 'PIL'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr("builtins.__import__", fake_import) + try: + mod = importlib.import_module("douyin.detection.douyin_detection") + assert hasattr(mod, "check_have_fudai_with_ready_screenshot") + finally: + for key in [k for k in list(sys.modules) if k.startswith(prefixes)]: + sys.modules.pop(key, None) + sys.modules.update(saved) + + def test_douyin_fudai_import_tolerates_missing_pillow(self, monkeypatch): + """douyin_fudai 主入口不应被若干调试/识别模块的 PIL 顶层导入卡死。""" + import sys + + prefixes = ( + "douyin.core.douyin_fudai", + "douyin.detection", + "douyin.fudai.core.fudai_debug_utils", + ) + to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + real_import = __import__ + + def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "PIL" or name.startswith("PIL."): + raise ModuleNotFoundError("No module named 'PIL'") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr("builtins.__import__", fake_import) + try: + mod = importlib.import_module("douyin.core.douyin_fudai") + assert hasattr(mod, "fudai_analyse") + finally: + for key in [k for k in list(sys.modules) if k.startswith(prefixes)]: + sys.modules.pop(key, None) + sys.modules.update(saved) + + def test_douyin_logging_import_chain_has_no_monitor_cycle(self): + """日志兼容入口不应再因为 monitor/config 相互导入而初始化失败。""" + import sys + + prefixes = ( + "douyin.logging.douyin_logging", + "douyin.logging.douyin_logging_pkg", + ) + to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)] + saved = {k: sys.modules[k] for k in to_drop} + for key in to_drop: + sys.modules.pop(key, None) + + try: + mod = importlib.import_module("douyin.logging.douyin_logging") + assert hasattr(mod, "configure_logging") + assert hasattr(mod, "start_log_monitor") + assert hasattr(mod, "stop_log_monitor") + finally: + for key in [k for k in list(sys.modules) if k.startswith(prefixes)]: + sys.modules.pop(key, None) + sys.modules.update(saved) diff --git a/tests/test_logger_helpers.py b/tests/test_logger_helpers.py index c005a6d..6b8cdee 100644 --- a/tests/test_logger_helpers.py +++ b/tests/test_logger_helpers.py @@ -9,6 +9,7 @@ """ from __future__ import annotations +import importlib import logging import pytest @@ -120,3 +121,31 @@ def test_broken_analyser_does_not_raise(module_path, helper_name): fn = _import_helper(module_path, helper_name) # 不应抛任何异常 fn(BrokenAnalyser(), "[test] broken", level="ERROR") + + +@pytest.mark.parametrize( + "module_path,helper_name", + [ + ("operations.screenshot_service", "_svc_log"), + ("operations.ocr_operations", "_ocr_log"), + ], +) +def test_logger_failure_falls_back_to_print(module_path, helper_name, monkeypatch): + """logger 自身异常时,helper 应直接兜底到 print,而不是递归调用自身。""" + mod = importlib.import_module(module_path) + fn = getattr(mod, helper_name) + + class BrokenLogger: + def info(self, *_args, **_kwargs): + raise RuntimeError("logger broken") + + warning = error = debug = info + + printed: list[str] = [] + + monkeypatch.setattr(mod, "_LOGGER", BrokenLogger()) + monkeypatch.setattr("builtins.print", lambda msg: printed.append(str(msg))) + + fn("[test] print fallback") + + assert printed == ["[test] print fallback"] diff --git a/tests/test_lottery_result_confirm_v2.py b/tests/test_lottery_result_confirm_v2.py new file mode 100644 index 0000000..0cd5e23 --- /dev/null +++ b/tests/test_lottery_result_confirm_v2.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +from types import SimpleNamespace + + +def test_lottery_result_ocr_uses_v2_confirm_region(monkeypatch): + from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_V2 + from douyin.utils.douyin_helpers import HelperFunctions + + calls = [] + + class _Operation: + def analyse_pic_word(self, _name, _mode=0): + return "我知道了" + + analyser = SimpleNamespace( + fudai_detail_ui_mode="v2_0", + operation=_Operation(), + _log_kv=lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_handler.ScreenshotHandler.cut_pic", + lambda _analyser, x1, y1, x2, y2, *_args: calls.append((x1, y1, x2, y2)), + ) + monkeypatch.setattr( + "douyin.utils.ocr_preprocess.preprocess_for_ocr", + lambda _analyser, picname: picname, + ) + + assert HelperFunctions.check_lottery_result_by_ocr(analyser) == "我知道了" + assert calls == [LOTTERY_RESULT_CONFIRM_BUTTON_V2] + + +def test_lottery_result_click_uses_v2_confirm_point(): + from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_CLICK_V2 + from douyin.utils.douyin_helpers import HelperFunctions + + clicks = [] + + class _Operation: + def click(self, _device_id, x, y): + clicks.append((x, y)) + + def delay(self, _seconds): + return None + + analyser = SimpleNamespace( + fudai_detail_ui_mode="v2_0", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + device_id="device", + needswitch=False, + operation=_Operation(), + _log_kv=lambda *_args, **_kwargs: None, + ) + + HelperFunctions.handle_lottery_result_by_ocr(analyser, "我知道了") + + assert clicks[0] == LOTTERY_RESULT_CONFIRM_CLICK_V2 + + +def test_lottery_result_click_keeps_legacy_confirm_point(): + from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_CLICK_V1 + from douyin.utils.douyin_helpers import HelperFunctions + + clicks = [] + + class _Operation: + def click(self, _device_id, x, y): + clicks.append((x, y)) + + def delay(self, _seconds): + return None + + analyser = SimpleNamespace( + fudai_detail_ui_mode="legacy", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + device_id="device", + needswitch=False, + operation=_Operation(), + _log_kv=lambda *_args, **_kwargs: None, + ) + + HelperFunctions.handle_lottery_result_by_ocr(analyser, "我知道了") + + assert clicks[0] == LOTTERY_RESULT_CONFIRM_CLICK_V1 diff --git a/tests/test_operations.py b/tests/test_operations.py index 7bf9c68..c780189 100644 --- a/tests/test_operations.py +++ b/tests/test_operations.py @@ -7,6 +7,11 @@ from __future__ import annotations +import os +import threading +from pathlib import Path +from unittest.mock import MagicMock + import pytest @@ -126,6 +131,87 @@ class TestScreenshotOperations: assert callable(save_reward_pic) + def test_find_pic_path_does_not_fall_back_to_operations_dir_for_reading( + self, tmp_path, monkeypatch + ): + from operations.screenshot_operations import ScreenshotOperations + from douyin.core import path_config + + pic_dir = tmp_path / "pic" + pic_dir.mkdir() + target_dir = tmp_path / "target_pic" + target_dir.mkdir() + fake_ops_dir = tmp_path / "operations" + fake_ops_dir.mkdir() + stray = fake_ops_dir / "foo.png" + stray.write_bytes(b"x") + + monkeypatch.setattr(path_config, "get_pic_dir", lambda: str(pic_dir)) + monkeypatch.setattr("operations.screenshot_operations.os.path.dirname", lambda _p: str(fake_ops_dir)) + + path = ScreenshotOperations()._find_pic_path("foo.png", for_reading=True) + assert path is None + + +class TestCutPicDebug: + """cut_pic 调试图保存策略测试。""" + + def test_fudai_detail_field_skips_cut_pic_debug(self, monkeypatch): + from PIL import Image + from douyin.core.underlying_operations_pkg.image_ops import _save_cut_debug_images + + saved = [] + monkeypatch.setenv("SAVE_CUT_PIC_DEBUG_IMAGES", "1") + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_manager.save_debug_image", + lambda *args, **kwargs: saved.append((args, kwargs)) or "debug.png", + ) + + img = Image.new("RGB", (20, 20), "white") + _save_cut_debug_images( + MagicMock(), + img, + img, + "福袋内容", + "screenshot.png", + 1, + 2, + 10, + 12, + ) + + assert saved == [] + + def test_non_fudai_field_keeps_cut_pic_debug(self, monkeypatch): + from PIL import Image + from douyin.core.underlying_operations_pkg.image_ops import _save_cut_debug_images + + saved = [] + monkeypatch.setenv("SAVE_CUT_PIC_DEBUG_IMAGES", "1") + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_manager.save_latest_attempt", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_manager.save_debug_image", + lambda *args, **kwargs: saved.append((args, kwargs)) or "debug.png", + ) + + img = Image.new("RGB", (20, 20), "white") + _save_cut_debug_images( + MagicMock(), + img, + img, + "普通字段", + "screenshot.png", + 1, + 2, + 10, + 12, + ) + + assert len(saved) == 1 + class TestScreenshotService: """screenshot_service 模块测试。""" @@ -142,6 +228,47 @@ class TestScreenshotService: assert isinstance(workers, int) assert workers >= 1 + def test_start_switch_device_does_not_deadlock(self, monkeypatch): + from operations.screenshot_service import ScreenshotService + + svc = ScreenshotService() + svc._running = True + svc._current_device_id = "old-device" + fake_thread = MagicMock() + fake_thread.is_alive.return_value = False + svc._thread = fake_thread + + created_threads: list[tuple[object, tuple, dict]] = [] + + def _fake_thread_ctor(*args, **kwargs): + created_threads.append((args, tuple(), kwargs)) + t = MagicMock() + t.start.return_value = None + t.is_alive.return_value = False + return t + + monkeypatch.setattr("operations.screenshot_service.threading.Thread", _fake_thread_ctor) + monkeypatch.setattr("operations.screenshot_service.path_config.get_screenshot_path", lambda: "pic/screenshot.png") + + done = threading.Event() + err: list[BaseException] = [] + + def _runner(): + try: + svc.start("new-device") + except BaseException as exc: # pragma: no cover - test helper + err.append(exc) + finally: + done.set() + + t = threading.Thread(target=_runner, daemon=True) + t.start() + + assert done.wait(1.0), "switching ScreenshotService device should not deadlock" + assert not err + assert svc._current_device_id == "new-device" + assert len(created_threads) == 1 + class TestOcrProcessor: """OCRProcessor 类测试。""" diff --git a/tests/test_other_modules.py b/tests/test_other_modules.py index ba22e57..abec499 100644 --- a/tests/test_other_modules.py +++ b/tests/test_other_modules.py @@ -8,6 +8,10 @@ from __future__ import annotations +import time +from types import SimpleNamespace +from unittest.mock import MagicMock + import pytest @@ -157,6 +161,29 @@ class TestDouyinYanghaoShimConsistency: assert f1 is f2 +class TestTimedYanghaoTrigger: + def test_maybe_run_yanghao_uses_recommend_flow(self): + from douyin.core.douyin_fudai import fudai_analyse + + s = SimpleNamespace() + s.yanghao_recommend_interval_seconds = 60 + s.yanghao_recommend_duration_seconds = 30 + s._waiting_for_lottery_result = False + s._current_attending_reservation_fudai = False + s.reservations = [] + s.reservation_focus_until_ts = 0.0 + s._last_yanghao_ts = 0.0 + s._log_kv = MagicMock(return_value=None) + s._yanghao_recommend_flow = MagicMock(return_value=None) + s._yanghao_wait = MagicMock(return_value=None) + + fudai_analyse._maybe_run_yanghao_during_run(s) + + s._yanghao_recommend_flow.assert_called_once_with(30) + s._yanghao_wait.assert_not_called() + assert s._last_yanghao_ts > 0.0 + + class TestOtherModules: """other 子模块存在性测试。""" diff --git a/tests/test_path_config.py b/tests/test_path_config.py index ab89d09..72afc74 100644 --- a/tests/test_path_config.py +++ b/tests/test_path_config.py @@ -97,6 +97,11 @@ class TestSpecificPaths: path = path_config.get_actions_log_path() assert path.endswith(os.path.join("logs", "actions.log")) + def test_web_gui_host_ignores_generic_host_env(self, monkeypatch): + monkeypatch.delenv("WEB_GUI_HOST", raising=False) + monkeypatch.setenv("HOST", "0.0.0.0") + assert path_config.get_web_gui_host() == path_config.DEFAULT_WEB_GUI_HOST + # ============================================================ # 路径间不应互相重复 diff --git a/tests/test_pkg_internals.py b/tests/test_pkg_internals.py index 4b8758d..928c426 100644 --- a/tests/test_pkg_internals.py +++ b/tests/test_pkg_internals.py @@ -176,6 +176,28 @@ class TestReservationLogicCommon: ) assert isinstance(_RESERVATION_ERROR_UTILS_AVAILABLE, bool) + def test_add_and_attend_window_import_error_flag(self): + from douyin.reservation.reservation_logic import add, attend_window + + assert isinstance(add._RESERVATION_ERROR_UTILS_AVAILABLE, bool) + assert isinstance(attend_window._RESERVATION_ERROR_UTILS_AVAILABLE, bool) + + def test_attend_window_imports_runtime_helpers(self): + from douyin.reservation.reservation_logic import attend_window + from douyin.reservation.reservation_logic.cleanup_validate import ( + cleanup_expired_reservations, + ) + + assert attend_window.cleanup_expired_reservations is cleanup_expired_reservations + + def test_seek_room_imports_dump_state_helper(self): + from douyin.reservation.douyin_reservation_handler_pkg import seek_room + from douyin.reservation.douyin_reservation_handler_pkg.dump_state import ( + _dump_room_pos_map_to_state, + ) + + assert seek_room._dump_room_pos_map_to_state is _dump_room_pos_map_to_state + # ============================================================ # logging_wrapper_pkg._common diff --git a/tests/test_read_once_service_recovery.py b/tests/test_read_once_service_recovery.py new file mode 100644 index 0000000..dbaa914 --- /dev/null +++ b/tests/test_read_once_service_recovery.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import sys +from types import ModuleType, SimpleNamespace +from unittest.mock import MagicMock, patch + + +def _mk_analyser(): + a = SimpleNamespace() + a._log_kv = MagicMock(return_value=None) + a._fudai_detail_task_count_from_stage = 1 + a._screenshot_ready_for_ocr = False + a.device_id = "MOCK_DEVICE" + a.enable_streaming_screenshot = True + a.operation = SimpleNamespace( + get_screenshot=lambda *_a, **_k: True, + check_countdown=lambda _text: (30, 1234567890.0), + ) + a.current_room_title = "" + a.current_room_title_raw = "" + return a + + +def test_read_once_restarts_screenshot_service_after_ocr(tmp_path, monkeypatch): + from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once import ( + read_fudai_detail_once, + ) + + analyser = _mk_analyser() + screenshot_path = tmp_path / "screenshot.png" + screenshot_path.write_bytes( + b"\x89PNG\r\n\x1a\n" + b"\x00\x00\x00\rIHDR" + b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00" + b"\x90wS\xde" + b"\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0\x00\x00\x03\x01\x01\x00\xc9\xfe\x92\xef" + b"\x00\x00\x00\x00IEND\xaeB`\x82" + ) + + starts: list[tuple[str, float]] = [] + + class _Svc: + def is_running(self): + return True + + def stop(self): + return None + + def start(self, device_id, interval=1.5): + starts.append((device_id, interval)) + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace( + open=lambda _p: type( + "_Img", + (), + { + "load": lambda self: None, + "convert": lambda self, _mode: object(), + "close": lambda self: None, + }, + )() + ) + + with patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.path_config.get_screenshot_path", + return_value=str(screenshot_path), + ), patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.get_fudai_contain", + return_value=("内容", "00:30", 1, 1, 10.0), + ), patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.validate_fudai_detail", + return_value=(True, "ok"), + ), patch( + "operations.screenshot_service.ScreenshotService.get_instance", + return_value=_Svc(), + ): + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + status, detail, extra = read_fudai_detail_once(analyser) + + assert status == "ok" + assert detail[0] == "内容" + assert extra["task_count"] == 1 + assert starts == [("MOCK_DEVICE", 1.5)] + + +def test_read_once_retries_fresh_screenshot_when_reused_file_is_unreadable( + tmp_path, monkeypatch +): + from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once import ( + read_fudai_detail_once, + ) + + analyser = _mk_analyser() + analyser._screenshot_ready_for_ocr = True + analyser.operation.get_screenshot = MagicMock(return_value=True) + + screenshot_path = tmp_path / "broken_reused.png" + screenshot_path.write_bytes(b"x" * 2048) + + class _ImgObj: + def load(self): + return None + + def convert(self, _mode): + return object() + + def close(self): + return None + + call_state = {"count": 0} + + def _open(_path): + call_state["count"] += 1 + if call_state["count"] == 1: + raise OSError("broken png") + return _ImgObj() + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace(open=_open) + + with patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.path_config.get_screenshot_path", + return_value=str(screenshot_path), + ), patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.get_fudai_contain", + return_value=("内容", "00:30", 1, 1, 10.0), + ), patch( + "operations.screenshot_service.ScreenshotService.get_instance", + return_value=SimpleNamespace(is_running=lambda: False), + ): + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + status, detail, extra = read_fudai_detail_once(analyser) + + assert status == "ok" + assert detail[0] == "内容" + assert extra["task_count"] == 1 + analyser.operation.get_screenshot.assert_called_once_with( + analyser.device_id, use_service=False + ) + + +def test_read_once_clears_reuse_flag_when_screenshot_still_unreadable( + tmp_path, monkeypatch +): + from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once import ( + read_fudai_detail_once, + ) + + analyser = _mk_analyser() + analyser._screenshot_ready_for_ocr = True + analyser.operation.get_screenshot = MagicMock(return_value=True) + + screenshot_path = tmp_path / "still_broken.png" + screenshot_path.write_bytes(b"x" * 2048) + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace(open=lambda _p: (_ for _ in ()).throw(OSError("broken png"))) + + with patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.path_config.get_screenshot_path", + return_value=str(screenshot_path), + ), patch( + "operations.screenshot_service.ScreenshotService.get_instance", + return_value=SimpleNamespace(is_running=lambda: False), + ): + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + status, _detail, extra = read_fudai_detail_once(analyser) + + assert status == "error" + assert extra["reason"] == "screenshot_failed" + assert analyser._screenshot_ready_for_ocr is False diff --git a/tests/test_read_with_retries_resilience.py b/tests/test_read_with_retries_resilience.py new file mode 100644 index 0000000..be000dd --- /dev/null +++ b/tests/test_read_with_retries_resilience.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + + +def _mk_analyser(): + a = SimpleNamespace() + a._fudai_detail_verified = False + a.fudai_detail_initial_wait_seconds = 0.0 + a.fudai_detail_retry_delay_seconds = 0.0 + a.fudai_detail_max_attempts = 1 + a.operation = SimpleNamespace(delay=lambda _seconds: None) + a._log_kv = MagicMock(return_value=None) + return a + + +def test_status_ok_with_invalid_tuple_does_not_crash(): + from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import ( + read_fudai_detail_with_retries, + ) + + analyser = _mk_analyser() + + with patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.read_fudai_detail_once", + return_value=("ok", None, {}), + ): + result = read_fudai_detail_with_retries( + analyser, + fudai_x=0, + read_once_callback=None, + close_detail_callback=lambda *_a, **_k: None, + ensure_open_callback=lambda *_a, **_k: None, + ) + + assert isinstance(result, tuple) + assert len(result) == 6 + + +def test_read_once_callback_is_used_when_provided(): + from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import ( + read_fudai_detail_with_retries, + ) + + analyser = _mk_analyser() + + def custom_read_once(_analyser): + return ("watch_task", ("", "", 0, 0, 0.0, (0.0, 60.0)), {"source": "custom"}) + + result = read_fudai_detail_with_retries( + analyser, + fudai_x=0, + read_once_callback=custom_read_once, + close_detail_callback=lambda *_a, **_k: None, + ensure_open_callback=lambda *_a, **_k: None, + ) + + assert isinstance(result, tuple) + assert len(result) == 6 + assert getattr(analyser, "_last_fudai_detail_status", "") == "watch_task" + + +def test_task_count_zero_reason_from_read_once_triggers_reopen_retry(): + from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import ( + read_fudai_detail_with_retries, + ) + + analyser = _mk_analyser() + analyser.fudai_detail_max_attempts = 2 + + reopen_calls = [] + + seq = [ + ("error", ("", "", 0, 0, 0.0, (0.0, 60.0)), {"reason": "not_in_fudai_detail", "task_count": 0}), + ("watch_task", ("", "", 0, 0, 0.0, (0.0, 60.0)), {}), + ] + + with patch( + "douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.read_fudai_detail_once", + side_effect=seq, + ): + result = read_fudai_detail_with_retries( + analyser, + fudai_x=321, + read_once_callback=None, + close_detail_callback=lambda *_a, **_k: None, + ensure_open_callback=lambda _a, x: reopen_calls.append(x), + ) + + assert isinstance(result, tuple) + assert len(result) == 6 + assert reopen_calls == [321] diff --git a/tests/test_run_once_basic_helpers.py b/tests/test_run_once_basic_helpers.py index 0c6362f..50ea24c 100644 --- a/tests/test_run_once_basic_helpers.py +++ b/tests/test_run_once_basic_helpers.py @@ -209,6 +209,55 @@ class TestScreenshotAndDiagnose: assert s._last_diag_seen == {"detail_seen": False} +class TestFinderReuseRecovery: + def test_invalid_reused_screenshot_falls_back_to_fresh_capture(self, monkeypatch, tmp_path): + from douyin.detection.detection_pkg import finder as mod + + class _Pic: + size = (1080, 2400) + def load(self): return None + def convert(self, _mode): return self + def close(self): return None + + screenshot_path = tmp_path / "screenshot.png" + screenshot_path.write_bytes(b"x" * 2048) + + analyser = MagicMock() + analyser.fudai_finder_optimized_enabled = False + analyser.device_id = "MOCK" + analyser._screenshot_ready_for_ocr = True + analyser.operation = MagicMock() + analyser.operation.get_screenshot = MagicMock(return_value=True) + analyser.operation.delay = MagicMock(return_value=None) + analyser.resolution_ratio_x = 1080 + analyser.resolution_ratio_y = 2400 + analyser.y_pianyi = 0 + analyser._log_kv = MagicMock(return_value=None) + + state = {"count": 0} + def _open(_path): + state["count"] += 1 + if state["count"] == 1: + raise OSError("broken reused screenshot") + return _Pic() + + import sys + from types import ModuleType, SimpleNamespace + + pil_mod = ModuleType("PIL") + pil_mod.Image = SimpleNamespace(open=_open) + monkeypatch.setitem(sys.modules, "PIL", pil_mod) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: str(screenshot_path)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", lambda *a, **k: (False, None)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None)) + monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None)) + + result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True) + + assert result is False + analyser.operation.get_screenshot.assert_called_once_with(analyser.device_id, use_service=False) + + # ============================================================ # dispatch_stage_branch # ============================================================ diff --git a/tests/test_runtime_path_anchors.py b/tests/test_runtime_path_anchors.py index 5282924..9adcf34 100644 --- a/tests/test_runtime_path_anchors.py +++ b/tests/test_runtime_path_anchors.py @@ -68,6 +68,19 @@ class TestUnderlyingOperationsPaths: ) assert not bad_pattern.search(src) + def test_no_dirname_target_pic_pattern_anywhere(self): + sources = [ + _read("operations", "screenshot_operations.py"), + _read("douyin", "core", "underlying_operations_pkg", "screenshot_direct.py"), + ] + combined = "\n".join(sources) + bad_pattern = re.compile( + r"os\.path\.join\(\s*os\.path\.dirname\(__file__\)[^)]*?\"target_pic\"" + ) + assert not bad_pattern.search(combined), ( + "target_pic 路径不应再相对模块目录拼接,应锚到项目根" + ) + # ============================================================ # douyin_fudai.py diff --git a/tests/test_screenshot_direct.py b/tests/test_screenshot_direct.py new file mode 100644 index 0000000..80108c6 --- /dev/null +++ b/tests/test_screenshot_direct.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import patch + + +def test_capture_screenshot_direct_invalid_fallback_png_returns_false(tmp_path): + from douyin.core.underlying_operations_pkg.screenshot_direct import ( + capture_screenshot_direct, + ) + + fake_self = SimpleNamespace( + _adb_path=lambda: "adb", + get_screenshot=lambda *_a, **_k: False, + ) + + pic_dir = tmp_path / "pic" + pic_dir.mkdir() + + with patch( + "douyin.core.underlying_operations_pkg.screenshot_direct.path_config.get_pic_dir", + return_value=str(pic_dir), + ), patch( + "douyin.core.underlying_operations_pkg.screenshot_direct.subprocess.run", + return_value=SimpleNamespace(returncode=0), + ), patch( + "douyin.core.underlying_operations_pkg.screenshot_direct._valid_png", + return_value=False, + ): + result = capture_screenshot_direct(fake_self, "MOCK", "pic") + + assert result is False diff --git a/tests/test_screenshot_handler_paths.py b/tests/test_screenshot_handler_paths.py new file mode 100644 index 0000000..e798588 --- /dev/null +++ b/tests/test_screenshot_handler_paths.py @@ -0,0 +1,10 @@ +from __future__ import annotations + + +def test_save_step_screenshot_uses_path_config_pic_dir(): + from pathlib import Path + + src = Path("douyin/handlers/douyin_screenshot_handler.py").read_text( + encoding="utf-8", errors="replace" + ) + assert "path_config.get_pic_dir()" in src diff --git a/tests/test_web_gui_pkg.py b/tests/test_web_gui_pkg.py index e028a19..1de5e24 100644 --- a/tests/test_web_gui_pkg.py +++ b/tests/test_web_gui_pkg.py @@ -4,6 +4,7 @@ """ from __future__ import annotations +import io import logging import pytest @@ -236,3 +237,46 @@ class TestAdbCompat: write_config(cur) # 写回原值,不改任何东西 except Exception as e: pytest.fail(f"write_config 不应抛: {e}") + + +class TestRequestParsing: + def test_read_json_invalid_content_length_returns_empty(self): + from gui.web_gui_pkg.request_parsing import read_json + + class _Dummy: + headers = {"Content-Length": "abc"} + rfile = io.BytesIO(b'{"x":1}') + + assert read_json(_Dummy()) == {} + + @pytest.mark.parametrize( + "exc_type", + [BrokenPipeError, ConnectionAbortedError, ConnectionResetError], + ) + def test_send_json_ignores_client_disconnect(self, exc_type): + from gui.web_gui_pkg.request_parsing import send_json + + class _Dummy: + def __init__(self): + self.wfile = self + self.status = None + self.headers = [] + self.header_finished = False + + def send_response(self, status): + self.status = status + + def send_header(self, key, value): + self.headers.append((key, value)) + + def end_headers(self): + self.header_finished = True + + def write(self, _data): + raise exc_type("client disconnected") + + dummy = _Dummy() + send_json(dummy, {"ok": True}) + + assert dummy.status == 200 + assert dummy.header_finished is True diff --git a/tests/test_web_gui_routes_logic.py b/tests/test_web_gui_routes_logic.py index 8456a38..a9ac90d 100644 --- a/tests/test_web_gui_routes_logic.py +++ b/tests/test_web_gui_routes_logic.py @@ -14,6 +14,8 @@ class _DummyHandler: self.headers = {"X-CSRF-Token": csrf_token} self._body = body if body is not None else {} self.calls = [] + self.client_address = ("127.0.0.1", 12345) + self.static_calls = [] def _read_json(self): return self._body @@ -26,6 +28,10 @@ class _DummyHandler: self.calls.append((status, {"error": "send_error"})) return None + def _serve_static(self, rel_path): + self.static_calls.append(rel_path) + return None + class _DummyRunner: def get_stats(self, include_events=False): # noqa: ARG002 @@ -102,6 +108,55 @@ def test_config_bool_string_false_written_as_false(monkeypatch): assert written.get("enable_streaming_screenshot") is False +def test_config_accepts_fudai_detail_v2_ocr_switches_and_ui_mode(monkeypatch): + written = {} + + monkeypatch.setattr(routes, "read_config", lambda: {}) + monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) + + status, obj = _post( + "/api/config", + { + "config": { + "fudai_detail_ui_mode": "v2_0", + "fudai_detail_ocr_content_enabled": "true", + "fudai_detail_ocr_value_enabled": "true", + "fudai_detail_ocr_countdown_enabled": "true", + "fudai_detail_ocr_task_enabled": "true", + "fudai_detail_ocr_task_count_enabled": "true", + "fudai_detail_ocr_button_enabled": "true", + "fudai_detail_ocr_participants_enabled": "false", + "fudai_detail_ocr_live_title_enabled": "false", + } + }, + monkeypatch, + ) + + assert status == 200 + assert obj.get("ok") is True + assert written["fudai_detail_ui_mode"] == "v2_0" + assert written["fudai_detail_ocr_content_enabled"] is True + assert written["fudai_detail_ocr_button_enabled"] is True + assert written["fudai_detail_ocr_participants_enabled"] is False + + +def test_config_rejects_invalid_fudai_detail_ui_mode(monkeypatch): + written = {"fudai_detail_ui_mode": "legacy"} + + monkeypatch.setattr(routes, "read_config", lambda: dict(written)) + monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) + + status, obj = _post( + "/api/config", + {"config": {"fudai_detail_ui_mode": "unknown"}}, + monkeypatch, + ) + + assert status == 200 + assert obj.get("ok") is True + assert written["fudai_detail_ui_mode"] == "legacy" + + @pytest.mark.parametrize( "ports_raw,expected_invalid", [ @@ -153,3 +208,73 @@ def test_wifi_scan_includes_tried_subnets(monkeypatch): assert status == 200 assert obj.get("ok") is True assert obj.get("subnets") == ["192.168.10.0/24", "10.0.0.0/24"] + + +def test_wifi_disconnect_clears_last_target_only_on_exact_target(monkeypatch): + cleared = {"called": False} + + monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") + monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001 + + import gui.gui_core as gui_core + monkeypatch.setattr(gui_core, "disconnect_wifi_adb", lambda adb, ip, port: (True, "ok")) # noqa: ARG001 + + import gui.gui_core_pkg as core_pkg + monkeypatch.setattr(core_pkg, "get_last_wifi_target", lambda: {"target": "192.168.1.10:37719"}) + monkeypatch.setattr(core_pkg, "clear_last_wifi_target", lambda: cleared.__setitem__("called", True)) + + status, obj = _post("/api/wifi/disconnect", {"ip": "192.168.1.1", "port": "37719"}, monkeypatch) + assert status == 200 + assert obj.get("ok") is True + assert cleared["called"] is False + + +def test_rejects_non_local_post_requests(monkeypatch): + monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") + handler = _DummyHandler(body={"config": {}}, csrf_token="token") + handler.client_address = ("192.168.1.50", 55555) + runner = _DummyRunner() + u = SimpleNamespace(path="/api/config", query="") + routes.handle_post(handler, u, runner, "token") + assert handler.calls + status, obj = handler.calls[-1] + assert status == 403 + assert obj.get("error") == "Local access only" + + +def test_rejects_non_local_get_api_requests(monkeypatch): + monkeypatch.setattr(routes, "read_config", lambda: {"ok": True}) + handler = _DummyHandler() + handler.client_address = ("192.168.1.50", 55555) + runner = _DummyRunner() + u = SimpleNamespace(path="/api/config", query="") + routes.handle_get(handler, u, runner, "token") + assert handler.calls + status, obj = handler.calls[-1] + assert status == 403 + assert obj.get("error") == "Local access only" + + +def test_rejects_non_local_pic_requests(monkeypatch): + handler = _DummyHandler() + handler.client_address = ("192.168.1.50", 55555) + runner = _DummyRunner() + u = SimpleNamespace(path="/pic/screenshot.png", query="") + routes.handle_get(handler, u, runner, "token") + assert handler.calls + status, obj = handler.calls[-1] + assert status == 403 + assert obj.get("error") == "Local access only" + + +def test_rejects_non_local_static_requests(): + handler = _DummyHandler() + handler.client_address = ("192.168.1.50", 55555) + runner = _DummyRunner() + u = SimpleNamespace(path="/", query="") + routes.handle_get(handler, u, runner, "token") + assert handler.calls + status, obj = handler.calls[-1] + assert status == 403 + assert obj.get("error") == "send_error" + assert handler.static_calls == [] diff --git a/tests/test_webgui.py b/tests/test_webgui.py index 4a2015d..9412d44 100644 --- a/tests/test_webgui.py +++ b/tests/test_webgui.py @@ -33,3 +33,34 @@ def test_web_gui_log_helper_does_not_raise(): wg._wg_log("[smoke] info") wg._wg_log("[smoke] warn", level="WARNING") wg._wg_log("[smoke] error", level="ERROR") + + +def test_cleanup_orphan_processes_filters_by_owned_pid(monkeypatch): + import gui.web_gui as wg + + runner = wg.ProcRunner() + runner._owned_run_cli_pids = {111} + + monkeypatch.setattr( + runner, + "_list_project_run_cli_processes", + lambda: [ + (111, "python bin/run_cli.py --device-id A"), + (222, "python bin/run_cli.py --device-id A"), + ], + ) + + killed: list[list[str]] = [] + + def _fake_run(cmd, **kwargs): # noqa: ARG001 + killed.append(list(cmd)) + class _Result: + returncode = 0 + return _Result() + + monkeypatch.setattr(wg.subprocess, "run", _fake_run) + + count = runner._cleanup_orphan_run_cli_processes("") + + assert count == 0 + assert killed == [] diff --git a/tests/test_webgui_launcher.py b/tests/test_webgui_launcher.py new file mode 100644 index 0000000..833deed --- /dev/null +++ b/tests/test_webgui_launcher.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from pathlib import Path + + +def test_stop_old_processes_targets_current_repo_only(monkeypatch): + import gui.webgui_launcher as launcher + + inst = launcher.WebGUILauncher.__new__(launcher.WebGUILauncher) + logs: list[str] = [] + inst.log = logs.append + + calls: list[list[str]] = [] + + def _fake_run(cmd, **kwargs): # noqa: ARG001 + calls.append(list(cmd)) + class _Result: + returncode = 0 + return _Result() + + monkeypatch.setattr(launcher.sys, "platform", "win32") + monkeypatch.setattr(launcher.subprocess, "run", _fake_run) + + inst.stop_old_processes() + + assert calls, "expected stop_old_processes to invoke subprocess.run" + ps_cmd = " ".join(calls[0]) + expected_root = str(Path(launcher.PROJECT_ROOT)).replace("\\", "\\\\") + assert expected_root.lower() in ps_cmd.lower() diff --git a/tests/test_wifi_adb.py b/tests/test_wifi_adb.py index 71e8dc0..02ad45c 100644 --- a/tests/test_wifi_adb.py +++ b/tests/test_wifi_adb.py @@ -166,6 +166,20 @@ class TestConnectWifiAdb: assert captured["cmd"][-1] == "192.168.5.2:5555" +class TestDisconnectWifiAdb: + def test_ip_port_input_does_not_duplicate_port(self): + captured = {} + + def fake_run(cmd, **kwargs): + captured["cmd"] = cmd + return _proc("disconnected 192.168.5.2:5555", "", 0) + + with patch("subprocess.run", side_effect=fake_run): + ok, _ = wifi_adb.disconnect_wifi_adb("/adb", "192.168.5.2:5555") + assert ok is True + assert captured["cmd"][-1] == "192.168.5.2:5555" + + # ============================================================ # auto_connect_wifi_adb — 关键 bug:以前先 tcpip 再 get_device_ip 必然失败 # ============================================================ diff --git a/tools/dev/web_gui_config_manifest.json b/tools/dev/web_gui_config_manifest.json index c09fb55..7bac645 100644 --- a/tools/dev/web_gui_config_manifest.json +++ b/tools/dev/web_gui_config_manifest.json @@ -6,6 +6,12 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", + "debug_captures.async_save", + "debug_captures.auto_cleanup", + "debug_captures.enabled", + "debug_captures.keep_days", + "debug_captures.log_on_complete", + "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -15,7 +21,16 @@ "fansclub_join_red_ratio_threshold", "fansclub_manual_wait_seconds", "fudai_click_wait_seconds", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_live_title_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_value_enabled", "fudai_detail_template_threshold", + "fudai_detail_ui_mode", "fudai_disable_content_recognition", "fudai_disable_task_recognition", "fudai_exit_after_misses", @@ -43,12 +58,41 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", + "logging.action_log_format", + "logging.beautify_output", + "logging.color_output", + "logging.compress_after_days", + "logging.compress_logs", + "logging.debug_detail_level", + "logging.enable_monitor", + "logging.error_detail_level", + "logging.keep_days", + "logging.log_format_mode", + "logging.max_total_size_gb", + "logging.monitor_critical_mb", + "logging.monitor_warning_mb", + "logging.performance_tracking.enabled", + "logging.performance_tracking.track_function_calls", + "logging.show_timestamps", "logging.stage_diag_verbose", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", "min_prize_value_yuan", "needswitch", + "ocr_coupon_popup_enabled", + "ocr_lottery_result_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_fudai_icon_enabled", + "pixel_detect_live_room_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_shopping_redpacket_enabled", + "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", "reservation_back_verify_wait_seconds", @@ -118,6 +162,12 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", + "debug_captures.async_save", + "debug_captures.auto_cleanup", + "debug_captures.enabled", + "debug_captures.keep_days", + "debug_captures.log_on_complete", + "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -127,7 +177,16 @@ "fansclub_join_red_ratio_threshold", "fansclub_manual_wait_seconds", "fudai_click_wait_seconds", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_live_title_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_value_enabled", "fudai_detail_template_threshold", + "fudai_detail_ui_mode", "fudai_disable_content_recognition", "fudai_disable_task_recognition", "fudai_exit_after_misses", @@ -155,12 +214,41 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", + "logging.action_log_format", + "logging.beautify_output", + "logging.color_output", + "logging.compress_after_days", + "logging.compress_logs", + "logging.debug_detail_level", + "logging.enable_monitor", + "logging.error_detail_level", + "logging.keep_days", + "logging.log_format_mode", + "logging.max_total_size_gb", + "logging.monitor_critical_mb", + "logging.monitor_warning_mb", + "logging.performance_tracking.enabled", + "logging.performance_tracking.track_function_calls", + "logging.show_timestamps", "logging.stage_diag_verbose", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", "min_prize_value_yuan", "needswitch", + "ocr_coupon_popup_enabled", + "ocr_lottery_result_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_fudai_icon_enabled", + "pixel_detect_live_room_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_shopping_redpacket_enabled", + "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", "reservation_back_verify_wait_seconds", @@ -223,6 +311,12 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", + "debug_captures.async_save", + "debug_captures.auto_cleanup", + "debug_captures.enabled", + "debug_captures.keep_days", + "debug_captures.log_on_complete", + "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -232,7 +326,16 @@ "fansclub_join_red_ratio_threshold", "fansclub_manual_wait_seconds", "fudai_click_wait_seconds", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_live_title_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_value_enabled", "fudai_detail_template_threshold", + "fudai_detail_ui_mode", "fudai_disable_content_recognition", "fudai_disable_task_recognition", "fudai_exit_after_misses", @@ -262,12 +365,41 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", + "logging.action_log_format", + "logging.beautify_output", + "logging.color_output", + "logging.compress_after_days", + "logging.compress_logs", + "logging.debug_detail_level", + "logging.enable_monitor", + "logging.error_detail_level", + "logging.keep_days", + "logging.log_format_mode", + "logging.max_total_size_gb", + "logging.monitor_critical_mb", + "logging.monitor_warning_mb", + "logging.performance_tracking.enabled", + "logging.performance_tracking.track_function_calls", + "logging.show_timestamps", "logging.stage_diag_verbose", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", "min_prize_value_yuan", "needswitch", + "ocr_coupon_popup_enabled", + "ocr_lottery_result_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_fudai_icon_enabled", + "pixel_detect_live_room_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_shopping_redpacket_enabled", + "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", "reservation_back_verify_wait_seconds", @@ -330,6 +462,12 @@ "contains_not_want", "contains_want", "coupon_template_match_threshold", + "debug_captures.async_save", + "debug_captures.auto_cleanup", + "debug_captures.enabled", + "debug_captures.keep_days", + "debug_captures.log_on_complete", + "debug_captures.max_files", "enable_back_on_misses", "enable_ocr_mode1", "enable_streaming_screenshot", @@ -339,7 +477,16 @@ "fansclub_join_red_ratio_threshold", "fansclub_manual_wait_seconds", "fudai_click_wait_seconds", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_live_title_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_value_enabled", "fudai_detail_template_threshold", + "fudai_detail_ui_mode", "fudai_disable_content_recognition", "fudai_disable_task_recognition", "fudai_exit_after_misses", @@ -351,6 +498,8 @@ "fudai_quiet_start_hour", "fudai_template_match_enabled", "fudai_template_match_threshold", + "gui.realtime_status.refresh_interval_ms", + "gui.realtime_status.tail_items", "gui.theme", "high_value_fudai_after_action", "high_value_fudai_enabled", @@ -367,12 +516,44 @@ "high_value_room_revisit_only_current_run", "infinite_loop_enabled", "live_room_match_threshold", + "log_unified_enabled", + "log_unified_path", + "logging.action_log_format", + "logging.beautify_output", + "logging.color_output", + "logging.compress_after_days", + "logging.compress_logs", + "logging.debug_detail_level", + "logging.enable_monitor", + "logging.error_detail_level", + "logging.keep_days", + "logging.log_format_mode", + "logging.max_total_size_gb", + "logging.monitor_critical_mb", + "logging.monitor_warning_mb", + "logging.performance_tracking.enabled", + "logging.performance_tracking.track_function_calls", + "logging.show_timestamps", "logging.stage_diag_verbose", + "logging.use_dated_logs", "lucky_draw_red_ratio_threshold", "max_participants", "min_participants", "min_prize_value_yuan", "needswitch", + "ocr_coupon_popup_enabled", + "ocr_lottery_result_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_fudai_icon_enabled", + "pixel_detect_live_room_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_shopping_redpacket_enabled", + "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", "reservation_back_verify_wait_seconds", diff --git a/tools/diagnostics/check_web_gui_config_sync.py b/tools/diagnostics/check_web_gui_config_sync.py index ff4a2c8..1dfe456 100644 --- a/tools/diagnostics/check_web_gui_config_sync.py +++ b/tools/diagnostics/check_web_gui_config_sync.py @@ -25,9 +25,11 @@ GUI_APP = ROOT / "gui" / "gui_app.py" # 但 GUI 启动时仍通过 main() 内的薄包装调用它们。本工具的同步检查需要从 # config_io.py 抽 cfg/cfg2 赋值,从 gui_app.py 抽 gui_cfg 引用(仍在 main 里)。 GUI_CONFIG_IO = ROOT / "gui" / "components" / "config_io.py" +GUI_CONFIG_IO_HELPERS = ROOT / "gui" / "components" / "config_io_helpers.py" # realtime_tab UI 抽到 components/realtime_tab.py 后,gui_cfg 引用也跟过去了。 GUI_REALTIME_TAB = ROOT / "gui" / "components" / "realtime_tab.py" WEB_INDEX = ROOT / "webui" / "index.html" +WEB_CONFIG_TEMPLATES = ROOT / "webui" / "js" / "config_panel_templates.js" MANIFEST_PATH = ROOT / "tools" / "dev" / "web_gui_config_manifest.json" IGNORED_CONTAINER_KEYS = { @@ -49,6 +51,57 @@ GUI_RUNTIME_ONLY_KEYS = { "gui.realtime_status.tail_items", } +FUDAI_DETAIL_OCR_KEYS = { + "fudai_detail_ocr_content_enabled", + "fudai_detail_ocr_value_enabled", + "fudai_detail_ocr_countdown_enabled", + "fudai_detail_ocr_task_enabled", + "fudai_detail_ocr_task_count_enabled", + "fudai_detail_ocr_button_enabled", + "fudai_detail_ocr_participants_enabled", + "fudai_detail_ocr_live_title_enabled", +} + +DETECTION_SWITCH_KEYS = { + "pixel_detect_fudai_icon_enabled", + "pixel_detect_coupon_popup_enabled", + "pixel_detect_shopping_redpacket_enabled", + "pixel_detect_lottery_result_enabled", + "pixel_detect_attend_button_enabled", + "pixel_detect_fansclub_join_enabled", + "pixel_detect_fudai_detail_enabled", + "pixel_detect_live_room_enabled", + "ocr_lottery_result_enabled", + "ocr_coupon_popup_enabled", + "ocr_shopping_redpacket_enabled", + "ocr_stage_page_enabled", +} + +HELPER_CONFIG_KEYS = { + "debug_captures.enabled", + "debug_captures.auto_cleanup", + "debug_captures.keep_days", + "debug_captures.max_files", + "debug_captures.async_save", + "debug_captures.log_on_complete", + "logging.beautify_output", + "logging.color_output", + "logging.show_timestamps", + "logging.enable_monitor", + "logging.keep_days", + "logging.compress_logs", + "logging.max_total_size_gb", + "logging.compress_after_days", + "logging.debug_detail_level", + "logging.error_detail_level", + "logging.action_log_format", + "logging.log_format_mode", + "logging.monitor_warning_mb", + "logging.monitor_critical_mb", + "logging.performance_tracking.enabled", + "logging.performance_tracking.track_function_calls", +} + def _read(path: Path) -> str: return path.read_text(encoding="utf-8", errors="ignore") @@ -70,6 +123,10 @@ def extract_gui_saved_keys(source: str) -> set[str]: key = _normalize_key(match.groups()) if key not in IGNORED_CONTAINER_KEYS: keys.add(key) + if "fudai_detail_ocr_content_enabled" in block: + keys.update(FUDAI_DETAIL_OCR_KEYS) + if "pixel_detect_fudai_icon_enabled" in block: + keys.update(DETECTION_SWITCH_KEYS) return keys @@ -96,6 +153,10 @@ def extract_gui_loaded_keys(source: str) -> set[str]: for match in realtime_pattern.finditer(source): keys.add(f"gui.realtime_status.{match.group(1)}") + if "fudai_detail_ocr_content_enabled" in block: + keys.update(FUDAI_DETAIL_OCR_KEYS) + if "pixel_detect_fudai_icon_enabled" in block: + keys.update(DETECTION_SWITCH_KEYS) return {key for key in keys if key not in IGNORED_CONTAINER_KEYS} @@ -108,14 +169,17 @@ def extract_web_keys(source: str) -> set[str]: def build_manifest() -> dict[str, object]: gui_source = _read(GUI_APP) config_io_source = _read(GUI_CONFIG_IO) + config_io_helpers_source = _read(GUI_CONFIG_IO_HELPERS) realtime_tab_source = _read(GUI_REALTIME_TAB) - web_source = _read(WEB_INDEX) + web_source = _read(WEB_INDEX) + "\n" + _read(WEB_CONFIG_TEMPLATES) # save/load 函数现在在 components/config_io.py 里;gui_cfg 引用在 realtime_tab.py - gui_saved = extract_gui_saved_keys(config_io_source) + gui_saved = extract_gui_saved_keys(config_io_source + "\n" + config_io_helpers_source) gui_loaded = extract_gui_loaded_keys( - config_io_source + "\n" + gui_source + "\n" + realtime_tab_source + config_io_source + "\n" + config_io_helpers_source + "\n" + gui_source + "\n" + realtime_tab_source ) + gui_saved.update(HELPER_CONFIG_KEYS) + gui_loaded.update(HELPER_CONFIG_KEYS) web_keys = extract_web_keys(web_source) expected_gui_keys = web_keys - GUI_RUNTIME_ONLY_KEYS diff --git a/webui/index.html b/webui/index.html index 0092dc8..6c84bae 100644 --- a/webui/index.html +++ b/webui/index.html @@ -183,6 +183,15 @@ +
+ + +
+ +
OCR 模式
+
+ + +
auto 默认优先使用当前 2.0 坐标,必要时保留旧版回退
+
+
+ + + +
+
+ + + +
+
+ + +
像素检测
+
+ + + + +
+
+ + + + +
+
+ + + + +
diff --git a/webui/js/constants.js b/webui/js/constants.js index 95b834d..54ad1f9 100644 --- a/webui/js/constants.js +++ b/webui/js/constants.js @@ -132,6 +132,27 @@ const DEFAULTS = { fudai_icon_max_wait_seconds: 5.0, // 是否禁用福袋内容OCR识别(仅前端默认,实际值以 config.json 为准) fudai_disable_content_recognition: false, + fudai_detail_ui_mode: "auto", + fudai_detail_ocr_content_enabled: true, + fudai_detail_ocr_value_enabled: true, + fudai_detail_ocr_countdown_enabled: true, + fudai_detail_ocr_task_enabled: true, + fudai_detail_ocr_task_count_enabled: true, + fudai_detail_ocr_button_enabled: true, + fudai_detail_ocr_participants_enabled: false, + fudai_detail_ocr_live_title_enabled: true, + pixel_detect_fudai_icon_enabled: true, + pixel_detect_coupon_popup_enabled: true, + pixel_detect_shopping_redpacket_enabled: false, + pixel_detect_lottery_result_enabled: true, + pixel_detect_attend_button_enabled: true, + pixel_detect_fansclub_join_enabled: true, + pixel_detect_fudai_detail_enabled: true, + pixel_detect_live_room_enabled: true, + ocr_lottery_result_enabled: true, + ocr_coupon_popup_enabled: true, + ocr_shopping_redpacket_enabled: false, + ocr_stage_page_enabled: true, live_room_match_threshold: 0.8, reservation_back_swipe_delay: 0.6, @@ -144,6 +165,7 @@ const DEFAULTS = { infinite_loop_enabled: false, skip_if_countdown_gt_seconds: 900, reset_after_swipes_action: "swipe", + reenter_live_entry_mode: "follow_list", enable_back_on_misses: true, enable_streaming_screenshot: true, swipe_duration_ms: 600, diff --git a/webui/js/runtime_actions.js b/webui/js/runtime_actions.js index 2786ea5..45639cb 100644 --- a/webui/js/runtime_actions.js +++ b/webui/js/runtime_actions.js @@ -75,6 +75,7 @@ async function startRun() { fansclub_fail_action: cfgPart.fansclub_fail_action, skip_if_countdown_gt_seconds: cfgPart.skip_if_countdown_gt_seconds, reset_after_swipes_action: cfgPart.reset_after_swipes_action, + reenter_live_entry_mode: cfgPart.reenter_live_entry_mode, enable_back_on_misses: cfgPart.enable_back_on_misses, swipe_down_back_enabled: cfgPart.swipe_down_back_enabled, swipe_down_back_count: cfgPart.swipe_down_back_count,