修复福袋详情OCR v2与调试日志

This commit is contained in:
Your Name committed 2026-06-03 01:22:13 +08:00
1 parent 2c6f024a24
commit 1d37d57c90
119 files changed
+5582 -767

No files matched your search

+14
View File
@@ -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()
+27 -5
View File
@@ -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
}
}
@@ -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。
@@ -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 路径仍相对模块目录拼接。
- 已统一锚到 `<project_root>/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 探针验证。
@@ -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,
+1 -5
View File
@@ -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:
@@ -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"
@@ -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
@@ -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(
@@ -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
+25
View File
@@ -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)
@@ -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(
+10 -2
View File
@@ -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:
+1 -10
View File
@@ -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,
@@ -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")
@@ -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")
@@ -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")
@@ -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:
+168 -2
View File
@@ -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()
+41 -27
View File
@@ -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
@@ -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)
@@ -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:
+3 -3
View File
@@ -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()
+2 -2
View File
@@ -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
+40 -11
View File
@@ -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,
}
+52 -19
View File
@@ -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:
+93 -2
View File
@@ -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
+117 -46
View File
@@ -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(
"参与",
+180 -10
View File
@@ -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
@@ -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()
@@ -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
@@ -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:
@@ -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(
@@ -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"
File diff suppressed because it is too large. Load diff
@@ -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)
@@ -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(
@@ -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
@@ -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)
@@ -28,6 +28,9 @@ _BUTTON_KEYWORDS = (
"评论",
"参与抽奖",
"开始观看",
"一键发表评论",
"发表评论",
"已参与",
"参与",
"加入粉丝团",
"粉丝团",
+3 -2
View File
@@ -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)
+16 -12
View File
@@ -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)
@@ -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:
"""压缩单个日志文件
@@ -9,6 +9,7 @@
"""
from __future__ import annotations
import glob
import inspect
import logging
import logging.handlers
+6 -11
View File
@@ -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
@@ -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"
@@ -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
+4 -1
View File
@@ -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
+26 -1
View File
@@ -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:
@@ -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])
@@ -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:
@@ -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,
@@ -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,
@@ -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()
+48
View File
@@ -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"])
+23 -5
View File
@@ -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:
+1 -1
View File
@@ -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():
+8
View File
@@ -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)
+13 -1
View File
@@ -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:
+72
View File
@@ -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()
)
+64
View File
@@ -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,
+75 -1
View File
@@ -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,
+16
View File
@@ -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))
+21 -21
View File
@@ -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
+11
View File
@@ -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,
+45 -28
View File
@@ -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
+1 -1
View File
@@ -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(
+29 -11
View File
@@ -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:
+199
View File
@@ -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
+9 -2
View File
@@ -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"))
+63 -1
View File
@@ -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
+2 -1
View File
@@ -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(
+35 -12
View File
@@ -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相关
+1 -1
View File
@@ -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
+8 -4
View File
@@ -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目录
+33 -7
View File
@@ -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]"
+2 -4
View File
@@ -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/**"
]
}
}
+87
View File
@@ -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())
+12
View File
@@ -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)})
+3 -3
View File
@@ -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()
+3 -3
View File
@@ -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()
+74
View File
@@ -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 模块测试。"""
+18
View File
@@ -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
+1 -1
View File
@@ -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,
+131
View File
@@ -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
+1
View File
@@ -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 → 不命中。"""
+131 -12
View File
@@ -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
+27 -1
View File
@@ -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
+60
View File
@@ -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"
+241
View File
@@ -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
+4 -4
View File
@@ -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
+166 -2
View File
@@ -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
)
+31
View File
@@ -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"
+84
View File
@@ -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。"""
+17
View File
@@ -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()
+188
View File
@@ -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)
+29
View File
@@ -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"]
+87
View File
@@ -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
+127
View File
@@ -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 类测试。"""
+27
View File
@@ -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 子模块存在性测试。"""
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more