diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 109e924..5c0d8aa 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -270,19 +270,8 @@ class underlying_operations: ), contextlib.redirect_stderr(devnull): from paddleocr import PaddleOCR - # PaddleOCR的GPU支持需要paddlepaddle-gpu版本 + # 使用 PaddleOCR(强制 CPU 模式) use_gpu = False - try: - import paddle - - if ( - paddle.device.is_compiled_with_cuda() - and paddle.device.get_device() - ): - use_gpu = False - except Exception: - pass - self.ocr = PaddleOCR( lang="ch", ocr_version="PP-OCRv4", @@ -293,8 +282,7 @@ class underlying_operations: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - gpu_status = "GPU加速" if use_gpu else "CPU模式" - print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})") + print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") print( f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr" ) @@ -373,19 +361,8 @@ class underlying_operations: ): from paddleocr import PaddleOCR - # PaddleOCR的GPU支持需要paddlepaddle-gpu版本 + # 使用 PaddleOCR(强制 CPU 模式) use_gpu = False - try: - import paddle - - if ( - paddle.device.is_compiled_with_cuda() - and paddle.device.get_device() - ): - use_gpu = False - except Exception: - pass - self.ocr = PaddleOCR( lang="ch", ocr_version="PP-OCRv4", @@ -396,8 +373,7 @@ class underlying_operations: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - gpu_status = "GPU加速" if use_gpu else "CPU模式" - print(f"[OCR] 延迟初始化:使用 PaddleOCR({gpu_status})") + print(f"[OCR] 延迟初始化:使用 PaddleOCR(CPU模式)") except Exception: self.ocr = None self.ocr_type = None diff --git a/config.json b/config.json index 75c1833..a601c61 100644 --- a/config.json +++ b/config.json @@ -25,6 +25,7 @@ "high_value_room_revisit_only_current_run": true, "reservation_back_verify_enabled": true, "reservation_back_swipe_delay": 0.5, + "record_room_title_mapping_enabled": true, "reservation_preempt_min_value": 0.0, "fudai_find_max_attempts": 99999, "fudai_icon_retry_delay_seconds": 0.1, @@ -84,4 +85,4 @@ "yanghao_comment_texts": [], "yanghao_like_keywords": [], "yanghao_fav_keywords": [] -} +} \ No newline at end of file diff --git a/config/config.json b/config/config.json index 8bf1ba9..6f5cec5 100644 --- a/config/config.json +++ b/config/config.json @@ -7,7 +7,7 @@ "max_participants": 0, "skip_if_countdown_gt_seconds": 120, "reset_after_swipes_enabled": true, - "reset_after_swipes": 50, + "reset_after_swipes": 10, "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, @@ -29,7 +29,7 @@ "yanghao_fallback_enter_live_y": 1200, "fudai_find_max_attempts": 99999, "fudai_icon_retry_delay_seconds": 0.1, - "fudai_icon_max_wait_seconds": 8.5, + "fudai_icon_max_wait_seconds": 8.0, "fudai_click_wait_seconds": 1.7, "fudai_detail_initial_wait_seconds": 0.8, "fudai_detail_verified_wait_seconds": 0.2, @@ -76,9 +76,9 @@ "yanghao_comment_texts": [], "yanghao_like_keywords": [], "yanghao_fav_keywords": [], - "stage_diag_max_time": 5.0, + "stage_diag_max_time": 6.0, "stage_diag_max_step_time": 2.0, - "live_room_match_threshold": 0.6, + "live_room_match_threshold": 0.8, "enable_ocr_mode1": false, "fudai_template_match_enabled": false, "fudai_template_match_threshold": 0.7, @@ -101,9 +101,9 @@ "beautify_output": true, "show_timestamps": true, "show_execution_times": true, - "debug_detail_level": "normal", + "debug_detail_level": "detailed", "error_detail_level": "full", - "action_log_format": "concise", + "action_log_format": "detailed", "color_output": true, "max_log_lines_display": 1000, "auto_scroll_logs": true, @@ -129,7 +129,7 @@ "debug_captures": { "enabled": true, "keep_days": 3, - "max_files": 2000, + "max_files": 1900, "auto_cleanup": true }, "fudai_detail_template_threshold": 0.54, @@ -138,7 +138,7 @@ "attend_button_red_ratio_threshold": 0.25, "fansclub_join_red_ratio_threshold": 0.25, "reservation_test_mode": false, - "swipe_duration_ms": 600, + "swipe_duration_ms": 300, "gui": { "theme": "litera" } diff --git a/docs/完整技术文档.md b/docs/完整技术文档.md new file mode 100644 index 0000000..d54053b --- /dev/null +++ b/docs/完整技术文档.md @@ -0,0 +1,6811 @@ +# 抖音福袋挂机项目 - 完整技术文档 + +**文档版本**: V3.0 +**最后更新**: 2025-12-30 +**目标读者**: AI助手、开发者、维护人员 + +--- + +## 【代码修改规范】 + +### 1. 缩进要求 + +- **严格使用4个空格**(不使用Tab) +- 确保所有代码块缩进层级正确 +- 保持与现有代码相同的缩进风格 + +### 2. 代码块完整性 + +- **try 必须有对应的 except/finally** +- **if 的 else/elif 必须配对** +- **for/while 循环体必须正确缩进** +- **def/class 内部代码必须正确缩进** + +### 3. 语法检查 + +- 确保没有孤立的 except、else、elif +- 确保所有括号、引号配对 +- 确保所有冒号后都有正确的缩进块 + +### 4. 修改流程 + +1. **先分析代码结构**,明确缩进层级 +2. **修改时保持缩进一致性** +3. **修改后验证语法正确性** + +### 5. 验证清单 + +- ✓ 缩进正确(4空格) +- ✓ 代码块完整(try/except配对等) +- ✓ 语法正确(无语法错误) +- ✓ 代码可运行(逻辑正确) + +--- + +## 文档目标 + +本文档旨在为AI助手提供项目的完整技术理解,包括: + +- 项目整体架构和设计模式 +- **完整的流程图(含函数调用链)** +- **所有关键函数的详细说明(参数、返回值、作用、调用位置)** +- 模块结构和职责划分 +- 数据流和状态管理 +- 关键技术实现细节 +- 配置系统和扩展指南 + +--- + +## 目录 + +1. [项目概述](#1-项目概述) +2. [项目架构](#2-项目架构) +3. [完整流程图(含函数调用链)](#3-完整流程图含函数调用链) +4. [关键函数详细说明](#4-关键函数详细说明) +5. [其他重要函数](#5-其他重要函数) +6. [核心类和数据结构详解](#6-核心类和数据结构详解) +7. [配置系统详解](#7-配置系统详解) +8. [状态管理机制详解](#8-状态管理机制详解) +9. [错误处理和异常情况](#9-错误处理和异常情况) +10. [代码示例](#10-代码示例) +11. [模块详解](#11-模块详解) +12. [数据流和状态管理](#12-数据流和状态管理) +13. [关键技术实现](#13-关键技术实现) +14. [扩展指南和最佳实践](#14-扩展指南和最佳实践) +15. [关键文件索引和调试指南](#15-关键文件索引和调试指南) +16. [高级主题和深入理解](#16-高级主题和深入理解) +17. [预约验证和错误处理模块](#17-预约验证和错误处理模块) +18. [核心处理函数详解补充](#18-核心处理函数详解补充) +19. [工具函数和辅助模块详解](#19-工具函数和辅助模块详解) +20. [检测功能详解](#20-检测功能详解) +21. [导航和滑动操作详解](#21-导航和滑动操作详解) +22. [桌面检测和自救机制详解](#22-桌面检测和自救机制详解) +23. [日志系统详解](#23-日志系统详解) +24. [OCR预处理和优化详解](#24-ocr预处理和优化详解) +25. [路径配置系统详解](#25-路径配置系统详解) +26. [文本处理工具函数详解](#26-文本处理工具函数详解) + +--- + +## 1. 项目概述 + +### 1.1 项目简介 + +抖音福袋挂机项目是一个基于ADB(Android Debug Bridge)的自动化工具,用于在抖音直播间自动检测、筛选和参与福袋抽奖活动。项目采用Python开发,通过多种技术手段(OCR、像素检测、模板匹配)实现智能化的福袋处理流程。 + +### 1.2 核心功能 + +1. **自动检测福袋**: 在直播间自动检测福袋图标并打开详情页 +2. **智能筛选**: 根据价值、参与人数、倒计时、关键词等条件筛选福袋 +3. **自动参与**: 自动点击参与按钮,处理各种前置条件(加入粉丝团、评论等) +4. **高价值预约**: 自动记录高价值福袋,并在开奖前自动回退参与 +5. **开奖结果处理**: 自动检测开奖结果并领取奖品 +6. **直播间切换**: 支持自动切换直播间寻找更多福袋 +7. **状态管理**: 完善的预约、等待开奖、超时保护等状态管理机制 + +### 1.3 技术栈 + +- **Python 3.10+**: 主要开发语言 +- **ADB**: Android设备连接和控制 +- **PaddleOCR/EasyOCR**: OCR文字识别 +- **OpenCV**: 图像处理和模板匹配 +- **Pillow (PIL)**: 图像处理 +- **ThreadPoolExecutor**: 并行处理 +- **JSON**: 配置和状态存储 + +### 1.4 项目特点 + +- **模块化设计**: 采用Mixin模式,功能模块化,易于维护和扩展 +- **多分辨率支持**: 自动适配不同设备分辨率(基准1080x2400) +- **并行处理**: 使用线程池并行执行OCR任务,提高效率 +- **智能检测**: 结合像素检测、模板匹配、OCR多种技术,提高检测准确率 +- **完善的状态管理**: 预约、等待开奖、超时保护等机制 +- **详细的日志系统**: 统一的日志记录,便于调试和分析 + +--- + +## 2. 项目架构 + +### 2.1 整体架构 + +项目采用**模块化架构**,核心类 `fudai_analyse` 通过**Mixin模式**组合多个功能模块: + +``` +fudai_analyse (核心调度器) +├── NavigationMixin (导航功能) +├── StageDetectionMixin (阶段检测) +├── PopupHandlerMixin (弹窗处理) +├── LotteryResultMixin (抽奖结果) +├── RoomUtilsMixin (直播间工具) +└── MainLogicMixin (主逻辑) +``` + +### 2.2 目录结构 + +``` +douyin_guaji-main/ +├── douyin/ # 核心业务逻辑 +│ ├── core/ # 核心流程控制 +│ │ ├── douyin_fudai.py # 主类定义(Mixin组合) +│ │ ├── douyin_flow_control.py # 流程控制 +│ │ └── fudai_modules/ # Mixin模块 +│ ├── stage/ # 阶段诊断 +│ ├── detection/ # 检测模块(像素、模板) +│ ├── fudai/ # 福袋处理 +│ ├── reservation/ # 预约逻辑 +│ ├── handlers/ # 各种处理器 +│ ├── logging/ # 日志系统 +│ └── utils/ # 工具函数 +├── operations/ # 底层操作封装 +│ ├── device_operations.py # 设备操作 +│ ├── screenshot_operations.py # 截图操作 +│ ├── ocr_operations.py # OCR操作 +│ └── image_operations.py # 图像处理 +├── gui/ # GUI界面 +│ ├── gui_app.py # Tkinter GUI +│ └── web_gui.py # Web GUI +├── config/ # 配置文件 +│ └── config.json # 主配置文件 +├── state/ # 状态文件 +│ ├── reservations.json # 预约数据 +│ └── high_value_rooms.json # 高价值直播间 +├── logs/ # 日志文件 +├── pic/ # 截图和临时图片 +├── assets/ # 模板图片 +├── run_cli.py # CLI入口 +├── Underlying_Operations.py # 底层操作类(兼容) +└── path_config.py # 路径配置 +``` + +### 2.3 设计模式 + +#### 2.3.1 Mixin模式 + +核心类 `fudai_analyse` 通过多重继承组合多个Mixin类,每个Mixin负责特定功能: + +```python +class fudai_analyse( + NavigationMixin, # 导航功能 + StageDetectionMixin, # 阶段检测 + PopupHandlerMixin, # 弹窗处理 + LotteryResultMixin, # 抽奖结果 + RoomUtilsMixin, # 直播间工具 + MainLogicMixin, # 主逻辑 +): + """福袋抽奖相关操作类""" +``` + +**优势**: +- 功能模块化,职责清晰 +- 易于扩展和维护 +- 避免单文件过大 + +#### 2.3.2 回调函数模式 + +流程控制函数使用回调函数模式,提高灵活性: + +```python +def handle_no_fudai_situation( + analyser, + swipe_up_switch_callback, # 上滑切换回调 + swipe_down_back_callback, # 下滑回退回调 + seek_reservation_room_callback, # 查找预约直播间回调 + ... +): + # 使用回调函数执行具体操作 +``` + +#### 2.3.3 状态管理模式 + +使用JSON文件持久化状态,内存中维护运行时状态: + +- **持久化状态**: `state/reservations.json` - 预约数据 +- **运行时状态**: `fudai_analyse` 类的属性 - 等待开奖、滑动次数等 + +--- + +## 3. 完整流程图(含函数调用链) + +### 3.1 程序启动流程 + +```javascript +run_cli.py::main(argv) + ↓ +[解析命令行参数] + ├─> parse_args(argv) + └─> 创建 fudai_analyse 对象 + ↓ +fudai_analyse.__init__() + ├─> 初始化设备属性 + ├─> 初始化底层操作对象 (underlying_operations) + ├─> 初始化日志系统 + └─> 初始化状态管理属性 + ↓ +fudai_analyse.fudai_choujiang(device_id, y_pianyi, needswitch, wait_minutes) + ├─> 设置设备ID和分辨率 + ├─> 加载配置 (load_config) + └─> 进入无限循环 + └─> fudai_analyse.run_once_basic() [循环调用] +``` + +**关键函数说明**: + +- `run_cli.py::main()`: 命令行入口,解析参数并创建分析器对象 +- `fudai_analyse.__init__()`: 初始化所有核心属性 +- `fudai_analyse.fudai_choujiang()`: 主循环入口,启动无限循环 + +--- + +### 3.2 单次循环完整流程 (`run_once_basic`) + +```javascript +run_once_basic(recursion_depth=0) + ↓ +[检查1] 预约回退直接参与标志 (_reservation_back_direct_attend) + ├─> 是 → _handle_reservation_direct_attend() → return + └─> 否 → 继续 + ↓ +[检查2] 等待开奖状态 (_waiting_for_lottery_result) + ├─> 是 → 检查预约抢占 → 检查开奖结果 → return + └─> 否 → 继续 + ↓ +[检查3] 30分钟超时检查 + ├─> 超时 → _return_to_recommend_and_reenter_live() → return + └─> 未超时 → 继续 + ↓ +[步骤1] 加载预约数据 + └─> douyin_reservation_logic.load_reservations_from_state(analyser) + └─> 读取 state/reservations.json + └─> 更新 analyser.reservations + ↓ +[步骤2] 处理预约回退窗口 + └─> douyin_reservation_logic.process_reservation_attend_window(analyser, ...) + ├─> 检查距离开奖时间 + ├─> 如果 ≤ high_value_fudai_join_ahead_seconds + │ ├─> 触发回退 → _seek_reservation_room() → swipe_down_back_from_live() → return + └─> 未触发 → 继续 + ↓ +[步骤3] 获取截图 + └─> analyser.operation.get_screenshot(device_id) + └─> ADB命令: adb -s {device_id} exec-out screencap -p + └─> 保存到 pic/screenshot.png + ↓ +[步骤4] 阶段诊断 + └─> diagnose_stage_from_current_screen(analyser) + ├─> 步骤0: 检测直播间(优先级最高) + │ ├─> _check_in_live_room_by_pixel() - 像素检测 + │ ├─> _check_in_live_room_by_icon() - 模板匹配 + │ └─> _check_in_live_room_by_ocr() - OCR回退 + ├─> 步骤1: 并行像素检测 + │ └─> read_pixel_stage_state_from_screenshot() + │ ├─> detect_shopping_redpacket_background() + │ ├─> detect_coupon_background() + │ ├─> detect_attend_button_red_area() + │ ├─> detect_fansclub_join_red_area() + │ ├─> detect_fudai_detail_page() + │ └─> detect_lucky_draw_result_popup() + └─> 返回阶段结果 (IN_LIVE_ROOM, FUDai_DETAIL, FUDai_RESULT, 等) + ↓ +[步骤5] 根据阶段执行逻辑 + ├─> IN_LIVE_ROOM → _handle_live_room_has_or_not_fudai() + ├─> FUDai_DETAIL → _handle_in_fudai_detail() + ├─> FUDai_RESULT → _handle_lottery_result() + ├─> COUPON_POPUP → _check_coupon_popup() → 关闭弹窗 + ├─> SHOPPING_REDPACKET_POPUP → _check_shopping_redpacket_popup() → 关闭弹窗 + └─> 其他 → 导航到直播间 +``` + +**关键函数说明**: + +- `run_once_basic()`: 单次循环的核心函数,包含所有检查和处理逻辑 +- `diagnose_stage_from_current_screen()`: 综合诊断当前页面阶段 +- `process_reservation_attend_window()`: 处理预约回退窗口 + +--- + +### 3.3 直播间处理流程 (`_handle_live_room_has_or_not_fudai`) + +```javascript +_handle_live_room_has_or_not_fudai() + ↓ +find_and_open_fudai_detail(analyser, room_pos_ref) + ├─> analyser.operation.get_screenshot(device_id) + ├─> 查找福袋图标 + │ ├─> 像素检测 (优先) + │ │ └─> detect_fudai_icon_by_pixel() + │ └─> 模板匹配 (可选,如果启用 fudai_template_match_enabled) + │ └─> template_match_fudai_icon() + ├─> 如果找到福袋图标 + │ ├─> analyser.operation.click(device_id, x, y) + │ └─> 智能等待详情页打开 + │ ├─> 最小等待 (fudai_detail_initial_wait_seconds, 默认0.8秒) + │ ├─> 循环检测详情页是否打开 + │ │ ├─> diagnose_stage_from_current_screen(analyser) + │ │ └─> 如果检测到 FUDai_DETAIL → 成功 + │ └─> 最大等待 (fudai_click_wait_seconds, 默认1.7秒) + └─> 如果未找到福袋图标 + └─> 返回 False + ↓ +[结果判断] + ├─> 成功打开 → _handle_in_fudai_detail() + └─> 未找到福袋 → handle_no_fudai_situation(analyser, ...) + ├─> process_reservation_attend_window(analyser, ...) + │ └─> 如果触发预约回退 → return True + └─> 如果未触发预约回退,且 needswitch=true + └─> swipe_up_to_next_live() + └─> analyser.operation.swipe(device_id, x1, y1, x2, y2, duration_ms) + └─> _swipe_times += 1 + └─> _maybe_reset_after_swipes() [检查是否需要重置] +``` + +**关键函数说明**: + +- `find_and_open_fudai_detail()`: 查找并打开福袋详情页 +- `handle_no_fudai_situation()`: 处理未找到福袋的情况(预约回退或切换直播间) + +--- + +### 3.4 福袋详情处理流程 (`_handle_in_fudai_detail`) + +```javascript +_handle_in_fudai_detail() + ↓ +[步骤1] 读取福袋信息 + └─> get_fudai_contain(analyser, renwu=2) + ├─> 并行OCR (ThreadPoolExecutor, 6个线程) + │ ├─> ocr_task_list() - 任务列表 OCR + │ │ └─> 识别区域: (200, 600, 880, 900) + │ ├─> ocr_content() - 福袋内容 OCR + │ │ └─> 识别区域: (200, 600, 880, 900) + │ ├─> ocr_countdown_mm() - 倒计时分钟 OCR + │ │ └─> 识别区域: (390, 1140, 480, 1290) + │ ├─> ocr_countdown_ss() - 倒计时秒 OCR + │ │ └─> 识别区域: (480, 1140, 570, 1290) + │ ├─> ocr_value() - 价值 OCR + │ │ └─> 识别区域: (200, 1400, 880, 1600) + │ └─> ocr_button() - 按钮状态 OCR + │ └─> 识别区域: (306, 2030, 780, 2110) + │ └─> 存储到 analyser._fudai_button_status, analyser._fudai_button_text + │ └─> 记录识别时间 analyser._fudai_button_ocr_time + ├─> 解析倒计时 (normalize_countdown_text) + │ └─> 如果整体识别失败,使用分割识别结果 (mm + ss) + ├─> 解析价值 (extract_prize_value_yuan) + │ └─> 从OCR文本中提取数字(元) + └─> 解析参与人数 + └─> 从任务列表OCR结果中提取 + ↓ + 返回: (content, countdown_text, participants, task_count, prize_value_yuan) + ↓ +[步骤2] 数据验证 + └─> fudai_detail_validator.validate_fudai_detail(analyser, detail) + ├─> 验证倒计时格式 + ├─> 验证价值范围 + └─> 验证参与人数 + ↓ +[步骤3] 筛选判断 + └─> basic_join_decision(analyser, detail) + ├─> 价值筛选: prize_value_yuan >= min_prize_value_yuan + ├─> 参与人数筛选: min_participants <= participants <= max_participants + ├─> 倒计时筛选: countdown >= skip_if_countdown_lt_seconds + ├─> 关键词筛选: + │ ├─> contains_want: 必须包含的关键词(任意一个匹配即可) + │ └─> contains_not_want: 不能包含的关键词(任意一个匹配即跳过) + └─> 高价值预约: + └─> 如果价值 ≥ high_value_fudai_threshold_yuan + └─> 记录到 state/reservations.json + └─> 包含: room_title, lottery_time_ts, prize_value_yuan, fudai_x + ↓ +[步骤4] 根据筛选结果 + ├─> 通过筛选 → attend_choujiang(analyser) + │ ├─> 识别按钮状态 + │ │ ├─> 优先使用并行OCR结果(5秒内有效) + │ │ │ ├─> 检查 analyser._fudai_button_text 和 analyser._fudai_button_status + │ │ │ └─> 检查 analyser._fudai_button_ocr_time 是否在5秒内 + │ │ └─> 如果不可用,重新识别按钮 + │ │ ├─> 裁剪按钮区域 (analyser.cut_pic) + │ │ ├─> 图像预处理 (preprocess_for_ocr) + │ │ └─> OCR识别(模式0和模式1) + │ ├─> 根据按钮状态执行操作: + │ │ ├─> "已参与" → 设置 _waiting_for_lottery_result = True + │ │ │ └─> 计算 _lottery_result_expected_ts = 当前时间 + 倒计时秒数 + │ │ │ └─> 更新 _last_successful_attend_ts = 当前时间 + │ │ ├─> "需要加入粉丝团" → 加入粉丝团 + │ │ │ └─> 点击粉丝团加入按钮 + │ │ │ └─> 如果失败且 fansclub_fail_action="switch" → 切换直播间 + │ │ ├─> "需要评论" → 发送评论 + │ │ │ └─> 点击评论输入框 + │ │ │ └─> 输入评论内容(使用ADB键盘) + │ │ │ └─> 点击发送按钮 + │ │ └─> "可以参与" → 点击参与按钮 + │ │ └─> analyser.operation.click(device_id, x, y) + │ │ └─> 更新 _last_successful_attend_ts = 当前时间 + │ └─> 最多重试2次 + └─> 未通过筛选 → 关闭详情页 → 切换直播间 (如果 needswitch=true) + └─> 点击返回按钮 + └─> swipe_up_to_next_live() +``` + +**关键函数说明**: + +- `get_fudai_contain()`: 并行OCR获取福袋完整信息 +- `basic_join_decision()`: 根据配置筛选福袋 +- `attend_choujiang()`: 点击参与抽奖,处理各种前置条件 + +--- + +## 4. 关键函数详细说明 + +### 4.1 入口函数 + +#### `run_cli.py::main(argv: list[str]) -> int` + +- **文件位置**: `run_cli.py` +- **作用**: 命令行入口函数,解析参数并启动主程序 +- **参数**: + - `argv`: 命令行参数列表 +- **返回值**: 退出码 (0=成功, 其他=失败) +- **调用位置**: 命令行直接调用(`if __name__ == "__main__"`) +- **主要逻辑**: + 1. 确保ADB在PATH中 (`ensure_adb_in_path()`) + 2. 解析命令行参数 (`parse_args(argv)`) + 3. 配置输出编码(UTF-8,实时刷新) + 4. 创建 `fudai_analyse` 对象 + 5. 设置配置覆盖(从命令行参数) + 6. 调用 `fudai_choujiang()` 启动主循环 + +**代码示例**: +```python +def main(argv: list[str]) -> int: + ensure_adb_in_path() + args = parse_args(argv) + + # 配置输出编码 + sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) + + analyser = fudai_analyse() + + # 从命令行参数设置配置 + if args.device_id: + analyser.device_id = args.device_id + if args.needswitch is not None: + analyser.needswitch = args.needswitch + + # 启动主循环 + analyser.fudai_choujiang( + device_id=args.device_id or "", + y_pianyi=int(args.y_pianyi or 0), + needswitch=args.needswitch, + wait_minutes=int(args.wait_minutes or 0) + ) + + return 0 +``` + +--- + +#### `fudai_analyse.fudai_choujiang(device_id, y_pianyi, needswitch, wait_minutes)` + +- **文件位置**: `douyin/core/fudai_modules/fudai_main_logic.py` (MainLogicMixin) +- **作用**: 主循环入口,初始化并启动无限循环 +- **参数**: + - `device_id: str`: 设备ID(如果为空,会自动选择设备) + - `y_pianyi: int`: Y轴偏移,用于调整点击坐标 + - `needswitch: bool`: 是否允许切换直播间 + - `wait_minutes: int`: 运行时长(分钟,0表示无限) +- **返回值**: None +- **调用位置**: `run_cli.py::main()`, GUI启动 +- **主要逻辑**: + 1. 设置设备ID和分辨率 + - 如果 `device_id` 为空,调用 `operation.select_device()` 选择设备 + - 获取设备分辨率 (`operation.get_device_resolution()`) + 2. 加载配置 (`load_config()`) + - 从 `config/config.json` 读取配置 + - 更新 `self.needswitch` 等属性 + 3. 初始化运行状态 + - 设置 `_run_start_ts = time.time()` + - 初始化 `_last_successful_attend_ts` + 4. 进入无限循环调用 `run_once_basic()` + - 如果 `wait_minutes > 0`,检查运行时间是否超过限制 + - 每次循环后延迟0.1秒(避免CPU占用过高) + +**代码示例**: +```python +def fudai_choujiang(self, device_id: str = "", y_pianyi: int = 0, + needswitch: bool = False, wait_minutes: int = 15) -> None: + # 设置设备ID + if not device_id: + device_id = self.operation.select_device() + self.device_id = device_id + + # 设置Y偏移和分辨率 + self.y_pianyi = y_pianyi + self.resolution_ratio_x, self.resolution_ratio_y = \ + self.operation.get_device_resolution(device_id) + + # 加载配置 + self.load_config() + if needswitch is not None: + self.needswitch = needswitch + + # 初始化运行状态 + self._run_start_ts = time.time() + self._last_successful_attend_ts = self._run_start_ts + + # 进入无限循环 + while True: + if wait_minutes > 0: + if time.time() - self._run_start_ts > wait_minutes * 60: + break + + self.run_once_basic() + time.sleep(0.1) +``` + +--- + +### 4.2 主循环函数 + +#### `fudai_analyse.run_once_basic(recursion_depth: int = 0) -> None` + +- **文件位置**: `douyin/core/douyin_fudai.py`(实际实现位置) +- **作用**: 单次循环执行,包含所有核心逻辑 +- **参数**: 无(`recursion_depth` 参数已移除) +- **返回值**: None +- **调用位置**: `fudai_choujiang()` 循环调用 +- **主要逻辑**(按执行顺序): + + **0. 检查等待开奖状态** (`_waiting_for_lottery_result`) + - 如果为 `True`,执行以下逻辑: + 1. **检查预约抢占**: + - 如果启用高价值预约且预约队列不为空,调用 `process_reservation_attend_window()` 检查是否需要抢占 + - 如果检测到预约需要处理,清除等待开奖标志,中断等待,继续执行后续逻辑 + 2. **等待开奖时间检查**: + - 计算剩余秒数:`remain_seconds = max(0, future_ts - current_ts + 6.0)`(加上6秒延迟修正) + - 开奖检测开始时间:`check_start_ts = future_ts + 1.0`(开奖时间+1秒缓冲) + - 超时时间:`timeout_ts = future_ts + 10.0`(超过开奖时间10秒清除等待标志) + 3. **超时处理**: + - 如果 `current_ts >= timeout_ts`,清除等待标志,继续执行其他操作 + 4. **开奖结果检测**: + - 如果 `current_ts >= check_start_ts`,开始检测开奖结果: + - **直接点击模式**: 直接点击"我知道了"按钮(坐标532, 1322,最多点击10次,每次间隔1秒) + - 每次点击后通过阶段诊断检查是否还在开奖结果弹窗(`FUDai_RESULT`) + - 如果弹窗已关闭,停止点击 + - 如果直接点击失败,回退到OCR识别方式 + - 如果OCR识别到结果,调用 `_handle_lottery_result_by_ocr()` 处理 + - 清除等待标志,切换直播间(如果允许) + 5. **等待中**: + - 如果还未到开奖时间,短暂等待(`min(2.0, remain_seconds)`)后返回 + + **0.1. 检查30分钟超时** (`_no_attend_timeout_minutes`) + - 如果距离 `_last_successful_attend_ts` 超过 `_no_attend_timeout_minutes` 分钟(默认30分钟): + - 调用 `_return_to_recommend_and_reenter_live()` 返回推荐页面并重新进入直播间 + - 重置最后成功参与时间(避免立即再次触发) + - 返回,不执行后续逻辑 + - 如果从未成功参与过,检查运行时间: + - 如果运行时间超过30分钟,同样触发超时处理 + + **0.2. 处理预约回退窗口**(如果启用高价值预约) + 1. **第一次运行处理**: + - 如果是第一次运行(`_first_run_once_basic = True`),清空预约队列,不加载状态文件 + - 同时清空状态文件,确保外部查看时也是空的 + - 标记已运行过(`_first_run_once_basic = False`) + 2. **预约回退检查**: + - 如果启用高价值预约且预约队列不为空,调用 `process_reservation_attend_window()` 检查是否需要回退 + - 如果触发回退,设置 `_reservation_back_direct_attend = True` + + **1. 检查预约回退直接参与标志** (`_reservation_back_direct_attend`) + - 如果为 `True`,调用 `_handle_reservation_direct_attend()` 处理并返回 + + **2. 获取截图并执行阶段诊断** + - 调用 `operation.get_screenshot()` 获取截图 + - 调用 `_diagnose_stage_from_current_screen()` 执行阶段诊断 + - 根据诊断结果执行相应的处理逻辑 + + **3. 根据阶段执行相应逻辑** + - `FUDai_DETAIL`: 调用 `_handle_in_fudai_detail()` 处理福袋详情 + - `LIVE_ROOM`: 调用 `_handle_live_room_has_or_not_fudai()` 处理直播间 + - `FUDai_RESULT`: 调用 `_handle_lottery_result()` 处理开奖结果 + - 其他阶段:执行相应的处理逻辑(导航到直播间等) + + **4. 桌面检测和自救机制**(阶段诊断后) + - 检测是否意外返回桌面(不在抖音前台) + - 如果检测到不在抖音前台,尝试恢复: + - 点击桌面图标(坐标:`desktop_icon_x`, `desktop_icon_y` 或默认 153, 260) + - 点击直播按钮(坐标:`yanghao_fallback_live_x`, `yanghao_fallback_live_y`) + - 点击进入直播间(坐标:`yanghao_fallback_enter_live_x`, `yanghao_fallback_enter_live_y`,点击2次) + - 自救完成后,递归调用 `run_once_basic()` 重新执行主流程 + +**代码示例**: +```python +def run_once_basic(self) -> None: + start_time = time.time() + + # 0. 检查等待开奖状态 + if getattr(self, "_waiting_for_lottery_result", False): + # 检查预约抢占 + if high_value_enabled and reservations: + preempted = process_reservation_attend_window(...) + if preempted: + self._waiting_for_lottery_result = False + # 继续执行后续逻辑 + else: + # 等待开奖时间检查 + remain_seconds = max(0, future_ts - current_ts + 6.0) + check_start_ts = future_ts + 1.0 + timeout_ts = future_ts + 10.0 + + if current_ts >= timeout_ts: + self._waiting_for_lottery_result = False + elif current_ts >= check_start_ts: + # 直接点击"我知道了"按钮或OCR识别 + # ... + else: + # 等待中 + wait_s = min(2.0, remain_seconds) + self.operation.delay(wait_s) + return + + # 0.1. 检查30分钟超时 + if self._last_successful_attend_ts > 0: + elapsed_minutes = (time.time() - self._last_successful_attend_ts) / 60.0 + if elapsed_minutes >= self._no_attend_timeout_minutes: + self._return_to_recommend_and_reenter_live() + self._last_successful_attend_ts = time.time() + return + + # 0.2. 处理预约回退窗口 + if is_first_run: + # 清空预约队列和状态文件 + self.reservations = [] + write_reservations_state(...) + self._first_run_once_basic = False + + if queue_full: + # 回退到最早开奖的预约直播间等待 + handle_queue_full_wait_at_earliest(...) + return + + if process_reservation_attend_window(...): + self._reservation_back_direct_attend = True + + # 1. 检查预约回退直接参与标志 + if self._reservation_back_direct_attend: + self._handle_reservation_direct_attend() + return + + # 2. 检查跳过阶段诊断标志 + if self._skip_stage_diagnosis_and_find_fudai: + self._skip_stage_diagnosis_and_find_fudai = False + self._handle_live_room_has_or_not_fudai() + return + + # 3. 获取截图并执行阶段诊断 + if not self.operation.get_screenshot(self.device_id): + return + + stage, seen = self._diagnose_stage_from_current_screen() + self._last_diag_stage = stage + self._last_diag_seen = seen + self._last_diag_ts = time.time() + + # 4. 桌面检测和自救机制 + top_pkg = self.operation.get_top_package(self.device_id) + if top_pkg and not is_douyin_pkg(top_pkg): + # 尝试恢复 + self.click(self.desktop_icon_x, self.desktop_icon_y) + # ... 其他恢复操作 + self.run_once_basic() # 递归调用 + return + + # 5. 根据阶段执行相应逻辑 + if stage == "FUDai_DETAIL": + self._handle_in_fudai_detail() + elif stage == "LIVE_ROOM": + self._handle_live_room_has_or_not_fudai() + elif stage == "FUDai_RESULT": + self._handle_lottery_result() + # ... 其他阶段处理 +``` + +### 4.3 阶段诊断函数 + +#### `douyin_stage.diagnose_stage_from_current_screen(analyser) -> Tuple[str, str]` + +- **文件位置**: `douyin/stage/douyin_stage.py` +- **作用**: 综合诊断当前页面阶段,使用多种检测方法确保准确性 +- **参数**: + - `analyser`: 分析器对象 +- **返回值**: `Tuple[str, str]` - (阶段字符串, 识别结果描述) + - `IN_LIVE_ROOM`: 直播间 + - `FUDai_DETAIL`: 福袋详情页 + - `FUDai_RESULT`: 抽奖结果页 + - `RECOMMEND_PAGE`: 推荐页 + - `COUPON_POPUP`: 优惠券弹窗 + - `SHOPPING_REDPACKET_POPUP`: 购物红包弹窗 + - 等其他阶段 +- **调用位置**: `run_once_basic()` 中调用 +- **主要逻辑**: + + 1. **步骤0: 检测直播间(优先级最高)** + - **像素检测** (`detect_live_room_icons_by_pixel`) + - 检测直播间特征像素(点赞、收藏、评论图标区域) + - 返回置信度分数(0.0-1.0) + - 如果置信度 ≥ `live_room_match_threshold`(默认0.8),判定为直播间 + - **模板匹配** (`_check_in_live_room_by_icon`) + - 使用OpenCV模板匹配检测直播间图标 + - 匹配多个模板(`assets/like.png`, `assets/fav.png`, `assets/xin.png`等) + - 如果匹配度 ≥ `live_room_match_threshold`,判定为直播间 + - **OCR回退** (`_check_in_live_room_by_ocr`) + - 如果前两种方法都失败,使用OCR识别直播间标题 + - 识别区域:屏幕顶部标题区域 + - 如果识别到直播间特征文字,判定为直播间 + + 2. **步骤1: 并行像素检测** + - 调用 `read_pixel_stage_state_from_screenshot()` 并行检测多个区域 + - 检测项目: + - `shopping_redpacket_background`: 购物红包背景 + - `coupon_background`: 优惠券背景 + - `attend_button_red_region`: 参与按钮红色区域 + - `fansclub_join_red_region`: 粉丝团加入红色区域 + - `fudai_detail_page`: 福袋详情页 + - `lottery_result_popup`: 抽奖结果弹窗 + + 3. **综合判断返回阶段** + - 根据像素检测结果,按优先级判断阶段 + - 优先级:`FUDai_RESULT` > `FUDai_DETAIL` > `COUPON_POPUP` > `SHOPPING_REDPACKET_POPUP` > `IN_LIVE_ROOM` + +**配置参数**: +- `stage_diag_max_time`: 最大诊断时间(秒,默认10.0) +- `stage_diag_max_step_time`: 单步最大耗时(秒,默认2.0) +- `live_room_match_threshold`: 直播间检测阈值(0.0-1.0,默认0.8) +- `stage_diag_verbose`: 是否输出详细日志(bool,默认False) + +**代码示例**: +```python +def diagnose_stage_from_current_screen(analyser): + # 步骤0: 检测直播间 + in_live_room, confidence = detect_live_room_icons_by_pixel(pic_rgb) + if in_live_room and confidence >= pixel_threshold: + return "IN_LIVE_ROOM", "直播间(像素检测)" + + # 如果像素检测失败,尝试模板匹配 + in_live_room, score = _check_in_live_room_by_icon(analyser) + if in_live_room and score >= template_threshold: + return "IN_LIVE_ROOM", f"直播间(模板匹配,分数={score})" + + # 步骤1: 并行像素检测 + pixel_state = read_pixel_stage_state_from_screenshot(...) + + # 综合判断 + if pixel_state["lottery_result_popup"]: + return "FUDai_RESULT", "抽奖结果页" + if pixel_state["fudai_detail_page"]: + return "FUDai_DETAIL", "福袋详情页" + # ... 其他判断 +``` + +--- + +#### `douyin_pixel.read_pixel_stage_state_from_screenshot(pic_path, ...) -> dict` + +- **文件位置**: `douyin/detection/douyin_pixel.py` +- **作用**: 并行像素检测,检测多个区域的特征,用于阶段诊断 +- **参数**: + - `pic_path: str`: 截图路径 + - `resolution_ratio_x: int`: 分辨率X(默认1080) + - `resolution_ratio_y: int`: 分辨率Y(默认2400) + - `y_pianyi: int`: Y轴偏移(默认0) + - `lucky_draw_red_ratio_threshold: float`: 抽奖结果弹窗红色比例阈值(默认0.8) + - `fudai_template_threshold: float`: 福袋模板匹配阈值(默认0.7) + - `return_details: bool`: 是否返回详细信息(默认False) + - `analyser: Any`: 分析器对象(可选) +- **返回值**: `dict[str, bool]` 或 `tuple[dict[str, bool], dict[str, dict]]`(如果 `return_details=True`) + - `shopping_redpacket_background: bool`: 购物红包背景 + - `coupon_background: bool`: 优惠券背景 + - `attend_button_red_region: bool`: 参与按钮红色区域 + - `fansclub_join_red_region: bool`: 粉丝团加入红色区域 + - `fudai_detail_page: bool`: 福袋详情页 + - `lottery_result_popup: bool`: 抽奖结果弹窗 +- **调用位置**: `diagnose_stage_from_current_screen()` 中调用 +- **检测方法**: + - 在指定区域采样像素,统计符合特征的颜色比例 + - 使用 `ThreadPoolExecutor` 并行执行多个检测任务 + - 每个检测函数独立采样像素并计算比例 + +**检测原理**: +1. 读取截图并转换为RGB格式 +2. 根据基准分辨率(1080x2400)和实际分辨率缩放坐标 +3. 在指定区域采样像素(通常每5像素采样一次) +4. 统计符合特征颜色的像素比例 +5. 如果比例 ≥ 阈值,判定为检测到该特征 + +**代码示例**: +```python +def read_pixel_stage_state_from_screenshot( + pic_path: str, + resolution_ratio_x: int = 1080, + resolution_ratio_y: int = 2400, + y_pianyi: int = 0, + lucky_draw_red_ratio_threshold: float = 0.8, + fudai_template_threshold: float = 0.7, + return_details: bool = False, + analyser: Any = None +) -> dict[str, bool]: + pic_rgb = _safe_open_screenshot_rgb(pic_path) + if pic_rgb is None: + return {} + + # 并行执行多个检测任务 + with ThreadPoolExecutor(max_workers=6) as executor: + future_shopping = executor.submit( + detect_shopping_redpacket_background, pic_rgb, ... + ) + future_coupon = executor.submit( + detect_coupon_background, pic_rgb, ... + ) + # ... 其他检测任务 + + results = { + "shopping_redpacket_background": future_shopping.result(), + "coupon_background": future_coupon.result(), + # ... 其他结果 + } + + return results +``` + +--- + +### 4.4 福袋查找函数 + +#### `douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) -> bool` + +- **文件位置**: `douyin/core/douyin_flow_control.py` +- **作用**: 查找并打开福袋详情页 +- **参数**: + - `analyser: Any`: 分析器对象 + - `room_pos_ref: List[int]`: 直播间位置引用(列表,用于更新位置) +- **返回值**: `bool` - `True`=成功打开, `False`=未找到 +- **调用位置**: `_handle_live_room_has_or_not_fudai()` 中调用 +- **主要逻辑**: + + 1. **检查等待开奖状态** + - 如果 `_waiting_for_lottery_result = True`,直接返回 `False`(避免重复打开) + + 2. **获取截图** + - 调用 `analyser.operation.get_screenshot(device_id)` 获取最新截图 + + 3. **查找福袋图标** + - **像素检测(优先)** + - 调用 `check_have_fudai_with_ready_screenshot()` 检测福袋图标 + - 在配置的最大等待时间内重复检测(`fudai_icon_max_wait_seconds`,默认8.5秒) + - 重试间隔:`fudai_icon_retry_delay_seconds`(默认0.1秒) + - **模板匹配(可选)** + - 如果启用 `fudai_template_match_enabled`,使用OpenCV模板匹配 + - 匹配模板:`assets/fudai.png` + - 匹配阈值:`fudai_template_match_threshold`(默认0.7) + + 4. **点击福袋图标** + - 如果找到福袋图标,调用 `analyser.operation.click(device_id, x, y)` 点击 + + 5. **智能等待详情页打开** + - **最小等待时间**: `fudai_detail_initial_wait_seconds`(默认0.8秒) + - **循环检测详情页是否打开** + - 每次等待 `fudai_detail_verified_wait_seconds`(默认0.2秒) + - 调用 `diagnose_stage_from_current_screen()` 检测阶段 + - 如果检测到 `FUDai_DETAIL`,判定为成功打开 + - **最大等待时间**: `fudai_click_wait_seconds`(默认1.7秒) + - 如果超时仍未打开,返回 `False` + +**配置参数**: +- `fudai_find_max_attempts`: 最大尝试次数(默认99999) +- `fudai_icon_retry_delay_seconds`: 重试间隔(秒,默认0.1) +- `fudai_icon_max_wait_seconds`: 最大等待时间(秒,默认8.5) +- `fudai_click_wait_seconds`: 点击后等待时间(秒,默认1.7) +- `fudai_detail_initial_wait_seconds`: 详情页初始等待时间(秒,默认0.8) +- `fudai_detail_verified_wait_seconds`: 详情页验证等待时间(秒,默认0.2) +- `fudai_template_match_enabled`: 是否启用模板匹配(bool,默认False) +- `fudai_template_match_threshold`: 模板匹配阈值(默认0.7) + +**代码示例**: +```python +def find_and_open_fudai_detail(analyser: Any, room_pos_ref: List[int]) -> bool: + # 检查等待开奖状态 + if getattr(analyser, "_waiting_for_lottery_result", False): + return False + + # 在最大等待时间内重复检测福袋图标 + max_wait_seconds = getattr(analyser, "fudai_icon_max_wait_seconds", 8.5) + start_time = time.time() + x = False + + while (time.time() - start_time) < max_wait_seconds: + x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) + if x: + break + time.sleep(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.1)) + + if not x: + return False + + # 点击福袋图标 + analyser.operation.click(analyser.device_id, x, analyser.y_pianyi + 2000) + + # 智能等待详情页打开 + initial_wait = getattr(analyser, "fudai_detail_initial_wait_seconds", 0.8) + time.sleep(initial_wait) + + max_wait = getattr(analyser, "fudai_click_wait_seconds", 1.7) + verified_wait = getattr(analyser, "fudai_detail_verified_wait_seconds", 0.2) + start_time = time.time() + + while (time.time() - start_time) < max_wait: + stage, _ = diagnose_stage_from_current_screen(analyser) + if stage == "FUDai_DETAIL": + return True + time.sleep(verified_wait) + + return False +``` + +--- + +#### `douyin_flow_control.handle_no_fudai_situation(analyser, ...) -> bool` + +- **文件位置**: `douyin/core/douyin_flow_control.py` +- **作用**: 处理未找到福袋的情况,包括预约回退和切换直播间 +- **参数**: + - `analyser: Any`: 分析器对象 + - `x: int`: 福袋X坐标(未使用,保留兼容性) + - `swipe_times: int`: 滑动次数(未使用,保留兼容性) + - `wait_times_ref: List[int]`: 等待次数引用(未使用) + - `needswitch: bool`: 是否允许切换直播间 + - `reservation_focus_until_ts: float`: 预约聚焦时间戳 + - `reservations: list`: 预约列表 + - `room_pos: int`: 当前直播间位置 + - `post_switch_delay_s: float`: 切换后延迟(秒) + - `swipe_up_switch_callback: Callable`: 上滑切换回调函数 + - `swipe_down_back_callback: Callable`: 下滑回退回调函数 + - `seek_reservation_room_callback: Callable`: 查找预约直播间回调函数 + - `sort_reservations_callback: Callable`: 排序预约回调函数 + - `write_state_callback: Callable`: 写入状态回调函数 + - `reservation_focus_until_ts_ref: List[float]`: 预约聚焦时间戳引用 + - `reset_to_list_after_reservations_ref: List[bool]`: 重置到列表标志引用 + - `swipe_times_ref: List[int]`: 滑动次数引用 +- **返回值**: `bool` - `True`=已处理预约回退, `False`=未处理 +- **调用位置**: `_handle_live_room_has_or_not_fudai()` 中调用 +- **主要逻辑**: + + 1. **处理预约回退窗口** + - 调用 `process_reservation_attend_window()` 检查是否需要回退到预约直播间 + - 如果触发预约回退,返回 `True` + + 2. **切换直播间(如果未触发预约回退)** + - 如果 `needswitch = True`,调用 `swipe_up_switch_callback()` 上滑切换直播间 + - 等待 `post_switch_delay_s` 秒 + - 更新滑动次数计数器 + +**代码示例**: +```python +def handle_no_fudai_situation( + analyser: Any, + x: int, + swipe_times: int, + wait_times_ref: List[int], + needswitch: bool, + reservation_focus_until_ts: float, + reservations: list, + room_pos: int, + post_switch_delay_s: float, + swipe_up_switch_callback, + swipe_down_back_callback, + seek_reservation_room_callback, + sort_reservations_callback, + write_state_callback, + back_to_list_callback, + into_list_callback, + reservation_focus_until_ts_ref: List[float], + reset_to_list_after_reservations_ref: List[bool], + swipe_times_ref: List[int] +) -> bool: + # 处理预约回退窗口 + if process_reservation_attend_window( + analyser, + reservations, + room_pos, + reservation_focus_until_ts_ref, + reservation_after_action_pending_ref, + reservation_back_swipe_delay_s, + swipe_down_back_callback, + seek_reservation_room_callback, + sort_reservations_callback, + write_state_callback + ): + return True # 已触发预约回退 + + # 如果未触发预约回退,且允许切换直播间 + if needswitch: + swipe_up_switch_callback() + time.sleep(post_switch_delay_s) + swipe_times_ref[0] += 1 + + return False +``` + +### 4.5 福袋详情处理函数 + +#### `douyin_fudai_core.get_fudai_contain(analyser, renwu: int = 2) -> Tuple` + +- **文件位置**: `douyin/fudai/douyin_fudai_core.py` +- **作用**: 获取福袋的完整信息(内容、倒计时、价值、参与人数),使用并行OCR提高效率 +- **参数**: + - `analyser: Any`: 分析器对象 + - `renwu: int`: 任务数量(用于验证,默认2) +- **返回值**: `Tuple[str, str, int, int, float]` + - `content: str`: 福袋内容文本 + - `countdown_text: str`: 倒计时文本(格式:mm:ss) + - `participants: int`: 参与人数 + - `task_count: int`: 任务数量 + - `prize_value_yuan: float`: 奖品价值(元) +- **调用位置**: `_handle_in_fudai_detail()` 中调用 +- **主要逻辑**: + + 1. **并行OCR识别(使用 `ThreadPoolExecutor`,6个线程)** + - `ocr_task_list()`: 任务列表OCR + - 识别区域: `(200, 600, 880, 900)` + - 用于提取参与人数和任务数量 + - `ocr_content()`: 福袋内容OCR + - 识别区域: `(200, 600, 880, 900)` + - 识别福袋内容描述 + - `ocr_countdown_mm()`: 倒计时分钟OCR + - 识别区域: `(390, 1140, 480, 1290)` (倒计时区域的前30%) + - 识别分钟数字 + - `ocr_countdown_ss()`: 倒计时秒OCR + - 识别区域: `(480, 1140, 570, 1290)` (倒计时区域的中间30%) + - 识别秒数字 + - `ocr_value()`: 价值OCR + - 识别区域: `(200, 1400, 880, 1600)` + - 识别奖品价值(元) + - `ocr_button()`: 按钮状态OCR + - 识别区域: `(306, 2030, 780, 2110)` + - 识别参与按钮状态("已参与"、"需要加入粉丝团"、"需要评论"、"可以参与"等) + - **特殊处理**: + - 识别结果存储在 `analyser._fudai_button_status` 和 `analyser._fudai_button_text` + - 记录识别时间 `analyser._fudai_button_ocr_time`(用于判断是否可复用,5秒内有效) + + 2. **解析倒计时** + - 优先使用整体识别结果(`normalize_countdown_text`) + - 如果整体识别失败,使用分割识别结果(分钟 + 秒) + - 支持多种格式:`mm:ss`、`mm分ss秒`、`mm:ss后开奖` 等 + + 3. **解析价值** + - 使用 `extract_prize_value_yuan` 从OCR文本中提取数字(元) + - 支持格式:`200元`、`¥200`、`价值200元` 等 + + 4. **解析参与人数** + - 从任务列表OCR结果中提取参与人数 + - 支持格式:`已有1234人参与`、`参与人数:1234` 等 + + 5. **返回完整信息** + +**代码示例**: +```python +def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: + # 并行OCR识别(6个线程) + with ThreadPoolExecutor(max_workers=6) as executor: + future_task_list = executor.submit(ocr_task_list) + future_content = executor.submit(ocr_content) + future_countdown_mm = executor.submit(ocr_countdown_mm) + future_countdown_ss = executor.submit(ocr_countdown_ss) + future_value = executor.submit(ocr_value) + future_button = executor.submit(ocr_button) + + # 等待所有任务完成 + task_list_raw = future_task_list.result() + fudai_content_raw = future_content.result() + countdown_mm_raw = future_countdown_mm.result() + countdown_ss_raw = future_countdown_ss.result() + value_raw = future_value.result() + button_text_raw = future_button.result() + + # 解析倒计时 + countdown_text = normalize_countdown_text( + countdown_mm_raw, countdown_ss_raw + ) + + # 解析价值 + prize_value_yuan = extract_prize_value_yuan(value_raw) + + # 解析参与人数 + participants = extract_participants(task_list_raw) + + return (fudai_content_raw, countdown_text, participants, renwu, prize_value_yuan) +``` + +--- + +#### `douyin_fudai_core.basic_join_decision(analyser: Any, detail: Tuple) -> bool` + +- **文件位置**: `douyin/fudai/douyin_fudai_core.py` +- **作用**: 基础版参与决策,根据配置筛选福袋 +- **参数**: + - `analyser: Any`: 分析器对象 + - `detail: Tuple`: 福袋详情元组 `(content, countdown_text, participants, task_count, prize_value_yuan, countdown_tuple)` +- **返回值**: `bool` - `True`=已参与或已处理, `False`=未参与 +- **调用位置**: `_handle_in_fudai_detail()` 中调用 +- **筛选逻辑**: + + 1. **价值筛选** + - 如果 `min_prize_value_yuan > 0`,检查 `prize_value_yuan >= min_prize_value_yuan` + - 如果价值低于阈值,返回 `False`(不参与) + + 2. **参与人数筛选** + - 如果 `min_participants > 0`,检查 `participants >= min_participants` + - 如果 `max_participants > 0`,检查 `participants <= max_participants` + - 如果不在范围内,返回 `False` + + 3. **倒计时筛选** + - 如果 `skip_if_countdown_lt_seconds > 0`,检查 `countdown >= skip_if_countdown_lt_seconds` + - 如果倒计时小于阈值,返回 `False`(避免参与即将开奖的福袋) + - 如果 `skip_if_countdown_gt_seconds > 0`,检查 `countdown <= skip_if_countdown_gt_seconds` + - 如果倒计时大于阈值,返回 `False`(避免参与等待时间过长的福袋) + + 4. **关键词筛选** + - `contains_want`: 必须包含的关键词列表(任意一个匹配即可) + - 如果列表不为空,且内容中不包含任何关键词,返回 `False` + - `contains_not_want`: 不能包含的关键词列表(任意一个匹配即跳过) + - 如果内容中包含任何关键词,返回 `False` + + 5. **高价值预约** + - 如果价值 ≥ `high_value_fudai_threshold_yuan`,记录到 `state/reservations.json` + - 预约信息包含: + - `room_title`: 直播间标题 + - `lottery_time_ts`: 开奖时间戳(当前时间 + 倒计时秒数) + - `prize_value_yuan`: 奖品价值 + - `fudai_x`: 福袋X坐标 + - `reserved_at_ts`: 预约时间戳 + +**配置参数**: +- `min_prize_value_yuan`: 最低奖品价值(元,默认200.0) +- `min_participants`: 最少参与人数(默认0,表示不启用) +- `max_participants`: 最多参与人数(默认0,表示不启用) +- `skip_if_countdown_lt_seconds`: 倒计时小于该秒数时不参与(默认5) +- `skip_if_countdown_gt_seconds`: 倒计时大于该秒数时不参与(默认120) +- `contains_want`: 必须包含的关键词列表(默认[]) +- `contains_not_want`: 不能包含的关键词列表(默认["首饰盒", "袜子"]) +- `high_value_fudai_threshold_yuan`: 高价值福袋阈值(元,默认500.0) + +**代码示例**: +```python +def basic_join_decision(analyser: Any, detail: Tuple) -> bool: + content, countdown_text, participants, task_count, prize_value_yuan, countdown_tuple = detail + countdown = countdown_tuple[0] * 60 + countdown_tuple[1] if countdown_tuple else 0 + + # 价值筛选 + min_prize = analyser.config.get("min_prize_value_yuan", 200.0) + if min_prize > 0 and prize_value_yuan < min_prize: + return False + + # 参与人数筛选 + min_participants = analyser.config.get("min_participants", 0) + max_participants = analyser.config.get("max_participants", 0) + if min_participants > 0 and participants < min_participants: + return False + if max_participants > 0 and participants > max_participants: + return False + + # 倒计时筛选 + skip_lt = analyser.config.get("skip_if_countdown_lt_seconds", 5) + if skip_lt > 0 and countdown < skip_lt: + return False + skip_gt = analyser.config.get("skip_if_countdown_gt_seconds", 120) + if skip_gt > 0 and countdown > skip_gt: + return False + + # 关键词筛选 + contains_want = analyser.config.get("contains_want", []) + if contains_want and not any(kw in content for kw in contains_want): + return False + + contains_not_want = analyser.config.get("contains_not_want", []) + if contains_not_want and any(kw in content for kw in contains_not_want): + return False + + # 高价值预约 + threshold = analyser.config.get("high_value_fudai_threshold_yuan", 500.0) + if prize_value_yuan >= threshold: + # 记录预约 + reservation = { + "room_title": analyser._current_room_title or "", + "lottery_time_ts": time.time() + countdown, + "prize_value_yuan": prize_value_yuan, + "fudai_x": analyser._current_fudai_x or 540, + "reserved_at_ts": time.time() + } + # 写入 state/reservations.json + # ... + + return True # 通过筛选 +``` + +--- + +#### `douyin_fudai_core.attend_choujiang(analyser) -> bool` + +- **文件位置**: `douyin/fudai/core/fudai_attend.py` +- **作用**: 点击参与抽奖,根据按钮状态执行相应操作 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: `bool` - `True`=参与成功, `False`=参与失败 +- **调用位置**: `basic_join_decision()` 中调用(如果通过筛选) +- **主要逻辑**: + + 1. **识别按钮状态** + - **优先使用并行OCR结果(5秒内有效)** + - 检查 `analyser._fudai_button_text` 和 `analyser._fudai_button_status` + - 检查 `analyser._fudai_button_ocr_time` 是否在5秒内 + - 如果可用,直接使用,避免重复识别 + - **如果不可用,重新识别按钮** + - 裁剪按钮区域 (`analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮")`) + - 图像预处理 (`preprocess_for_ocr`) + - OCR识别(模式0和模式1,如果模式0识别失败) + + 2. **根据按钮状态执行操作**: + - **"已参与"** → 设置 `_waiting_for_lottery_result = True` + - 计算 `_lottery_result_expected_ts = 当前时间 + 倒计时秒数` + - 更新 `_last_successful_attend_ts = 当前时间` + - 返回 `True` + - **"需要加入粉丝团"** → 加入粉丝团 + - 点击粉丝团加入按钮 + - 如果失败且 `fansclub_fail_action="switch"` → 切换直播间 + - 如果 `fansclub_fail_action="stay"` → 停留等待 + - **"需要评论"** → 发送评论 + - 点击评论输入框 + - 输入评论内容(使用ADB键盘) + - 点击发送按钮 + - **"可以参与"** → 点击参与按钮 + - `analyser.operation.click(device_id, x, y)` + - 更新 `_last_successful_attend_ts = 当前时间` + - 返回 `True` + + 3. **最多重试2次** + - 如果第一次操作失败,重试一次 + - 如果两次都失败,返回 `False` + +**配置参数**: +- `auto_join_fansclub`: 是否自动加入粉丝团(bool,默认True) +- `fansclub_fail_action`: 加入粉丝团失败后的动作("switch"=切换直播间, "stay"=停留,默认"switch") + +**代码示例**: +```python +def attend_choujiang(analyser) -> bool: + click_times = 0 + while click_times < 2: + # 优先使用并行OCR结果 + attend_button_text = None + button_status = getattr(analyser, "_fudai_button_status", None) + button_text = getattr(analyser, "_fudai_button_text", "") + + if button_text and button_status: + button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0) + if time.time() - button_ocr_time < 5.0: + attend_button_text = button_text + + # 如果不可用,重新识别 + if not attend_button_text: + analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") + use_name = preprocess_for_ocr(analyser, "参与按钮") + attend_button_text = analyser.operation.analyse_pic_word(use_name, 0) + if not attend_button_text: + attend_button_text = analyser.operation.analyse_pic_word(use_name, 1) + + # 根据按钮状态执行操作 + if "参与成功" in attend_button_text or "已参与" in attend_button_text: + analyser._waiting_for_lottery_result = True + analyser._lottery_result_expected_ts = time.time() + countdown_seconds + analyser._last_successful_attend_ts = time.time() + return True + + elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text: + # 加入粉丝团 + if analyser.config.get("auto_join_fansclub", True): + if join_fansclub(analyser): + continue # 重试参与 + else: + if analyser.config.get("fansclub_fail_action") == "switch": + return False # 切换直播间 + + elif "评论" in attend_button_text: + # 发送评论 + send_comment(analyser) + continue # 重试参与 + + elif "参与抽奖" in attend_button_text or "参与" in attend_button_text: + # 点击参与按钮 + analyser.operation.click(analyser.device_id, 540, 2070) + analyser._last_successful_attend_ts = time.time() + return True + + click_times += 1 + + return False +``` + +--- + +### 4.6 预约相关函数 + +#### `douyin_reservation_logic.load_reservations_from_state(analyser) -> list` + +- **文件位置**: `douyin/reservation/douyin_reservation_logic.py` +- **作用**: 从状态文件加载预约数据 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: `list[dict]` - 预约列表 +- **调用位置**: `run_once_basic()` 中调用 +- **文件路径**: `state/reservations.json` (通过 `path_config.get_reservations_path()` 获取) +- **主要逻辑**: + + 1. 读取 `state/reservations.json` 文件 + 2. 解析JSON数据 + 3. 过滤已过期的预约(`lottery_time_ts < 当前时间`) + 4. 更新 `analyser.reservations` 属性 + 5. 返回预约列表 + +**预约数据格式**: +```json +[ + { + "room_title": "直播间标题", + "lottery_time_ts": 1234567890.0, + "prize_value_yuan": 500.0, + "fudai_x": 540, + "reserved_at_ts": 1234567890.0 + } +] +``` + +**代码示例**: +```python +def load_reservations_from_state(analyser) -> list: + import json + import path_config + + reservations_path = path_config.get_reservations_path() + if not os.path.exists(reservations_path): + return [] + + try: + with open(reservations_path, "r", encoding="utf-8") as f: + reservations = json.load(f) + + # 过滤已过期的预约 + current_time = time.time() + reservations = [ + r for r in reservations + if r.get("lottery_time_ts", 0) > current_time + ] + + # 更新 analyser 属性 + analyser.reservations = reservations + + return reservations + except Exception as e: + analyser._log_kv("错误", "加载预约数据失败", error=str(e)) + return [] +``` + +--- + +#### `douyin_reservation_logic.process_reservation_attend_window(analyser, ...) -> bool` + +- **文件位置**: `douyin/reservation/douyin_reservation_logic.py` +- **作用**: 处理预约回退窗口,检查是否需要回退到预约直播间 +- **参数**: + - `analyser: Any`: 分析器对象 + - `reservations: list`: 预约列表 + - `room_pos: int`: 当前直播间位置 + - `reservation_focus_until_ts_ref: List[float]`: 预约聚焦时间戳引用 + - `reservation_after_action_pending_ref: List[bool]`: 预约后动作待处理标志引用 + - `reservation_back_swipe_delay_s: float`: 回退滑动延迟(秒) + - `swipe_down_back_callback: Callable`: 下滑回退回调函数 + - `seek_reservation_room_callback: Callable`: 查找预约直播间回调函数 + - `sort_reservations_callback: Callable`: 排序预约回调函数 + - `write_state_callback: Callable`: 写入状态回调函数 +- **返回值**: `bool` - `True`=已触发回退, `False`=未触发 +- **调用位置**: `run_once_basic()` 和 `handle_no_fudai_situation()` 中调用 +- **主要逻辑**: + + 1. **检查预约队列是否已满** + - 如果预约数量 ≥ `high_value_fudai_max_reservations`,跳过处理 + + 2. **遍历预约列表,计算距离开奖时间** + - 对预约列表按开奖时间排序(`sort_reservations_callback`) + - 计算每个预约距离开奖时间:`remaining_seconds = lottery_time_ts - 当前时间` + + 3. **如果距离开奖时间 ≤ `high_value_fudai_join_ahead_seconds`,触发回退** + - 调用 `seek_reservation_room_callback` 查找目标直播间 + - 调用 `swipe_down_back_callback` 回退到目标直播间 + - 设置 `reservation_focus_until_ts = lottery_time_ts + 60`(聚焦到开奖后60秒) + - 设置 `reservation_back_direct_attend = True`(标记需要直接参与) + + 4. **验证是否在目标直播间(可选)** + - 如果启用 `reservation_back_verify_enabled`,验证是否在目标直播间 + - 通过OCR识别直播间标题,与预约的 `room_title` 比较 + +**配置参数**: +- `high_value_fudai_join_ahead_seconds`: 提前参与秒数(默认120) +- `high_value_fudai_max_reservations`: 最大预约数量(默认9999) +- `reservation_back_verify_enabled`: 是否启用回退验证(bool,默认True) +- `reservation_back_swipe_delay`: 回退滑动延迟(秒,默认0.1) + +**代码示例**: +```python +def process_reservation_attend_window( + analyser: Any, + reservations: list, + room_pos: int, + reservation_focus_until_ts_ref: List[float], + reservation_after_action_pending_ref: List[bool], + reservation_back_swipe_delay_s: float, + swipe_down_back_callback: Callable, + seek_reservation_room_callback: Callable, + sort_reservations_callback: Callable, + write_state_callback: Callable +) -> bool: + # 检查预约队列是否已满 + max_reservations = analyser.config.get("high_value_fudai_max_reservations", 9999) + if len(reservations) >= max_reservations: + return False + + # 排序预约列表 + sorted_reservations = sort_reservations_callback(reservations) + + # 遍历预约列表 + current_time = time.time() + ahead_seconds = analyser.config.get("high_value_fudai_join_ahead_seconds", 120) + + for item in sorted_reservations: + lottery_time_ts = item.get("lottery_time_ts", 0) + remaining_seconds = lottery_time_ts - current_time + + # 如果距离开奖时间 ≤ 提前参与秒数,触发回退 + if 0 < remaining_seconds <= ahead_seconds: + # 查找目标直播间 + if seek_reservation_room_callback(item): + # 回退到目标直播间 + swipe_down_back_callback() + time.sleep(reservation_back_swipe_delay_s) + + # 设置聚焦时间戳 + reservation_focus_until_ts_ref[0] = lottery_time_ts + 60 + + # 验证是否在目标直播间(可选) + if analyser.config.get("reservation_back_verify_enabled", True): + verify_reservation_room(analyser, item) + + return True + + return False +``` + +### 4.7 预约处理函数详解 + +#### 4.7.1 `ReservationHandler.find_room_pos_by_title(analyser, target_title: str, target_title_raw: str = "") -> Optional[int]` + +- **文件位置**: `douyin/reservation/douyin_reservation_handler.py` +- **作用**: 根据直播间标题在运行时映射表中查找对应的位置 +- **参数**: + - `analyser: Any`: 分析器对象 + - `target_title: str`: 目标标题(规范化后) + - `target_title_raw: str`: 目标原始标题 +- **返回值**: `Optional[int]` - 如果找到匹配的位置,返回位置值;否则返回 `None` +- **调用位置**: 预约回退时查找目标直播间 +- **实现细节**: + 1. **规范化标题**: 使用 `_normalize_room_title()` 规范化目标标题和记录的标题 + 2. **匹配算法**: + - **完全匹配**: 如果规范化后的标题完全相同,匹配分数 = 1.0 + - **子串匹配**: 如果一个是另一个的子串,匹配分数 = 0.8 + - **相似度匹配**: 使用 `difflib.SequenceMatcher` 计算相似度(0.0~1.0) + 3. **选择最佳匹配**: 选择匹配分数 >= 0.6 且最高的位置 + 4. **返回结果**: 如果找到匹配,返回位置值;否则返回 `None` + +**代码示例**: +```python +# 查找目标直播间位置 +target_pos = ReservationHandler.find_room_pos_by_title( + analyser, + target_title="直播间标题", + target_title_raw="直播间标题(原始)" +) +if target_pos is not None: + print(f"找到目标直播间,位置: {target_pos}") +else: + print("未找到目标直播间") +``` + +#### 4.7.2 `ReservationHandler.record_room_title_and_pos(analyser) -> None` + +- **文件位置**: `douyin/reservation/douyin_reservation_handler.py` +- **作用**: 记录当前直播间的标题和位置到运行时映射表 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: 无 +- **调用位置**: 进入直播间后调用 +- **实现细节**: + 1. **获取当前直播间位置**: `room_pos = analyser.room_pos` + 2. **读取直播间标题**: 调用 `read_live_room_title_core()` 获取标题(规范化和原始) + 3. **更新映射表**: 将 `(room_title, room_title_raw)` 存储到 `analyser._room_pos_to_title_map[room_pos]` + 4. **更新分析器属性**: 更新 `analyser.current_room_title` 和 `analyser.current_room_title_raw` + +**代码示例**: +```python +# 记录当前直播间标题和位置 +ReservationHandler.record_room_title_and_pos(analyser) +# 映射表现在包含: {room_pos: (room_title, room_title_raw)} +``` + +#### 4.7.3 `ReservationHandler.seek_reservation_room(analyser, item: Dict[str, Any]) -> bool` + +- **文件位置**: `douyin/reservation/douyin_reservation_handler.py` +- **作用**: 根据预约记录里的 `pos_seen` 与当前 `room_pos` 进行回退,靠近目标直播间 +- **参数**: + - `analyser: Any`: 分析器对象 + - `item: Dict[str, Any]`: 预约记录字典 +- **返回值**: `bool` - 是否成功回退到目标直播间 +- **调用位置**: 预约回退时调用 +- **实现细节**: + 1. **计算位置差**: `pos_diff = target_pos - cur_pos` + 2. **判断方向**: + - **`pos_diff < 0`**: 目标在上方,需要向上回退(减少 `room_pos`) + - **`pos_diff > 0`**: 目标在下方,需要向下切换(增加 `room_pos`) + - **`pos_diff == 0`**: 已在目标位置,跳过回退 + 3. **计算回退次数**: + - 向上回退: `back_times = min(abs(pos_diff), max_back)` + - 向下切换: `forward_times = min(pos_diff, max_back)` + 4. **执行回退**: + - 向上回退: 调用 `swipe_down_back_from_live()` N次 + - 向下切换: 调用 `swipe_up_to_next_live()` N次 + - 每次滑动后延迟 `reservation_back_swipe_delay` 秒 + 5. **设置标志**: 回退过程中设置 `_skip_record_title_during_seek = True`,避免重复记录标题 + 6. **返回结果**: 回退完成后返回 `True`(校验将在 `process_reservation_attend_window` 中统一进行) + +**配置参数**: +- `high_value_fudai_max_swipe_back`: 最大回退次数(默认60,最大100) +- `reservation_back_swipe_delay`: 回退滑动延迟(秒,默认0.3) + +**代码示例**: +```python +# 回退到目标直播间 +item = { + "pos_seen": 5, # 目标位置 + "room_title": "目标直播间", + "lottery_time_ts": 1704067200.0 +} +success = ReservationHandler.seek_reservation_room(analyser, item) +if success: + print("成功回退到目标直播间") +``` + +#### 4.7.4 `ReservationHandler.handle_reservation_direct_attend(analyser) -> None` + +- **文件位置**: `douyin/reservation/douyin_reservation_handler.py` +- **作用**: 预约回退后直接参与,跳过OCR识别,使用按钮检测进行决策 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: 无 +- **调用位置**: `run_once_basic()` 中检查到 `_reservation_back_direct_attend = True` 时调用 +- **主要流程**: + 1. **检查预约队列**: 如果预约队列为空,回退到正常流程(调用 `_handle_in_fudai_detail()`) + 2. **检查福袋是否过期**: + - 获取预约的 `future_ts`(开奖时间戳,从 `first_reservation.get("future_ts")` 获取) + - 计算过期阈值: `expired_threshold = future_ts + poll_before_seconds` + - 如果当前时间 > 过期阈值,清除标志并退出 + - 调用 `cleanup_expired_reservations()` 从预约队列中移除过期预约 + 3. **步骤1: 直接查找福袋图标并点击** + - 调用 `find_and_open_fudai_detail()` 查找并打开福袋详情 + - 如果未找到,回退到正常流程(调用 `_handle_in_fudai_detail()`) + - 等待详情页加载(0.5秒,减少延迟) + 4. **步骤2: 调用按钮检测进行决策** + - 获取截图(`operation.get_screenshot()`) + - 读取截图文件(`path_config.get_screenshot_path()`) + - 调用 `detect_attend_button_red_area()` 检测参与按钮(返回 `(has_button, button_info)` 元组) + - 如果未检测到按钮,回退到正常流程 + 5. **步骤3: 点击参与按钮** + - 计算参与按钮坐标(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) + - 根据设备分辨率缩放坐标: `attend_x = int(543 * rx / 1080)`, `attend_y = int(2070 * ry / 2400)` + - 点击参与按钮(`operation.click(device_id, attend_x, attend_y)`) + - 等待点击后的响应(0.8秒,减少延迟) + 6. **步骤4: 点击福袋图标验证参与状态**(详细验证逻辑) + - **再次查找并点击福袋图标**: + - 调用 `find_and_open_fudai_detail()` 再次查找福袋图标 + - 如果未找到,可能已参与成功(记录日志,继续执行) + - **如果找到福袋图标**: + - 等待详情页加载(0.5秒) + - 获取截图并检测按钮状态 + - 调用 `detect_attend_button_red_area()` 再次检测参与按钮 + - 如果仍检测到按钮,可能参与失败,回退到正常流程 + - 如果未检测到按钮,说明参与成功 + 7. **步骤5: 参与成功,设置开奖等待状态并从预约队列中移除** + - **设置开奖等待状态**: + - 计算剩余秒数: `remain_seconds = max(0, future_ts - current_time)` + - 如果 `remain_seconds > 0`,设置 `_waiting_for_lottery_result = True` + - 设置 `_lottery_result_expected_ts = future_ts - 13.0`(提前13秒检查开奖结果) + - **设置锁定期**: + - 计算锁定期: `reservation_focus_until_ts = future_ts + max(0.0, poll_before)` + - 防止过早切换直播间 + - **从预约队列中移除已参与的预约**: + - 遍历预约队列,匹配 `future_ts`(允许5秒误差: `abs(res_future_ts - future_ts) <= 5.0`) + - 移除匹配的预约,保留不匹配的预约 + - 记录移除日志 + - **清除标志**: + - 清除 `_reservation_back_direct_attend = False` + - 清除 `reservation_after_action_pending = False` + +**配置参数**: +- `high_value_fudai_poll_before_seconds`: 开奖前轮询时间(秒,默认10.0) + +**关键实现细节**: +- **参与按钮坐标**: 基于OCR区域中心点计算,坐标为 (543, 2070)(基准分辨率1080x2400) +- **验证机制**: 通过再次检测按钮状态验证参与是否成功 +- **预约匹配**: 通过 `future_ts` 匹配预约(允许5秒误差),确保准确移除已参与的预约 +- **错误处理**: 所有步骤都有异常处理,出错时回退到正常流程(`_handle_in_fudai_detail()`) + +**代码示例**: +```python +# 预约回退后直接参与 +if analyser._reservation_back_direct_attend: + ReservationHandler.handle_reservation_direct_attend(analyser) + analyser._reservation_back_direct_attend = False + return +``` + +#### 4.7.5 预约验证机制 + +预约回退后需要进行验证,确保在正确的直播间。验证机制包括: + +1. **标题匹配验证**: + - 使用 `find_room_pos_by_title()` 查找目标直播间位置 + - 如果找到匹配的位置,验证成功 + +2. **位置验证**: + - 检查当前 `room_pos` 是否等于目标 `pos_seen` + - 如果相等,验证成功 + +3. **福袋详情验证**(可选): + - 打开福袋详情页 + - 验证福袋价值是否匹配 + - 验证倒计时是否合理 + +**验证失败处理**: +- 如果验证失败,记录警告日志 +- 继续执行流程(不中断) +- 如果多次验证失败,可能需要重新查找目标直播间 + +#### 4.7.6 `douyin_reservation_verify.match_reservation(item, detail) -> Tuple[bool, str, Dict]` + +- **文件位置**: `douyin/reservation/douyin_reservation_verify.py` +- **作用**: 校验回退后的福袋详情是否匹配预约记录 +- **参数**: + - `item: Dict[str, Any]`: 预约项字典,包含 `prize_value_yuan`, `future_ts`, `content` 等 + - `detail: Tuple`: 福袋详情元组 `(content, time_text, participants, copies, prize_value_yuan, countdown_tuple)` +- **返回值**: `(is_match, reason, debug_dict)` - 是否匹配、原因、调试信息 +- **调用位置**: 预约回退验证时调用 +- **主要逻辑**: + 1. **提取预约和实际福袋信息**: + - 从预约项提取: `expected_value`, `expected_future`, `expected_content` + - 从详情元组提取: `actual_value`, `actual_future`, `actual_content` + 2. **检查是否为"观看X分钟"类任务**: + - 使用正则表达式检测: `(?:观看|看)(?:直播)?\s*(?:\d+|[\u4e00-\u9fff]+)\s*分钟` + - 如果是观看任务,返回 `(False, "watch_task_detected", ...)` + 3. **验证 future_ts**: + - 如果 `expected_future <= 0` 或 `actual_future <= 0`,返回 `(False, "future_missing", ...)` + 4. **价值或内容匹配**(二选一命中即可): + - **价值匹配**: `abs(expected_value - actual_value) <= max(50.0, expected_value * 0.25)` + - **内容匹配**: `expected_content in actual_content` 或 `actual_content in expected_content` + - 如果价值或内容都不匹配,返回 `(False, "content_or_value_mismatch", ...)` + 5. **future_ts 精确匹配**: + - 计算 `future_diff = abs(expected_future - actual_future)` + - 如果 `future_diff <= 180`,返回 `(True, "ok", ...)` + - 如果 `future_diff > 180` 但 `future_diff <= 1200` 且价值+内容都匹配,返回 `(True, "future_mismatch_relaxed", ...)` + - 否则返回 `(False, "future_mismatch", ...)` + +**代码示例**: +```python +item = { + "prize_value_yuan": 500.0, + "future_ts": 1704067200.0, + "content": "测试福袋" +} +detail = ("测试福袋", "01:30", 100, 10, 500.0, (1704067000.0, 1704067200.0)) +is_match, reason, debug = match_reservation(item, detail) +``` + +#### 4.7.7 `douyin_reservation_verify.validate_back_to_reservation(analyser, item, quick=False, max_checks=3) -> Tuple[bool, Optional[Tuple]]` + +- **文件位置**: `douyin/reservation/douyin_reservation_verify.py` +- **作用**: 回退后校验直播间标题,确保在正确的直播间 +- **参数**: + - `analyser: Any`: 分析器对象 + - `item: Dict[str, Any]`: 预约项字典 + - `quick: bool`: 是否快速模式(减少检查次数) + - `max_checks: int`: 最大检查次数(未使用,保留兼容性) +- **返回值**: `(is_valid, None)` - 如果校验通过返回 `True`,否则返回 `False` +- **调用位置**: 预约回退后验证时调用 +- **主要逻辑**: + 1. **检查是否启用验证**: + - 如果 `reservation_back_verify_enabled = False`,直接返回 `True` + 2. **规范化预期标题**: + - 使用 `_normalize_room_title()` 规范化预约的 `room_title` + - 去除空格、特殊字符、无关词("点赞"、"关注"等) + 3. **运行时映射表验证**: + - 从 `_room_pos_to_title_map` 获取目标位置的记录标题 + - 如果映射表中的标题与预期标题匹配,增强验证信心 + 4. **读取当前直播间标题**: + - 调用 `read_live_room_title_core()` 读取当前直播间标题 + - 计算相似度: `difflib.SequenceMatcher(None, expected_title, current_title).ratio()` + 5. **标题匹配判断**: + - 如果 `expected_title in current_title` 或 `current_title in expected_title` 或 `ratio >= 0.45`,验证通过 + - 如果标题不匹配(`ratio < 0.45`),尝试根据映射表找到正确位置并回退 + 6. **自动回退到正确位置**: + - 调用 `_find_room_pos_by_title()` 在映射表中查找正确位置 + - 如果找到,更新 `item["pos_seen"]` 并调用 `_seek_reservation_room()` 回退 + - 重新读取标题验证,如果匹配则返回 `True` + +**配置参数**: +- `reservation_back_verify_enabled`: 是否启用回退验证(bool,默认True) + +--- + +## 5. 底层操作函数 + +底层操作函数封装在 `Underlying_Operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。 + +### 5.1 设备操作函数 + +#### `underlying_operations.select_device() -> str | bool` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 选择需要连接的Android设备 +- **参数**: 无 +- **返回值**: + - `str`: 设备ID(单设备或多设备选择后) + - `False`: 无设备连接 +- **调用位置**: `run_cli.py` 的 `main()` 函数中调用 +- **实现细节**: + - 执行 `adb devices` 命令获取设备列表 + - 使用正则表达式提取设备ID(支持IP地址和序列号) + - 单设备:直接返回设备ID + - 多设备:显示设备列表,用户选择后返回 + - 无设备:返回 `False` 并提示检查连接 + +**代码示例**: +```python +operation = underlying_operations() +device_id = operation.select_device() +if not device_id: + print("未检测到设备") + return +``` + +#### `underlying_operations.get_device_resolution(device_id: str) -> Tuple[int, int]` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 获取Android设备的分辨率 +- **参数**: + - `device_id: str`: 设备ID +- **返回值**: `Tuple[int, int]` - (宽度, 高度) +- **调用位置**: `fudai_analyse.__init__()` 中调用,用于初始化分辨率 +- **实现细节**: + - 执行 `adb shell wm size` 命令 + - 使用正则表达式提取物理分辨率(格式:`Physical size: WIDTHxHEIGHT`) + - 返回宽度和高度 + +**代码示例**: +```python +width, height = operation.get_device_resolution(device_id) +analyser.resolution_ratio_x = width +analyser.resolution_ratio_y = height +``` + +#### `underlying_operations.click(device_id: str, x: int, y: int) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 在设备屏幕上点击指定坐标 +- **参数**: + - `device_id: str`: 设备ID + - `x: int`: X坐标 + - `y: int`: Y坐标 +- **返回值**: 无 +- **调用位置**: 所有需要点击的地方(福袋图标、参与按钮、返回键等) +- **实现细节**: + - 执行 `adb shell input tap x y` 命令 + - 支持坐标缩放(根据设备分辨率自动调整) + +**代码示例**: +```python +operation.click(device_id, 540, 1200) # 点击屏幕中心 +``` + +#### `underlying_operations.click_back(device_id: str) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 点击Android返回键(KEYCODE_BACK) +- **参数**: + - `device_id: str`: 设备ID +- **返回值**: 无 +- **调用位置**: 返回操作、退出详情页等场景 +- **实现细节**: + - 执行 `adb shell input keyevent 4` 命令(4 = KEYCODE_BACK) + +#### `underlying_operations.click_confirm(device_id: str) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 点击确认键(KEYCODE_ENTER) +- **参数**: + - `device_id: str`: 设备ID +- **返回值**: 无 +- **调用位置**: 确认操作场景 +- **实现细节**: + - 执行 `adb shell input keyevent 66` 命令(66 = KEYCODE_ENTER) + +### 5.2 截图操作函数 + +#### `underlying_operations.get_screenshot(device_id: str, path: str = "pic") -> bool` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 获取设备屏幕截图并保存到本地 +- **参数**: + - `device_id: str`: 设备ID + - `path: str`: 保存路径(默认"pic") +- **返回值**: `bool` - 成功返回 `True`,失败返回 `False` +- **调用位置**: 所有需要截图的地方(阶段诊断、OCR识别、像素检测等) +- **实现细节**: + - **优先方法**: 使用 `adb exec-out screencap -p` 直接输出到文件(只需1次adb调用,不在手机端落盘) + - **回退方法1**: 使用 `adb shell screencap -p /sdcard/DCIM/screenshot.png` + `adb pull`(2次adb调用) + - **回退方法2**: 使用 `screenshot1.png` 覆盖 `screenshot.png` + - **文件安全**: 先写入临时文件(`screenshot.png.tmp`),再原子替换,避免并发读取到半写入文件 + - **Windows兼容**: 使用 `_safe_replace_file()` 处理Windows文件锁定问题 + - **镜像功能**: 自动镜像截图到外部工作树(如果配置了 `EXTERNAL_DOUYIN_FUDAI_DIR`) + - **文件验证**: 检查文件大小(至少1KB),避免0字节/损坏文件 + +**代码示例**: +```python +if operation.get_screenshot(device_id): + # 截图成功,继续处理 + pass +else: + # 截图失败,记录错误 + logger.error("截图失败") +``` + +#### `underlying_operations.save_reward_pic(device_id: str) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 保存中奖截图(带时间戳) +- **参数**: + - `device_id: str`: 设备ID +- **返回值**: 无 +- **调用位置**: `fudai_result_checker.get_reward()` 中调用 +- **实现细节**: + - 生成带时间戳的文件名(格式:`YYYY-MM-DD-HH-MM-SS.png`) + - 优先使用 `exec-out` 方法,失败则回退到 `shell screencap + pull` + - 保存失败不打断主流程(仅打印警告) + +### 5.3 图像处理函数 + +#### `underlying_operations.cut_pic(left_up: Tuple[int, int] = (0, 63), right_down: Tuple[int, int] = (1080, 1620), target: str = "", name: str = "") -> bool` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 裁剪图片,获取指定区域的子图片(用于OCR识别) +- **参数**: + - `left_up: Tuple[int, int]`: 左上角坐标(默认(0, 63)) + - `right_down: Tuple[int, int]`: 右下角坐标(默认(1080, 1620)) + - `target: str`: 目标目录(空字符串表示使用默认路径) + - `name: str`: 裁剪后的图片名称(不含扩展名,空字符串表示使用"cut") +- **返回值**: `bool` - 成功返回 `True`,失败返回 `False` +- **调用位置**: 所有需要OCR识别的地方(福袋内容、倒计时、价值、参与人数等) +- **实现细节**: + - **重试机制**: 最多重试3次,每次延迟递增(0.1s, 0.2s, 0.3s) + - **文件验证**: 检查源文件是否存在、文件大小(至少100字节)、图片完整性 + - **坐标验证**: 验证裁剪坐标有效性(不能超出图片范围,left < right, top < bottom) + - **路径管理**: 使用 `_find_pic_path()` 查找/创建图片路径(支持分类目录) + - **坐标缓存**: 存储裁剪坐标到 `_ocr_coords_cache`,供OCR使用 + - **调试图像**: 自动保存调试图像(完整截图+区域标注) + - **错误处理**: 捕获所有异常,最后一次尝试失败则返回 `False` 并记录错误 + +**代码示例**: +```python +# 裁剪福袋内容区域 +if operation.cut_pic( + left_up=(100, 200), + right_down=(980, 400), + name="福袋内容" +): + # 裁剪成功,继续OCR识别 + text = operation.analyse_pic_word("福袋内容") +else: + # 裁剪失败 + logger.error("裁剪福袋内容区域失败") +``` + +### 5.4 OCR识别函数 + +#### `underlying_operations.analyse_pic_word(picname: str, change_color: int = 0, pic_path: Optional[str] = None) -> str` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 对指定图片运行OCR识别,返回拼接后的文本结果 +- **参数**: + - `picname: str`: 图片名称(不含扩展名,如"福袋内容") + - `change_color: int`: 颜色转换模式(0=不转换,1=转换为黑白,2=其他) + - `pic_path: Optional[str]`: 图片路径(可选,默认使用 `_find_pic_path()` 查找) +- **返回值**: `str` - OCR识别结果(所有文本行拼接后的字符串) +- **调用位置**: 所有需要OCR识别的地方(福袋内容、倒计时、价值、参与人数、按钮文本等) +- **实现细节**: + - **OCR引擎**: 优先使用EasyOCR,失败则回退到PaddleOCR + - **延迟初始化**: OCR引擎在首次使用时初始化(`_ensure_ocr()`) + - **图片加载**: 使用PIL加载图片,支持多种格式(PNG、JPEG等) + - **颜色转换**: 根据 `change_color` 参数进行颜色转换(提高识别率) + - **文本提取**: 使用 `extract_ocr_content()` 提取文本(去除置信度信息) + - **坐标缓存**: 如果存在坐标缓存,传递给OCR引擎(提高识别精度) + - **错误处理**: 捕获所有异常,返回空字符串并记录错误 + +**代码示例**: +```python +# 识别福袋内容 +content = operation.analyse_pic_word("福袋内容") +if content: + print(f"福袋内容: {content}") +else: + print("OCR识别失败") +``` + +#### `underlying_operations.analyse_pic_digits(picname: str, change_color: int = 1, pic_path: Optional[str] = None) -> str` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 对指定图片运行OCR识别,专门用于识别数字(倒计时、价值、参与人数等) +- **参数**: + - `picname: str`: 图片名称(不含扩展名,如"倒计时") + - `change_color: int`: 颜色转换模式(默认1=转换为黑白,提高数字识别率) + - `pic_path: Optional[str]`: 图片路径(可选) +- **返回值**: `str` - OCR识别结果(数字字符串) +- **调用位置**: 识别倒计时、价值、参与人数等数字信息 +- **实现细节**: + - 与 `analyse_pic_word()` 类似,但默认使用黑白转换(`change_color=1`) + - 专门优化数字识别(去除非数字字符,保留数字、小数点、冒号等) + +**代码示例**: +```python +# 识别倒计时 +countdown_text = operation.analyse_pic_digits("倒计时") +# 可能返回: "05:30" 或 "5:30" +``` + +#### `underlying_operations.extract_ocr_content(content: List, return_confidence: bool = False) -> str | Tuple[str, float]` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 从OCR结果中提取文本内容(去除坐标、置信度等信息) +- **参数**: + - `content: List`: OCR原始结果(EasyOCR或PaddleOCR格式) + - `return_confidence: bool`: 是否返回平均置信度(默认 `False`) +- **返回值**: + - `str`: 提取的文本(如果 `return_confidence=False`) + - `Tuple[str, float]`: (文本, 平均置信度)(如果 `return_confidence=True`) +- **调用位置**: `analyse_pic_word()` 和 `analyse_pic_digits()` 内部调用 +- **实现细节**: + - **EasyOCR格式**: `[[[坐标], 文本, 置信度], ...]` → 提取文本和置信度 + - **PaddleOCR格式**: `[[[坐标], [文本, 置信度]], ...]` → 提取文本和置信度 + - **文本拼接**: 将所有文本行用空格拼接 + - **置信度计算**: 计算所有文本的平均置信度(如果 `return_confidence=True`) + +### 5.5 滑动操作函数 + +#### `underlying_operations.swipe(device_id: str, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 600) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 在设备屏幕上执行滑动操作(从起点滑动到终点) +- **参数**: + - `device_id: str`: 设备ID + - `x1: int`: 起点X坐标 + - `y1: int`: 起点Y坐标 + - `x2: int`: 终点X坐标 + - `y2: int`: 终点Y坐标 + - `duration_ms: int`: 滑动持续时间(毫秒,默认600ms) +- **返回值**: 无 +- **调用位置**: 所有需要滑动的地方(切换直播间、返回推荐页、滑动列表等) +- **实现细节**: + - **优先方法**: 使用 `adb shell input swipe x1 y1 x2 y2 duration_ms`(最简单,兼容性好) + - **回退方法1**: 使用 `sendevent` 模拟触摸事件(更精确,但需要root权限) + - **回退方法2**: 使用 `uiautomator`(Android 4.3+) + - **回退方法3**: 使用改进的 `sendevent`(支持非root设备) + - **坐标缩放**: 根据设备分辨率自动调整坐标 + +**代码示例**: +```python +# 向上滑动(切换直播间) +operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600) +``` + +### 5.6 工具函数 + +#### `underlying_operations.delay(seconds: float = 1.0) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 延迟指定秒数 +- **参数**: + - `seconds: float`: 延迟秒数(默认1.0秒) +- **返回值**: 无 +- **调用位置**: 所有需要等待的地方(页面加载、操作后等待等) + +#### `underlying_operations.random_delay(min_seconds: float = 1.0, max_seconds: float = 100.0) -> None` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 随机延迟指定范围内的秒数(模拟人工操作) +- **参数**: + - `min_seconds: float`: 最小延迟秒数(默认1.0秒) + - `max_seconds: float`: 最大延迟秒数(默认100.0秒) +- **返回值**: 无 +- **调用位置**: 需要模拟人工操作的场景 + +#### `underlying_operations.check_countdown(last_time: str = "") -> Optional[int]` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 检查倒计时文本,转换为剩余秒数 +- **参数**: + - `last_time: str`: 倒计时文本(格式:`mm:ss` 或 `m:ss` 或 `ss`) +- **返回值**: `Optional[int]` - 剩余秒数,解析失败返回 `None` +- **调用位置**: `douyin_fudai_core.ocr_countdown_mm()` 和 `ocr_countdown_ss()` 中调用 +- **实现细节**: + - 支持多种格式:`mm:ss`、`m:ss`、`ss`、`m分s秒` 等 + - 使用正则表达式提取分钟和秒数 + - 计算总秒数 = 分钟 × 60 + 秒数 + +**代码示例**: +```python +countdown_text = "05:30" +remaining_seconds = operation.check_countdown(countdown_text) +# 返回: 330 (5分30秒 = 330秒) +``` + +#### `underlying_operations.get_current_hour() -> int` + +- **文件位置**: `Underlying_Operations.py` +- **作用**: 获取当前时间的小时数(0-23) +- **参数**: 无 +- **返回值**: `int` - 当前小时数(0-23) +- **调用位置**: 静音时段检查等场景 + +--- + +## 6. 核心类和数据结构详解 + +### 6.1 核心类:`fudai_analyse` + +`fudai_analyse` 是项目的核心调度类,采用**Mixin模式**组合多个功能模块。 + +#### 类定义 + +```python +class fudai_analyse( + NavigationMixin, # 导航功能 + StageDetectionMixin, # 阶段检测 + PopupHandlerMixin, # 弹窗处理 + LotteryResultMixin, # 抽奖结果 + RoomUtilsMixin, # 直播间工具 + MainLogicMixin, # 主逻辑 +): + """福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。""" +``` + +#### 核心属性 + +##### 设备与分辨率 + +- `device_id: str` - 设备ID(需要在运行时设置) +- `y_pianyi: int` - Y轴偏移量(用于坐标调整) +- `resolution_ratio_x: int` - 屏幕宽度(默认1080) +- `resolution_ratio_y: int` - 屏幕高度(默认2400) + +##### 运行配置 + +- `operation: underlying_operations` - 底层操作对象 +- `config_path: str` - 配置文件路径 +- `config: dict` - 配置字典(从 `config.json` 加载) + +##### 日志相关 + +- `_run_id: str` - 运行ID(格式:`YYYYMMDDHHMMSS`) +- `_log_seq: int` - 日志序列号 +- `_log_kv: Callable` - 日志记录函数(增强版本) +- `_last_log_tag: str` - 上一个日志标签(用于检测阶段变化) +- `_std_logger: logging.Logger` - 标准日志器 + +##### 状态管理 + +- `_swipe_times: int` - 滑动次数计数器(用于滑动次数重置功能) +- `_last_diag_stage: str` - 上次诊断的阶段(如"IN_LIVE_ROOM") +- `_last_diag_seen: str` - 上次诊断看到的标识(如直播间标题) +- `_last_diag_ts: float` - 上次诊断的时间戳 +- `_last_successful_attend_ts: float` - 最后一次成功参与福袋的时间戳(用于30分钟超时检查) +- `_no_attend_timeout_minutes: float` - 无参与超时时间(默认30分钟) +- `_run_start_ts: float` - 运行开始时间戳 +- `last_fudai_x: int` - 上次检测到的福袋图标X坐标(用于优化搜索) + +##### 福袋筛选配置 + +- `contains_not_want: List[str]` - 不想要的福袋内容关键词列表 +- `contains_want: List[str]` - 想要的福袋内容关键词列表 +- `min_prize_value_yuan: float` - 最小奖品价值(元) +- `min_participants: int` - 最小参与人数 +- `max_participants: int` - 最大参与人数 +- `skip_if_countdown_gt_seconds: int` - 倒计时大于该秒数则跳过(默认900秒) +- `skip_if_countdown_lt_seconds: int` - 倒计时小于该秒数则不参与(默认0秒) + +##### 福袋查找配置 + +- `fudai_icon_retry_delay_seconds: float` - 福袋图标重试延迟(默认0.6秒) +- `fudai_icon_max_wait_seconds: float` - 福袋图标最大等待时间(默认5.0秒) +- `fudai_click_wait_seconds: float` - 点击福袋图标后等待详情页加载的时间(默认2.0秒) +- `fudai_finder_optimized_enabled: bool` - 是否启用优化查找器(默认 `True`) +- `fudai_click_verify_enabled: bool` - 点击后是否验证成功打开详情页(默认 `True`) +- `fudai_find_max_retries: int` - 最大重试次数(默认3次) + +##### 其他配置 + +- `switch_room_wait_after_stage_diag_seconds: float` - 切换直播间后等待阶段诊断的时间(默认7.0秒) +- `swipe_duration_ms: int` - 滑动持续时间(毫秒,默认600ms) +- `screenshot_diagnose_min_interval_seconds: float` - 截图诊断最小间隔(默认8.0秒) +- `no_fudai_watchdog_enabled: bool` - 是否启用无福袋看门狗(默认 `False`) + +##### 预约相关 + +- `_forced_reservation_detail: Optional[dict]` - 强制预约详情(用于测试) +- `_forced_reservation_fudai_x: Optional[int]` - 强制预约福袋X坐标(用于测试) + +##### 等待开奖相关 + +- `_waiting_for_lottery_result: bool` - 是否正在等待开奖结果 +- `_lottery_result_room_pos: Optional[dict]` - 等待开奖的直播间位置信息 + +#### 核心方法 + +##### 初始化方法 + +- `__init__() -> None` - 初始化所有属性,加载配置,初始化日志系统 + +##### 主流程方法 + +- `fudai_choujiang() -> None` - 主循环入口(无限循环或单次运行) +- `run_once_basic() -> bool` - 单次循环执行(返回 `True` 表示继续,`False` 表示退出) + +##### 配置加载 + +- `load_config() -> None` - 从 `config.json` 加载配置并更新属性 + +##### 阶段诊断 + +- `_diagnose_stage_from_current_screen() -> str` - 阶段诊断入口(调用 `douyin_stage.diagnose_stage_from_current_screen()`) + +##### 后台任务 + +- `background_tick() -> None` - 后台tick函数(在等待循环期间执行轻量后台任务,如处理弹窗) + +### 6.2 Mixin类详细说明 + +#### 6.2.1 NavigationMixin(导航功能混入类) + +**文件位置**: `douyin/core/fudai_modules/fudai_navigation.py` + +**职责**: 提供导航、点击、滑动等基础交互功能 + +**主要方法**: + +1. **`click(x: int, y: int) -> None`** + - **作用**: 点击指定坐标(兼容原版接口) + - **参数**: + - `x: int` - X坐标 + - `y: int` - Y坐标 + - **实现**: 转发到底层 `operation.click()` + - **调用位置**: 所有需要点击的地方 + +2. **`load_config() -> None`** + - **作用**: 从 `config.json` 加载配置 + - **实现**: 调用 `douyin_config.ConfigManager.load_config_from_file()` + - **调用位置**: `fudai_analyse.__init__()` 中调用 + +3. **`cut_pic(x1: int, y1: int, x2: int, y2: int, name: str = "", desc: str = "", y_pianyi: int = 0) -> None`** + - **作用**: 截取指定区域的图片(兼容原版接口) + - **参数**: + - `x1, y1: int` - 左上角坐标 + - `x2, y2: int` - 右下角坐标 + - `name: str` - 图片名称(不含扩展名) + - `desc: str` - 描述信息 + - `y_pianyi: int` - Y轴偏移量 + - **实现**: 调用 `douyin_screenshot_handler.ScreenshotHandler.cut_pic()` + - **调用位置**: OCR识别前裁剪图片区域 + +4. **`_scale_from_base(base_x: int, base_y: int) -> tuple[int, int]`** + - **作用**: 根据当前设备分辨率,从基准分辨率(1080x2400)缩放到实际分辨率 + - **参数**: + - `base_x, base_y: int` - 基准坐标(基于1080x2400) + - **返回值**: `(scaled_x, scaled_y)` - 缩放后的坐标 + - **调用位置**: 所有需要坐标缩放的地方 + +5. **`_save_step_screenshot(label: str) -> None`** + - **作用**: 保存步骤截图用于调试(带时间戳) + - **参数**: `label: str` - 步骤标签 + - **调用位置**: 关键步骤执行后保存调试截图 + +6. **`swipe_up_to_next_live() -> None`** + - **作用**: 上滑切换直播间 + - **注意**: 如果处于预约锁定期内,则不允许上划离开预约直播间 + - **实现**: 调用 `douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live()` + - **调用位置**: 切换直播间时调用 + +7. **`_return_to_recommend_and_reenter_live() -> None`** + - **作用**: 返回推荐页面并重新进入直播间 + - **实现**: 通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间 + - **调用位置**: 30分钟超时、滑动次数重置等场景 + +8. **`swipe_down_back_from_live() -> None`** + - **作用**: 上划回退到上一个直播间(供预约/无福袋逻辑使用) + - **实现**: 调用 `douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live()` + - **调用位置**: 预约回退、无福袋回退等场景 + +9. **`_maybe_reset_after_swipes() -> int`** + - **作用**: 达到切换阈值后,在当前直播间页面回退到第一个直播间 + - **返回值**: `int` - 重置后的滑动次数(通常为0) + - **实现**: 调用 `douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes()` + - **调用位置**: 滑动次数达到阈值时调用 + +#### 6.2.2 StageDetectionMixin(阶段检测混入类) + +**文件位置**: `douyin/core/fudai_modules/fudai_stage_detection.py` + +**职责**: 提供屏幕阶段诊断、像素状态检测等功能 + +**主要方法**: + +1. **`_diagnose_stage_from_current_screen() -> Tuple[str, str]`** + - **作用**: 封装到子模块的阶段诊断入口 + - **返回值**: `(stage, seen)` - (阶段字符串, 看到的标识) + - **实现**: 调用 `douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen()` + - **调用位置**: `run_once_basic()` 中调用 + +2. **`_read_pixel_stage_state(return_details: bool = False) -> dict | tuple[dict, dict]`** + - **作用**: 读取像素阶段状态(用于阶段诊断) + - **参数**: + - `return_details: bool` - 是否返回每个检测步骤的详细信息(包括分数) + - **返回值**: + - `dict` - 检测结果(`return_details=False`时) + - `tuple[dict, dict]` - (检测结果, 详细信息)(`return_details=True`时) + - **实现**: 调用 `douyin_helpers.HelperFunctions.read_pixel_stage_state()` + - **调用位置**: 阶段诊断时调用 + +3. **`_check_in_live_room_by_icon() -> Tuple[bool, float]`** + - **作用**: 通过模板匹配检测是否在直播间 + - **返回值**: `(is_in_live_room, confidence)` - (是否在直播间, 置信度) + - **实现**: 使用OpenCV模板匹配检测直播间图标 + - **调用位置**: 阶段诊断时调用 + +#### 6.2.3 PopupHandlerMixin(弹窗处理混入类) + +**文件位置**: `douyin/core/fudai_modules/fudai_popup_handler.py` + +**职责**: 提供各种弹窗的检测和处理功能 + +**主要方法**: + +1. **`_check_coupon_popup() -> bool`** + - **作用**: 检测购物券/新客专享券等底部营销弹窗 + - **返回值**: `bool` - 是否检测到弹窗 + - **注意**: 仅在详情链路外的"看门狗"中使用 + - **实现**: 调用 `douyin_popup_handler.PopupHandler.check_coupon_popup()` + - **调用位置**: 后台tick函数中调用 + +2. **`_check_shopping_redpacket_popup() -> bool`** + - **作用**: 检测购物红包中央弹窗 + - **返回值**: `bool` - 是否检测到弹窗 + - **实现**: 调用 `douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup()` + - **调用位置**: 后台tick函数中调用 + +3. **`_shot_and_diagnose(operation_type: str, description: str, device_id: str | None = None, force_screenshot: bool = False) -> None`** + - **作用**: 统一截图并诊断方法 + - **参数**: + - `operation_type: str` - 操作类型(如"开奖诊断"、"详情识别"等) + - `description: str` - 操作描述 + - `device_id: str | None` - 设备ID,如果为None则使用self.device_id + - `force_screenshot: bool` - 是否强制截图(忽略缓存) + - **实现**: 调用 `douyin_helpers.HelperFunctions.shot_and_diagnose()` + - **调用位置**: 需要截图并诊断的场景 + +#### 6.2.4 LotteryResultMixin(抽奖结果混入类) + +**文件位置**: `douyin/core/fudai_modules/fudai_lottery_result.py` + +**职责**: 提供开奖结果的OCR识别和处理功能 + +**主要方法**: + +1. **`_check_lottery_result_by_ocr() -> Optional[str]`** + - **作用**: 通过OCR识别开奖结果按钮区域,返回识别到的文本类型 + - **返回值**: + - `"我知道了"` - 未中奖 + - `"立即领取奖品"` - 中奖 + - `None` - 识别失败 + - **实现**: 调用 `douyin_helpers.HelperFunctions.check_lottery_result_by_ocr()` + - **调用位置**: 检查开奖结果时调用 + +2. **`_handle_lottery_result_by_ocr(result_type: str) -> None`** + - **作用**: 根据OCR识别结果处理开奖结果 + - **参数**: `result_type: str` - "我知道了" 或 "立即领取奖品" + - **实现**: 调用 `douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr()` + - **调用位置**: 处理开奖结果时调用 + +#### 6.2.5 RoomUtilsMixin(直播间工具混入类) + +**文件位置**: `douyin/core/fudai_modules/fudai_room_utils.py` + +**职责**: 提供房间定位、记录等工具功能 + +**主要方法**: + +1. **`_find_room_pos_by_title(target_title: str, target_title_raw: str = "") -> int | None`** + - **作用**: 根据直播间标题在运行时映射表中查找对应的位置 + - **参数**: + - `target_title: str` - 目标直播间标题(规范化后) + - `target_title_raw: str` - 目标直播间标题(原始) + - **返回值**: `int | None` - 如果找到匹配的位置,返回位置值;否则返回None + - **实现**: 调用 `douyin_reservation_handler.ReservationHandler.find_room_pos_by_title()` + - **调用位置**: 预约回退时查找目标直播间 + +2. **`_record_room_title_and_pos() -> None`** + - **作用**: 记录当前直播间的标题和位置到运行时映射表 + - **用途**: 用于预约回退校验时验证位置信息 + - **实现**: 调用 `douyin_reservation_handler.ReservationHandler.record_room_title_and_pos()` + - **调用位置**: 进入直播间后调用 + +3. **`_seek_reservation_room(item: dict[str, Any]) -> bool`** + - **作用**: 根据预约记录里的 `pos_seen` 与当前 `room_pos` 进行回退,靠近目标直播间 + - **参数**: `item: dict` - 预约记录 + - **返回值**: `bool` - 是否成功找到目标直播间 + - **说明**: + - 使用 `high_value_fudai_max_swipe_back` 约束最大回退次数 + - 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配) + - **实现**: 调用 `douyin_reservation_handler.ReservationHandler.seek_reservation_room()` + - **调用位置**: 预约回退时调用 + +#### 6.2.6 MainLogicMixin(主逻辑混入类) + +**文件位置**: `douyin/core/fudai_modules/fudai_main_logic.py` + +**职责**: 提供主要的业务逻辑和流程控制 + +**主要方法**: + +1. **`_enhanced_log_kv(*args, **fields) -> None`** + - **作用**: 增强版日志记录,自动添加时间戳、设备ID等通用字段 + - **实现**: 调用 `douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv()` + - **调用位置**: 所有需要记录日志的地方 + +2. **`_log_step_time(step_name: str, start_time: float) -> None`** + - **作用**: 记录步骤耗时(带格式化) + - **参数**: + - `step_name: str` - 步骤名称 + - `start_time: float` - 开始时间戳 + - **调用位置**: 性能分析时调用 + +3. **`fudai_choujiang(device_id: str = "", y_pianyi: int = 0, needswitch: bool = False, wait_minutes: int = 15) -> None`** + - **作用**: 主循环入口(兼容原版接口) + - **参数**: + - `device_id: str` - 设备ID + - `y_pianyi: int` - Y轴偏移量 + - `needswitch: bool` - 是否允许切换直播间 + - `wait_minutes: int` - 每次循环等待时间(分钟) + - **实现**: 设置设备ID和配置,然后循环调用 `run_once_basic()` + - **调用位置**: `run_cli.py` 的 `main()` 函数中调用 + +#### 6.2.7 BaseFudaiMixin(基础混入类) + +**文件位置**: `douyin/core/fudai_modules/base_interface.py` + +**职责**: 提供通用功能,所有Mixin类的基类 + +**主要方法**: + +1. **`_safe_log(*args, **fields) -> None`** + - **作用**: 安全的日志记录,避免依赖主类的日志方法 + - **实现**: 尝试调用主类的 `_enhanced_log_kv()`,失败则使用 `print()` + - **调用位置**: Mixin类内部需要记录日志时调用 + +2. **`_safe_operation_call(operation_name: str, *args, **kwargs) -> Any`** + - **作用**: 安全的操作调用,避免依赖未定义的属性 + - **参数**: + - `operation_name: str` - 操作名称 + - `*args, **kwargs` - 传递给操作的参数 + - **返回值**: 操作结果,失败返回 `None` + - **调用位置**: Mixin类内部需要调用操作时使用 + +### 6.3 数据结构 + +#### 预约数据结构 + +预约数据存储在 `state/reservations.json` 文件中,格式如下: + +```json +[ + { + "room_title": "直播间标题", + "room_pos": { + "x": 540, + "y": 1200, + "title": "直播间标题" + }, + "lottery_time_ts": 1704067200.0, + "prize_value_yuan": 500.0, + "fudai_x": 900 + }, + ... +] +``` + +**字段说明**: +- `room_title: str` - 直播间标题(用于匹配) +- `room_pos: dict` - 直播间位置信息 + - `x: int` - X坐标 + - `y: int` - Y坐标 + - `title: str` - 直播间标题 +- `lottery_time_ts: float` - 开奖时间戳(Unix时间戳) +- `prize_value_yuan: float` - 奖品价值(元) +- `fudai_x: int` - 福袋图标X坐标(可选) + +#### 阶段类型枚举 + +阶段类型定义在 `douyin/stage/douyin_stage.py` 中: + +```python +IN_LIVE_ROOM = "IN_LIVE_ROOM" # 直播间 +RECOMMEND_PAGE = "RECOMMEND_PAGE" # 推荐页 +FOLLOW_LIST = "FOLLOW_LIST" # 关注列表 +LIVE_LIST = "LIVE_LIST" # 直播列表 +FUDai_DETAIL = "FUDai_DETAIL" # 福袋详情页 +FUDai_RESULT = "FUDai_RESULT" # 抽奖结果页 +FANSCLUB_JOIN = "FANSCLUB_JOIN" # 粉丝团加入页 +LIVE_CLOSED = "LIVE_CLOSED" # 直播已结束 +UNKNOWN = "UNKNOWN" # 未知阶段 +``` + +#### 福袋详情数据结构 + +福袋详情在代码中通常使用元组或字典表示: + +```python +# 元组格式(get_fudai_contain返回值) +( + content: str, # 福袋内容文本 + countdown_text: str, # 倒计时文本(格式:mm:ss) + participants: int, # 参与人数 + task_count: int, # 任务数量 + prize_value_yuan: float # 奖品价值(元) +) + +# 字典格式(用于传递) +{ + "content": "福袋内容", + "countdown_text": "05:30", + "participants": 1000, + "task_count": 2, + "prize_value_yuan": 500.0 +} +``` + +#### 直播间位置数据结构 + +```python +{ + "x": 540, # X坐标 + "y": 1200, # Y坐标 + "title": "直播间标题" # 直播间标题(用于匹配) +} +``` + +--- + +## 7. 配置系统详解 + +### 7.1 配置文件位置 + +配置文件位于 `config/config.json`,路径通过 `path_config.get_config_path()` 获取。 + +### 7.2 配置项详解 + +#### 7.2.1 基础运行配置 + +```json +{ + "needswitch": true, // 是否允许切换直播间 + "infinite_loop_enabled": true, // 是否启用无限循环 + "wait_minutes": 5 // 每次循环等待时间(分钟) +} +``` + +- **`needswitch`**: 控制是否允许自动切换直播间寻找更多福袋 + - `true`: 允许切换(多间模式) + - `false`: 不允许切换(单间模式) +- **`infinite_loop_enabled`**: 控制主循环是否无限运行 + - `true`: 无限循环 + - `false`: 单次运行后退出 +- **`wait_minutes`**: 每次循环结束后的等待时间(分钟) + +#### 7.2.2 福袋筛选配置 + +```json +{ + "min_prize_value_yuan": 200.0, // 最小奖品价值(元) + "min_participants": 0, // 最小参与人数(0=不限制) + "max_participants": 0, // 最大参与人数(0=不限制) + "skip_if_countdown_gt_seconds": 120, // 倒计时大于该秒数则跳过 + "skip_if_countdown_lt_seconds": 5, // 倒计时小于该秒数则不参与 + "contains_want": [], // 想要的福袋内容关键词列表 + "contains_not_want": [ // 不想要的福袋内容关键词列表 + "首饰盒", + "袜子" + ] +} +``` + +- **`min_prize_value_yuan`**: 只参与价值大于等于该值的福袋 +- **`min_participants`**: 只参与参与人数大于等于该值的福袋(0=不限制) +- **`max_participants`**: 只参与参与人数小于等于该值的福袋(0=不限制) +- **`skip_if_countdown_gt_seconds`**: 倒计时大于该秒数则跳过(避免等待时间过长) +- **`skip_if_countdown_lt_seconds`**: 倒计时小于该秒数则不参与(避免来不及参与) +- **`contains_want`**: 福袋内容必须包含这些关键词之一(空列表=不限制) +- **`contains_not_want`**: 福袋内容不能包含这些关键词(空列表=不限制) + +#### 7.2.3 高价值福袋预约配置 + +```json +{ + "high_value_fudai_enabled": true, // 是否启用高价值福袋预约 + "high_value_fudai_threshold_yuan": 500.0, // 高价值福袋阈值(元) + "high_value_fudai_join_ahead_seconds": 120, // 提前参与秒数(开奖前N秒回退参与) + "high_value_fudai_max_swipe_back": 50, // 最大回退滑动次数 + "high_value_fudai_max_reservations": 9999, // 最大预约数量 + "high_value_fudai_after_action": "continue", // 预约后的动作(continue/switch) + "high_value_room_revisit_enabled": true, // 是否启用高价值直播间重访 + "high_value_room_revisit_only_current_run": true, // 是否仅在当前运行中重访 + "reservation_back_verify_enabled": true, // 是否验证预约回退 + "reservation_back_swipe_delay": 0.1, // 预约回退滑动延迟(秒) + "reservation_preempt_min_value": 0.0 // 预约抢占最小价值(元) +} +``` + +- **`high_value_fudai_enabled`**: 是否启用高价值福袋预约功能 +- **`high_value_fudai_threshold_yuan`**: 价值大于等于该值的福袋会被预约 +- **`high_value_fudai_join_ahead_seconds`**: 开奖前N秒自动回退到目标直播间参与 +- **`high_value_fudai_max_swipe_back`**: 回退时最多滑动N次(防止无限滑动) +- **`high_value_fudai_max_reservations`**: 最多同时记录N个预约(超过后丢弃最晚开奖的) +- **`high_value_fudai_after_action`**: 预约后的动作 + - `"continue"`: 继续当前流程 + - `"switch"`: 切换直播间 +- **`high_value_room_revisit_enabled`**: 是否启用高价值直播间重访(记录高价值直播间,后续自动重访) +- **`high_value_room_revisit_only_current_run`**: 是否仅在当前运行中重访(重启后不保留) +- **`reservation_back_verify_enabled`**: 是否验证预约回退(回退后验证是否在目标直播间) +- **`reservation_back_swipe_delay`**: 预约回退滑动后的延迟(秒) +- **`reservation_preempt_min_value`**: 预约抢占最小价值(如果新福袋价值更高,可以抢占旧预约) + +#### 7.2.4 福袋查找配置 + +```json +{ + "fudai_find_max_attempts": 99999, // 最大尝试次数(已废弃,保留仅为兼容性) + "fudai_icon_retry_delay_seconds": 0.1, // 福袋图标重试延迟(秒) + "fudai_icon_max_wait_seconds": 8.5, // 福袋图标最大等待时间(秒) + "fudai_click_wait_seconds": 1.7, // 点击福袋图标后等待详情页加载的时间(秒) + "fudai_detail_initial_wait_seconds": 0.8, // 福袋详情页初始等待时间(秒) + "fudai_detail_verified_wait_seconds": 0.2, // 福袋详情页验证后等待时间(秒) + "fudai_detail_retry_delay_seconds": 0.5, // 福袋详情页重试延迟(秒) + "fudai_detail_save_debug_images": false // 是否保存调试图像 +} +``` + +- **`fudai_icon_retry_delay_seconds`**: 每次重试查找福袋图标之间的延迟 +- **`fudai_icon_max_wait_seconds`**: 最多等待N秒查找福袋图标(超时后放弃) +- **`fudai_click_wait_seconds`**: 点击福袋图标后等待详情页加载的时间 +- **`fudai_detail_initial_wait_seconds`**: 进入福袋详情页后的初始等待时间(等待页面稳定) +- **`fudai_detail_verified_wait_seconds`**: 验证详情页加载成功后的等待时间 +- **`fudai_detail_retry_delay_seconds`**: 详情页加载失败后的重试延迟 +- **`fudai_detail_save_debug_images`**: 是否保存调试图像(用于调试OCR识别问题) + +#### 7.2.5 滑动和导航配置 + +```json +{ + "reset_after_swipes_enabled": true, // 是否启用滑动次数重置 + "reset_after_swipes": 50, // 滑动N次后重置到推荐页 + "swipe_duration_ms": 600, // 滑动持续时间(毫秒) + "switch_room_wait_after_stage_diag_seconds": 4.0 // 切换直播间后等待阶段诊断的时间(秒) +} +``` + +- **`reset_after_swipes_enabled`**: 是否启用滑动次数重置功能 +- **`reset_after_swipes`**: 滑动N次后自动返回推荐页(防止无限滑动) +- **`swipe_duration_ms`**: 滑动持续时间(毫秒,值越大滑动越慢) +- **`switch_room_wait_after_stage_diag_seconds`**: 切换直播间后等待阶段诊断的时间(确保页面稳定) + +#### 7.2.6 粉丝团配置 + +```json +{ + "auto_join_fansclub": true, // 是否自动加入粉丝团 + "fansclub_fail_action": "switch" // 加入粉丝团失败后的动作(switch/continue) +} +``` + +- **`auto_join_fansclub`**: 是否自动加入粉丝团(如果需要) +- **`fansclub_fail_action`**: 加入粉丝团失败后的动作 + - `"switch"`: 切换直播间 + - `"continue"`: 继续当前流程 + +#### 7.2.7 超时配置 + +```json +{ + "no_attend_timeout_minutes": 30.0 // 无参与超时时间(分钟) +} +``` + +- **`no_attend_timeout_minutes`**: 如果N分钟内没有成功参与任何福袋,则返回推荐页(防止卡在无福袋的直播间) + +#### 7.2.8 静音时段配置 + +```json +{ + "fudai_quiet_hours_enabled": true, // 是否启用静音时段 + "fudai_quiet_start_hour": 2, // 静音时段开始时间(小时,0-23) + "fudai_quiet_end_hour": 9 // 静音时段结束时间(小时,0-23) +} +``` + +- **`fudai_quiet_hours_enabled`**: 是否启用静音时段(在指定时间段内不参与福袋) +- **`fudai_quiet_start_hour`**: 静音时段开始时间(小时,0-23) +- **`fudai_quiet_end_hour`**: 静音时段结束时间(小时,0-23) + +#### 7.2.9 检测阈值配置 + +```json +{ + "stage_diag_max_time": 5.0, // 阶段诊断最大时间(秒) + "stage_diag_max_step_time": 2.0, // 阶段诊断单步最大时间(秒) + "live_room_match_threshold": 0.6, // 直播间模板匹配阈值(0.0-1.0) + "fudai_template_match_enabled": false, // 是否启用福袋模板匹配 + "fudai_template_match_threshold": 0.7, // 福袋模板匹配阈值(0.0-1.0) + "lucky_draw_red_ratio_threshold": 0.8, // 开奖页面红色占比阈值(0.0-1.0) + "attend_button_red_ratio_threshold": 0.25, // 参与按钮红色占比阈值(0.0-1.0) + "fansclub_join_red_ratio_threshold": 0.25, // 粉丝团加入按钮红色占比阈值(0.0-1.0) + "coupon_template_match_threshold": 0.4, // 优惠券弹窗模板匹配阈值(0.0-1.0) + "fudai_detail_template_threshold": 0.54 // 福袋详情页模板匹配阈值(0.0-1.0) +} +``` + +- **`stage_diag_max_time`**: 阶段诊断总最大时间(超时后返回UNKNOWN) +- **`stage_diag_max_step_time`**: 阶段诊断单步最大时间(超时后跳过该步骤) +- **`live_room_match_threshold`**: 直播间模板匹配阈值(值越大越严格) +- **`fudai_template_match_enabled`**: 是否启用福袋模板匹配(用于查找福袋图标) +- **`fudai_template_match_threshold`**: 福袋模板匹配阈值 +- **`lucky_draw_red_ratio_threshold`**: 开奖页面红色占比阈值(用于检测开奖结果页面) +- **`attend_button_red_ratio_threshold`**: 参与按钮红色占比阈值(用于检测按钮状态) +- **`fansclub_join_red_ratio_threshold`**: 粉丝团加入按钮红色占比阈值 +- **`coupon_template_match_threshold`**: 优惠券弹窗模板匹配阈值 +- **`fudai_detail_template_threshold`**: 福袋详情页模板匹配阈值 + +#### 7.2.10 OCR配置 + +```json +{ + "enable_ocr_mode1": false // 是否启用OCR模式1(已废弃,保留仅为兼容性) +} +``` + +#### 7.2.11 日志配置 + +```json +{ + "logging": { + "level": "DEBUG", // 日志级别(DEBUG/INFO/WARNING/ERROR) + "file_path": "logs/unified.log", // 日志文件路径 + "keep_days": 30, // 日志保留天数 + "use_dated_logs": true, // 是否使用按日期分割的日志文件 + "rotation": { + "enabled": true, // 是否启用日志轮转 + "max_bytes": 10485760, // 单个日志文件最大大小(字节) + "backup_count": 5, // 保留的备份文件数量 + "when": "midnight", // 轮转时间(midnight/daily/hourly) + "interval": 1 // 轮转间隔 + }, + "beautify_output": true, // 是否美化输出 + "show_timestamps": true, // 是否显示时间戳 + "show_execution_times": true, // 是否显示执行时间 + "debug_detail_level": "detailed", // 调试详细级别 + "error_detail_level": "full", // 错误详细级别 + "action_log_format": "detailed", // 操作日志格式 + "color_output": true, // 是否启用彩色输出 + "max_log_lines_display": 1000, // 最大显示日志行数 + "auto_scroll_logs": true, // 是否自动滚动日志 + "performance_tracking": { + "enabled": true, // 是否启用性能跟踪 + "track_function_calls": true, // 是否跟踪函数调用 + "track_database_queries": false, // 是否跟踪数据库查询 + "slow_operation_threshold_ms": 100 // 慢操作阈值(毫秒) + }, + "error_logging": { + "capture_stack_traces": true, // 是否捕获堆栈跟踪 + "include_context": true, // 是否包含上下文 + "max_error_logs": 1000, // 最大错误日志数量 + "error_categories": [ // 错误类别列表 + "ocr", + "network", + "validation", + "system", + "user_action" + ] + } + } +} +``` + +#### 7.2.12 调试配置 + +```json +{ + "debug_captures": { + "enabled": true, // 是否启用调试捕获 + "keep_days": 3, // 调试文件保留天数 + "max_files": 2000, // 最大调试文件数量 + "auto_cleanup": true // 是否自动清理 + }, + "reservation_test_mode": false // 是否启用预约测试模式 +} +``` + +### 7.3 配置加载流程 + +1. **初始化时加载**: `fudai_analyse.__init__()` → `load_config()` +2. **配置文件路径**: 通过 `path_config.get_config_path()` 获取 +3. **配置更新**: 从JSON文件读取配置,更新类的所有相关属性 +4. **默认值**: 如果配置项不存在,使用类属性中的默认值 + +### 7.4 配置验证 + +配置加载后,会进行基本验证: +- 检查必需配置项是否存在 +- 验证数值范围(如阈值必须在0.0-1.0之间) +- 验证枚举值(如 `fansclub_fail_action` 必须是 "switch" 或 "continue") + +--- + +## 8. 状态管理机制详解 + +### 8.1 状态管理概述 + +项目使用多种状态标志来跟踪运行状态,确保流程的正确执行和异常恢复。状态主要分为以下几类: + +1. **运行状态标志**:控制主流程的执行 +2. **预约状态**:管理高价值福袋预约 +3. **等待开奖状态**:跟踪正在等待开奖的福袋 +4. **超时保护状态**:防止脚本卡死 +5. **阶段诊断状态**:记录当前页面阶段 + +### 8.2 运行状态标志 + +#### 8.2.1 预约回退直接参与标志 + +- **属性名**: `_reservation_back_direct_attend: bool` +- **作用**: 标记预约回退后是否直接参与(跳过阶段诊断和福袋查找) +- **设置时机**: 预约回退成功后设置为 `True` +- **清除时机**: 参与完成后清除 +- **使用位置**: `run_once_basic()` 开头检查 + +**代码示例**: +```python +# 在 run_once_basic() 中 +if self._reservation_back_direct_attend: + # 直接参与,跳过阶段诊断 + self._handle_reservation_direct_attend() + self._reservation_back_direct_attend = False + return +``` + +#### 8.2.2 等待开奖状态 + +- **属性名**: `_waiting_for_lottery_result: bool` +- **作用**: 标记是否正在等待某个福袋的开奖结果 +- **设置时机**: 参与福袋后,如果倒计时较长,设置为 `True` +- **清除时机**: 检查到开奖结果后清除 +- **使用位置**: `run_once_basic()` 中检查 + +**代码示例**: +```python +# 在 run_once_basic() 中 +if self._waiting_for_lottery_result: + # 检查预约抢占 + if self._check_reservation_preempt(): + self._waiting_for_lottery_result = False + return + + # 检查开奖结果 + if time.time() >= self._lottery_result_expected_ts: + self._handle_lottery_result() + self._waiting_for_lottery_result = False + return +``` + +#### 8.2.3 跳过阶段诊断标志 + +- **属性名**: `_skip_stage_diagnosis_and_find_fudai: bool` +- **作用**: 标记是否跳过阶段诊断和福袋查找(直接进入详情页处理) +- **设置时机**: + - 点击参与抽奖按钮后(`attend_choujiang()` 中设置) + - 预约回退后,如果确定在目标直播间 +- **清除时机**: 处理完成后清除 +- **使用位置**: `run_once_basic()` 中检查 +- **使用场景**: + - 点击参与按钮后,详情页会自动关闭,下次循环直接查找福袋,跳过阶段检测 + - 预约回退后,如果确定在目标直播间,跳过阶段检测直接查找福袋 + +#### 8.2.4 福袋详情验证标志 + +- **属性名**: `_fudai_detail_verified: bool` +- **作用**: 标记是否已验证过福袋详情页(用于避免重复查找福袋) +- **设置时机**: 验证福袋详情页成功后设置为 `True` +- **清除时机**: 处理完成后清除 +- **使用位置**: `_handle_live_room_has_or_not_fudai()` 中检查 +- **使用场景**: 如果已验证过详情页,直接调用 `_handle_in_fudai_detail()`,不查找福袋 + +#### 8.2.5 刚刚切换直播间标志 + +- **属性名**: `_just_switched_room: bool` +- **作用**: 标记是否刚刚切换了直播间(用于优化阶段诊断) +- **设置时机**: 切换直播间后设置为 `True` +- **清除时机**: 阶段诊断完成后清除 +- **使用位置**: 阶段诊断时,如果刚切换,增加等待时间 + +#### 8.2.6 第一次运行标志 + +- **属性名**: `_first_run_once_basic: bool` +- **作用**: 标记是否是第一次运行 `run_once_basic()` +- **设置时机**: 初始化时设置为 `True` +- **清除时机**: 第一次运行后设置为 `False` +- **使用位置**: `run_once_basic()` 中检查 +- **使用场景**: 第一次运行时清空预约队列和状态文件,确保每次启动时队列为空 + +#### 8.2.7 队列满等待标志 + +- **属性名**: `queue_full_waiting_at_earliest: bool` +- **作用**: 标记是否在队列满等待状态(回退到最早开奖的预约直播间等待) +- **设置时机**: 队列满时,回退到最早开奖的预约直播间后设置为 `True` +- **清除时机**: + - 所有预约完成后清除 + - 预约回退后清除 +- **使用位置**: `run_once_basic()` 中检查 +- **使用场景**: 队列满时,回退到最早开奖的预约直播间等待,避免继续添加预约 + +### 8.3 预约状态管理 + +#### 8.3.1 预约队列 + +- **属性名**: `reservations: List[Dict[str, Any]]` +- **作用**: 存储高价值福袋预约列表 +- **数据结构**: 见 [6.2 数据结构 - 预约数据结构](#62-数据结构) +- **初始化时机**: + - **第一次运行**: 清空预约队列,不加载状态文件(`_first_run_once_basic = True`) + - **非第一次运行**: 保持当前预约队列,不从状态文件加载 +- **保存时机**: + - 添加预约时 + - 清理过期预约时 + - 预约回退时 + - 队列裁剪时 + - 写入状态文件供外部查看 + +**重要变更**: +- **不再从状态文件加载**: 每次启动时预约队列为空,不加载之前保存的预约 +- **第一次运行清空**: 如果是第一次运行,强制清空预约队列和状态文件 +- **状态文件仅用于外部查看**: 状态文件主要用于外部查看预约状态,程序内部不依赖状态文件加载 + +#### 8.3.2 预约状态文件 + +- **文件路径**: `state/reservations.json` +- **格式**: JSON对象,包含 `reservations` 数组和其他元数据 +- **持久化**: 每次修改预约队列后自动保存(供外部查看) +- **加载策略**: + - **不再自动加载**: 程序启动时不从状态文件加载预约数据 + - **仅用于外部查看**: 状态文件主要用于外部工具查看预约状态 + - **第一次运行清空**: 第一次运行时清空状态文件 + +**代码示例**: +```python +# 加载预约数据 +def load_reservations_from_state(analyser): + try: + with open(analyser._reservations_state_path, 'r', encoding='utf-8') as f: + data = json.load(f) + analyser.reservations = data.get('reservations', []) + except FileNotFoundError: + analyser.reservations = [] + except Exception as e: + logger.error(f"加载预约数据失败: {e}") + analyser.reservations = [] + +# 保存预约数据 +def save_reservations_to_state(analyser): + try: + data = { + 'reservations': analyser.reservations, + 'updated_at': time.time() + } + with open(analyser._reservations_state_path, 'w', encoding='utf-8') as f: + json.dump(data, f, ensure_ascii=False, indent=2) + except Exception as e: + logger.error(f"保存预约数据失败: {e}") +``` + +#### 8.3.3 预约队列管理 + +**队列排序规则**: +1. **主排序键**: `lottery_time_ts`(开奖时间戳,升序) +2. **次排序键**: `prize_value_yuan`(奖品价值,降序) +3. **第三排序键**: `created_ts`(创建时间戳,升序) + +**队列裁剪**: +- 当队列长度超过 `high_value_fudai_max_reservations` 时 +- 保留优先级最高的N个预约(按排序规则) +- 丢弃优先级最低的预约 + +**过期清理**: +- 每次处理预约窗口时检查 +- 如果 `lottery_time_ts <= 当前时间`,则清理该预约 + +### 8.4 等待开奖状态管理 + +#### 8.4.1 等待开奖标志 + +- **属性名**: `_waiting_for_lottery_result: bool` +- **关联属性**: + - `_lottery_result_expected_ts: float` - 预期开奖时间戳 + - `_lottery_result_room_pos: Optional[Dict]` - 等待开奖的直播间位置信息 + +#### 8.4.2 等待开奖流程 + +1. **设置等待状态**: 参与福袋后,如果倒计时较长(> 30秒),设置等待状态 +2. **等待期间**: 继续运行主循环,但跳过福袋查找和参与 +3. **检查预约抢占**: 如果发现更高价值的预约,取消当前等待 +4. **检查开奖结果**: 到达预期开奖时间后,检查开奖结果 +5. **清除等待状态**: 处理完开奖结果后清除 + +**代码示例**: +```python +# 参与福袋后设置等待状态 +if countdown_seconds > 30: + self._waiting_for_lottery_result = True + self._lottery_result_expected_ts = time.time() + countdown_seconds + self._lottery_result_room_pos = room_pos + logger.info(f"设置等待开奖状态,预期开奖时间: {self._lottery_result_expected_ts}") +``` + +### 8.5 超时保护机制 + +#### 8.5.1 30分钟无参与超时 + +- **属性名**: `_last_successful_attend_ts: float` +- **配置项**: `no_attend_timeout_minutes: float`(默认30.0分钟) +- **作用**: 如果N分钟内没有成功参与任何福袋,返回推荐页面(防止卡在无福袋的直播间) + +**检查逻辑**: +```python +# 在 run_once_basic() 中 +current_time = time.time() +timeout_seconds = self._no_attend_timeout_minutes * 60 + +# 检查是否超时 +if self._last_successful_attend_ts > 0: + elapsed = current_time - self._last_successful_attend_ts + if elapsed > timeout_seconds: + logger.warning(f"30分钟无参与超时,返回推荐页面") + self._return_to_recommend_and_reenter_live() + return +else: + # 从未成功参与,检查运行时间 + elapsed = current_time - self._run_start_ts + if elapsed > timeout_seconds: + logger.warning(f"运行{timeout_seconds}秒未成功参与,返回推荐页面") + self._return_to_recommend_and_reenter_live() + return +``` + +#### 8.5.2 滑动次数重置 + +- **属性名**: `_swipe_times: int` +- **配置项**: `reset_after_swipes: int`(默认50次) +- **作用**: 滑动N次后自动返回推荐页面(防止无限滑动) + +**检查逻辑**: +```python +# 在 _maybe_reset_after_swipes() 中 +if self.config.get("reset_after_swipes_enabled", True): + max_swipes = self.config.get("reset_after_swipes", 50) + if self._swipe_times >= max_swipes: + logger.info(f"滑动次数达到{max_swipes}次,返回推荐页面") + self._return_to_recommend_and_reenter_live() + self._swipe_times = 0 + return True +return False +``` + +### 8.6 阶段诊断状态 + +#### 8.6.1 上次诊断信息 + +- **属性名**: + - `_last_diag_stage: str` - 上次诊断的阶段 + - `_last_diag_seen: str` - 上次诊断看到的标识(如直播间标题) + - `_last_diag_ts: float` - 上次诊断的时间戳 + +#### 8.6.2 阶段诊断优化 + +- **最小间隔**: `screenshot_diagnose_min_interval_seconds`(默认8.0秒) +- **作用**: 避免频繁截图和诊断,提高效率 + +**代码示例**: +```python +# 在 diagnose_stage_from_current_screen() 中 +current_time = time.time() +min_interval = analyser.screenshot_diagnose_min_interval_seconds + +# 如果距离上次诊断时间太短,且阶段未变化,直接返回上次结果 +if (analyser._last_diag_ts > 0 and + current_time - analyser._last_diag_ts < min_interval and + analyser._last_diag_stage != "UNKNOWN"): + return analyser._last_diag_stage +``` + +### 8.7 状态持久化 + +#### 8.7.1 预约状态持久化 + +- **文件**: `state/reservations.json` +- **时机**: 每次修改预约队列后自动保存 +- **格式**: JSON格式,包含预约列表和更新时间戳 + +#### 8.7.2 运行时状态 + +- **内存状态**: 大部分状态标志存储在内存中(重启后丢失) +- **持久化状态**: 只有预约数据持久化到文件 +- **恢复机制**: 程序启动时自动加载预约数据 + +--- + +## 9. 错误处理和异常情况 + +### 9.1 错误处理策略 + +项目采用**多层错误处理策略**,确保程序在遇到异常时能够优雅降级或恢复: + +1. **底层操作错误处理**:捕获ADB命令失败、文件操作失败等 +2. **OCR识别错误处理**:处理OCR失败、识别结果为空等 +3. **阶段诊断错误处理**:处理诊断超时、识别失败等 +4. **流程控制错误处理**:处理流程异常、状态不一致等 + +### 9.2 常见错误和恢复机制 + +#### 9.2.1 截图失败 + +**错误原因**: +- ADB连接断开 +- 设备锁屏 +- 设备无响应 +- 文件系统错误 + +**处理机制**: +```python +def get_screenshot(self, device_id, path="pic"): + # 优先方法:exec-out(1次adb调用) + try: + with open(tmp_file, "wb") as f: + subprocess.run( + [adb, "-s", device_id, "exec-out", "screencap", "-p"], + stdout=f, + stderr=subprocess.DEVNULL, + check=True, + ) + # 验证文件有效性 + if _valid_png(tmp_file): + _safe_replace_file(tmp_file, out_file) + return True + except Exception: + pass + + # 回退方法1:shell screencap + pull(2次adb调用) + try: + # ... 回退逻辑 + except Exception: + pass + + # 回退方法2:使用screenshot1.png + try: + # ... 回退逻辑 + except Exception: + return False # 所有方法都失败 +``` + +**恢复策略**: +- 重试机制(最多2次) +- 多种方法回退 +- 返回 `False` 让上层处理 + +#### 9.2.2 OCR识别失败 + +**错误原因**: +- 图片质量差 +- 文字区域裁剪错误 +- OCR引擎初始化失败 +- 识别结果为空 + +**处理机制**: +```python +def analyse_pic_word(self, picname, change_color=0, pic_path=None): + try: + # 确保OCR已初始化 + self._ensure_ocr() + if self.ocr is None: + logger.error("OCR引擎未初始化") + return "" + + # 加载图片 + pic_path = pic_path or self._find_pic_path(picname, for_reading=True) + if not pic_path or not os.path.exists(pic_path): + logger.error(f"图片文件不存在: {picname}") + return "" + + # 执行OCR + img = Image.open(pic_path) + # ... OCR处理 + + # 提取文本 + text = self.extract_ocr_content(result) + return text if text else "" + except Exception as e: + logger.error(f"OCR识别失败: {e}") + return "" # 返回空字符串,让上层处理 +``` + +**恢复策略**: +- 返回空字符串,让上层判断 +- 上层可以重试或跳过该步骤 +- 记录错误日志 + +#### 9.2.3 阶段诊断超时 + +**错误原因**: +- 截图失败 +- OCR识别超时 +- 像素检测超时 +- 设备响应慢 + +**处理机制**: +```python +def diagnose_stage_from_current_screen(analyser): + max_time = analyser.config.get("stage_diag_max_time", 5.0) + start_time = time.time() + + try: + # 步骤0: 检测直播间(优先级最高) + if time.time() - start_time > max_time: + return "UNKNOWN" + + # 步骤1: 并行像素检测 + if time.time() - start_time > max_time: + return "UNKNOWN" + + # ... 其他步骤 + + except Exception as e: + logger.error(f"阶段诊断异常: {e}") + return "UNKNOWN" + + return "UNKNOWN" # 默认返回未知阶段 +``` + +**恢复策略**: +- 设置超时时间(`stage_diag_max_time`) +- 超时后返回 `UNKNOWN` +- 上层根据 `UNKNOWN` 执行默认逻辑(导航到直播间) + +#### 9.2.4 福袋查找失败 + +**错误原因**: +- 福袋图标未出现 +- 像素检测失败 +- 模板匹配失败 +- 超时 + +**处理机制**: +```python +def find_fudai_icon(analyser): + max_wait = analyser.fudai_icon_max_wait_seconds + start_time = time.time() + + while time.time() - start_time < max_wait: + try: + # 获取截图 + if not analyser.operation.get_screenshot(analyser.device_id): + time.sleep(analyser.fudai_icon_retry_delay_seconds) + continue + + # 查找福袋图标 + result = _find_fudai_icon_internal(analyser) + if result: + return result + + # 等待后重试 + time.sleep(analyser.fudai_icon_retry_delay_seconds) + except Exception as e: + logger.error(f"查找福袋图标异常: {e}") + time.sleep(analyser.fudai_icon_retry_delay_seconds) + + # 超时返回None + logger.warning(f"查找福袋图标超时({max_wait}秒)") + return None +``` + +**恢复策略**: +- 设置最大等待时间(`fudai_icon_max_wait_seconds`) +- 超时后返回 `None` +- 上层根据 `None` 执行默认逻辑(切换直播间或返回) + +#### 9.2.5 福袋详情页加载失败 + +**错误原因**: +- 点击福袋图标后页面未加载 +- 详情页元素未出现 +- 超时 + +**处理机制**: +```python +def _handle_in_fudai_detail(self): + # 等待详情页加载 + initial_wait = self.config.get("fudai_detail_initial_wait_seconds", 0.8) + time.sleep(initial_wait) + + # 验证详情页是否加载成功 + if self.fudai_click_verify_enabled: + max_retries = self.fudai_find_max_retries + for i in range(max_retries): + try: + if not self.operation.get_screenshot(self.device_id): + continue + + # 检测详情页 + stage = diagnose_stage_from_current_screen(self) + if stage == "FUDai_DETAIL": + break # 加载成功 + + # 等待后重试 + time.sleep(self.config.get("fudai_detail_retry_delay_seconds", 0.5)) + except Exception as e: + logger.error(f"验证详情页加载异常: {e}") + + # 如果仍然失败,记录警告但继续处理 + if stage != "FUDai_DETAIL": + logger.warning("福袋详情页加载验证失败,但继续处理") +``` + +**恢复策略**: +- 重试机制(最多N次) +- 验证失败后记录警告但继续处理 +- 如果OCR识别失败,返回空值让上层处理 + +#### 9.2.6 预约回退失败 + +**错误原因**: +- 找不到目标直播间 +- 滑动次数超限 +- 直播间已关闭 +- 标题匹配失败 + +**处理机制**: +```python +def process_reservation_attend_window(analyser, ...): + try: + # 查找目标直播间 + if not seek_reservation_room_callback(item): + logger.warning(f"找不到预约直播间: {item.get('room_title')}") + return False + + # 回退到目标直播间 + swipe_down_back_callback() + time.sleep(reservation_back_swipe_delay_s) + + # 验证是否在目标直播间 + if analyser.config.get("reservation_back_verify_enabled", True): + if not verify_reservation_room(analyser, item): + logger.warning("预约回退验证失败") + return False + + return True + except Exception as e: + logger.error(f"预约回退异常: {e}") + return False +``` + +**恢复策略**: +- 验证失败后返回 `False` +- 上层可以重试或跳过该预约 +- 记录错误日志 + +### 9.3 异常情况处理 + +#### 9.3.1 设备断开连接 + +**检测**: ADB命令执行失败 +**处理**: +- 记录错误日志 +- 返回错误状态 +- 上层可以重试或退出 + +#### 9.3.2 直播间关闭 + +**检测**: 阶段诊断返回 `LIVE_CLOSED` +**处理**: +- 切换到下一个直播间 +- 或返回推荐页面 + +#### 9.3.3 网络异常 + +**检测**: OCR初始化失败、网络请求超时 +**处理**: +- 使用本地OCR引擎(PaddleOCR) +- 重试机制 +- 降级处理 + +#### 9.3.4 状态不一致 + +**检测**: 阶段诊断结果与预期不符 +**处理**: +- 重新诊断 +- 导航到正确页面 +- 重置相关状态 + +### 9.4 错误日志记录 + +所有错误都会记录到日志系统: + +```python +# 统一日志记录 +logger.error(f"错误描述: {error}", exc_info=True) + +# 带上下文的错误记录 +logger.error( + f"OCR识别失败: {picname}", + extra={ + "picname": picname, + "pic_path": pic_path, + "error": str(e) + } +) +``` + +--- + +## 10. 代码示例 + +### 10.1 完整运行示例 + +```python +# run_cli.py +from douyin.core.douyin_fudai import fudai_analyse +from Underlying_Operations import underlying_operations + +# 初始化 +operation = underlying_operations() +device_id = operation.select_device() +if not device_id: + print("未检测到设备") + exit(1) + +# 创建分析器 +analyser = fudai_analyse() +analyser.device_id = device_id + +# 获取设备分辨率 +width, height = operation.get_device_resolution(device_id) +analyser.resolution_ratio_x = width +analyser.resolution_ratio_y = height + +# 加载配置 +analyser.load_config() + +# 开始主循环 +analyser.fudai_choujiang() +``` + +### 10.2 阶段诊断示例 + +```python +# 获取截图 +if not analyser.operation.get_screenshot(analyser.device_id): + logger.error("截图失败") + return + +# 阶段诊断 +stage = diagnose_stage_from_current_screen(analyser) +logger.info(f"当前阶段: {stage}") + +# 根据阶段执行逻辑 +if stage == "IN_LIVE_ROOM": + # 处理直播间逻辑 + analyser._handle_live_room_has_or_not_fudai() +elif stage == "FUDai_DETAIL": + # 处理福袋详情页 + analyser._handle_in_fudai_detail() +elif stage == "FUDai_RESULT": + # 处理开奖结果 + analyser._handle_lottery_result() +else: + # 导航到直播间 + analyser._navigate_to_live_room() +``` + +### 10.3 福袋信息获取示例 + +```python +# 获取福袋信息(并行OCR) +content, countdown_text, participants, task_count, prize_value_yuan = \ + get_fudai_contain(analyser, renwu=2) + +logger.info(f"福袋内容: {content}") +logger.info(f"倒计时: {countdown_text}") +logger.info(f"参与人数: {participants}") +logger.info(f"任务数量: {task_count}") +logger.info(f"奖品价值: {prize_value_yuan}元") + +# 判断是否参与 +if basic_join_decision(analyser, { + "content": content, + "countdown_text": countdown_text, + "participants": participants, + "task_count": task_count, + "prize_value_yuan": prize_value_yuan +}): + # 参与福袋 + attend_choujiang(analyser) +``` + +### 10.4 预约管理示例 + +```python +# 加载预约数据 +load_reservations_from_state(analyser) + +# 添加预约 +if prize_value_yuan >= analyser.config.get("high_value_fudai_threshold_yuan", 500.0): + reservation = { + "room_title": room_title, + "room_pos": room_pos, + "lottery_time_ts": time.time() + countdown_seconds, + "prize_value_yuan": prize_value_yuan, + "fudai_x": fudai_x + } + analyser.reservations.append(reservation) + save_reservations_to_state(analyser) + +# 处理预约回退窗口 +if process_reservation_attend_window( + analyser, + analyser.reservations, + room_pos, + reservation_focus_until_ts_ref, + reservation_after_action_pending_ref, + reservation_back_swipe_delay_s, + swipe_down_back_callback, + seek_reservation_room_callback, + sort_reservations_callback, + write_state_callback +): + logger.info("已触发预约回退") + return +``` + +--- + +## 11. 模块详解 + +### 11.1 核心模块 (`douyin/core/`) + +#### 11.1.1 `douyin_fudai.py` - 主调度器 + +- **职责**: 核心调度器,主流程控制 +- **主要类**: `fudai_analyse`(使用Mixin模式组合功能) +- **设计模式**: Mixin组合模式 +- **主要方法**: + - `fudai_choujiang()`: 主循环入口 + - `run_once_basic()`: 单次循环执行 + - `load_config()`: 加载配置 + +#### 11.1.2 `douyin_flow_control.py` - 流程控制 + +- **职责**: 流程控制辅助函数 +- **主要函数**: + - `find_and_open_fudai_detail()`: 查找并打开福袋详情 + - `handle_no_fudai_situation()`: 处理无福袋情况 + +#### 11.1.3 `fudai_modules/` - Mixin模块 + +- **`NavigationMixin`**: 导航功能(滑动、返回等) +- **`StageDetectionMixin`**: 阶段检测 +- **`PopupHandlerMixin`**: 弹窗处理 +- **`LotteryResultMixin`**: 抽奖结果处理 +- **`RoomUtilsMixin`**: 直播间工具 +- **`MainLogicMixin`**: 主逻辑 + +### 11.2 阶段诊断模块 (`douyin/stage/`) + +#### 11.2.1 `douyin_stage.py` - 阶段诊断核心 + +- **职责**: 综合诊断当前页面阶段 +- **主要函数**: `diagnose_stage_from_current_screen()` +- **支持的阶段**: `IN_LIVE_ROOM`, `RECOMMEND_PAGE`, `FUDai_DETAIL`, `FUDai_RESULT`, 等 + +#### 11.2.2 `douyin_stage_handler.py` - 阶段处理 + +- **职责**: 阶段处理逻辑,包括直播间检测等 + +### 11.3 检测模块 (`douyin/detection/`) + +#### 11.3.1 `douyin_pixel.py` - 像素检测 + +- **职责**: 像素级检测(弹窗、按钮、页面等) +- **主要函数**: + - `read_pixel_stage_state_from_screenshot()`: 并行像素检测 + - `detect_live_room_icons_by_pixel()`: 检测直播间图标 + - `detect_attend_button_red_area()`: 检测参与按钮 + - `detect_fansclub_join_red_area()`: 检测粉丝团加入按钮 + - `detect_coupon_popup_background()`: 检测优惠券弹窗 + - `detect_redpacket_popup_background()`: 检测红包弹窗 + - `detect_lucky_draw_result_popup()`: 检测开奖结果弹窗 + - `detect_fudai_detail_page()`: 检测福袋详情页 + +#### 11.3.2 `douyin_detection.py` - 综合检测 + +- **职责**: 整合像素、模板、OCR检测 +- **主要函数**: `check_have_fudai_with_ready_screenshot()` + +### 11.4 福袋模块 (`douyin/fudai/`) + +#### 11.4.1 `douyin_fudai_core.py` - 福袋核心逻辑 + +- **职责**: 福袋核心业务逻辑 +- **主要函数**: + - `get_fudai_contain()`: 获取福袋信息(并行OCR) + - `basic_join_decision()`: 判断是否参与 + +#### 11.4.2 `douyin_fudai_detail.py` - 福袋详情处理 + +- **职责**: 福袋详情页处理 + +#### 11.4.3 `douyin_fudai_finder.py` - 福袋查找器 + +- **职责**: 查找福袋图标 + +#### 11.4.4 `core/` - 福袋核心子模块 + +- **`fudai_filter.py`**: 福袋筛选逻辑 +- **`fudai_result_checker.py`**: 开奖结果检查 +- **`fudai_attend.py`**: 参与抽奖逻辑 + +### 11.5 预约模块 (`douyin/reservation/`) + +#### 11.5.1 `douyin_reservation_logic.py` - 预约逻辑 + +- **职责**: 高价值福袋预约核心逻辑 +- **主要函数**: + - `load_reservations_from_state()`: 加载预约数据 + - `process_reservation_attend_window()`: 处理预约回退窗口 + - `add_reservation()`: 添加预约 + - `sort_reservations()`: 排序预约队列 + +#### 11.5.2 `douyin_reservation_handler.py` - 预约处理器 + +- **职责**: 预约处理逻辑 + +### 11.6 处理器模块 (`douyin/handlers/`) + +#### 11.6.1 `douyin_popup_handler.py` - 弹窗处理器 + +- **职责**: 弹窗检测与处理 + +#### 11.6.2 `douyin_screenshot_handler.py` - 截图处理器 + +- **职责**: 截图处理逻辑 + +#### 11.6.3 `douyin_swipe_handler.py` - 滑动处理器 + +- **职责**: 滑动操作处理 + +### 11.7 工具模块 (`douyin/utils/`) + +#### 11.7.1 `douyin_config.py` - 配置管理 + +- **职责**: 配置加载和管理 + +#### 11.7.2 `douyin_helpers.py` - 辅助函数 + +- **职责**: 通用辅助函数 + +#### 11.7.3 `douyin_text_utils.py` - 文本工具 + +- **职责**: 文本处理工具(倒计时解析、价值提取等) + +--- + +## 12. 数据流和状态管理 + +### 12.1 数据流概述 + +项目的数据流主要分为以下几个阶段: + +1. **输入**: ADB截图 → 图像数据 +2. **处理**: 图像处理 → OCR识别 → 阶段诊断 → 决策 +3. **输出**: 点击操作 → 滑动操作 → 状态更新 + +### 12.2 主要数据流 + +#### 12.2.1 截图数据流 + +``` +ADB设备 + ↓ (adb exec-out screencap -p) +截图文件 (pic/screenshot.png) + ↓ (PIL.Image.open) +图像对象 (PIL.Image) + ↓ (转换为RGB) +RGB图像 (Image.Image) + ↓ (裁剪/处理) +处理后的图像 +``` + +#### 12.2.2 OCR数据流 + +``` +裁剪后的图像 + ↓ (OCR引擎识别) +OCR原始结果 (List) + ↓ (extract_ocr_content) +文本字符串 (str) + ↓ (文本处理) +结构化数据 (dict) +``` + +#### 12.2.3 阶段诊断数据流 + +``` +截图文件 + ↓ (并行像素检测) +像素检测结果 (dict) + ↓ (模板匹配) +模板匹配结果 (bool) + ↓ (OCR识别) +OCR识别结果 (str) + ↓ (综合判断) +阶段结果 (str) +``` + +#### 12.2.4 预约数据流 + +``` +福袋信息 + ↓ (判断是否高价值) +高价值判断 (bool) + ↓ (添加到预约队列) +预约对象 (dict) + ↓ (保存到文件) +state/reservations.json + ↓ (加载预约数据) +内存中的预约列表 + ↓ (处理预约窗口) +预约回退操作 +``` + +### 12.3 状态转换图 + +``` +[初始化] + ↓ +[主循环开始] + ↓ +[加载预约数据] + ↓ +[处理预约回退窗口] + ├─> 触发回退 → [回退到目标直播间] → [参与福袋] → [清除预约] + └─> 未触发 → 继续 + ↓ +[获取截图] + ↓ +[阶段诊断] + ├─> IN_LIVE_ROOM → [查找福袋] → [打开详情页] → [处理详情页] + ├─> FUDai_DETAIL → [获取福袋信息] → [判断是否参与] → [参与/跳过] + ├─> FUDai_RESULT → [检查开奖结果] → [领取奖品/关闭] + └─> 其他 → [导航到直播间] + ↓ +[更新状态] + ├─> 成功参与 → 更新 _last_successful_attend_ts + ├─> 添加预约 → 更新 reservations + └─> 等待开奖 → 设置 _waiting_for_lottery_result + ↓ +[检查超时] + ├─> 30分钟超时 → [返回推荐页] + └─> 未超时 → 继续 + ↓ +[主循环结束] + ↓ +[等待/继续循环] +``` + +--- + +## 13. 关键技术实现 + +### 13.1 像素检测技术 + +#### 13.1.1 原理 + +像素检测通过分析指定区域的像素颜色特征来判断UI元素的存在。主要步骤: + +1. **区域定义**: 基于基准分辨率(1080x2400)定义检测区域 +2. **坐标缩放**: 根据实际设备分辨率缩放坐标 +3. **像素采样**: 在检测区域内采样像素点 +4. **特征匹配**: 根据颜色特征(RGB值)判断是否符合预期 +5. **阈值判断**: 计算符合特征的像素占比,与阈值比较 + +#### 13.1.2 实现示例 + +```python +def detect_attend_button_red_area( + pic_rgb: Image.Image, + red_ratio_threshold: float = 0.25, + return_info: bool = False +) -> bool | tuple[bool, dict]: + """检测参与按钮红色区域""" + width, height = pic_rgb.size + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + # 定义检测区域(基于1080x2400) + x1 = int(100 * scale_x) + y1 = int(1500 * scale_y) + x2 = int(980 * scale_x) + y2 = int(1700 * scale_y) + + # 采样像素 + red_count = 0 + total_samples = 0 + step_x = max(1, (x2 - x1) // 10) + step_y = max(1, (y2 - y1) // 10) + + for y in range(y1, y2, step_y): + for x in range(x1, x2, step_x): + r, g, b = pic_rgb.getpixel((x, y)) + total_samples += 1 + # 红色按钮特征:R >= 245 且 R 明显大于 G 和 B + if r >= 245 and (r - g) >= 50 and (r - b) >= 50: + red_count += 1 + + # 计算红色占比 + red_ratio = red_count / total_samples if total_samples > 0 else 0.0 + result = red_ratio >= red_ratio_threshold + + return result if not return_info else (result, { + "red_ratio": red_ratio, + "red_count": red_count, + "total_samples": total_samples + }) +``` + +#### 13.1.3 并行像素检测 + +使用 `ThreadPoolExecutor` 并行执行多个像素检测任务: + +```python +def read_pixel_stage_state_from_screenshot( + pic_path: str, + ... +) -> dict[str, bool]: + """并行执行所有像素检测""" + pic_rgb = _safe_open_screenshot_rgb(pic_path) + + # 定义检测任务 + detection_tasks = { + "has_coupon_bg": lambda pic: detect_coupon_popup_background(pic, ...), + "has_redpacket_bg": detect_redpacket_popup_background, + "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(pic, ...), + "has_attend_button_red": lambda pic: detect_attend_button_red_area(pic, ...), + "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(pic, ...), + "has_fudai_detail": lambda pic: detect_fudai_detail_page(pic, ...), + } + + # 使用线程池并行执行 + with ThreadPoolExecutor(max_workers=6) as executor: + futures = { + key: executor.submit(task, pic_rgb) + for key, task in detection_tasks.items() + } + + # 等待所有任务完成 + results = {} + for key, future in futures.items(): + try: + result = future.result(timeout=2.0) + results[key] = result if isinstance(result, bool) else result[0] + except Exception as e: + results[key] = False + + return results +``` + +### 13.2 模板匹配技术 + +#### 13.2.1 原理 + +模板匹配使用OpenCV的模板匹配算法,在截图中查找模板图片的位置。主要步骤: + +1. **模板准备**: 准备模板图片(如福袋图标、直播间图标等) +2. **图像预处理**: 将截图和模板转换为灰度图 +3. **模板匹配**: 使用 `cv2.matchTemplate()` 进行匹配 +4. **阈值判断**: 计算匹配分数,与阈值比较 + +#### 13.2.2 实现示例 + +```python +import cv2 +import numpy as np +from PIL import Image + +def detect_fudai_detail_page( + pic_rgb: Image.Image, + template_threshold: float = 0.7, + ... +) -> bool: + """使用模板匹配检测福袋详情页""" + try: + # 加载模板图片 + template_path = "assets/fudai_detail_template.png" + template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) + if template is None: + return False + + # 转换截图 + pic_gray = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2GRAY) + + # 模板匹配 + result = cv2.matchTemplate(pic_gray, template, cv2.TM_CCOEFF_NORMED) + min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) + + # 判断匹配分数 + return max_val >= template_threshold + except Exception: + return False +``` + +### 13.3 OCR识别技术 + +#### 13.3.1 OCR引擎选择 + +项目支持两种OCR引擎: + +1. **EasyOCR**(优先): 速度快,识别准确率高 +2. **PaddleOCR**(回退): 兼容性好,支持中文 + +#### 13.3.2 并行OCR处理 + +使用 `ThreadPoolExecutor` 并行执行多个OCR任务: + +```python +def get_fudai_contain(analyser, renwu: int = 2): + """并行OCR获取福袋信息""" + + def ocr_content(): + analyser.operation.cut_pic(..., name="福袋内容") + return analyser.operation.analyse_pic_word("福袋内容") + + def ocr_countdown_mm(): + analyser.operation.cut_pic(..., name="倒计时分钟") + return analyser.operation.analyse_pic_digits("倒计时分钟") + + def ocr_countdown_ss(): + analyser.operation.cut_pic(..., name="倒计时秒数") + return analyser.operation.analyse_pic_digits("倒计时秒数") + + def ocr_value(): + analyser.operation.cut_pic(..., name="奖品价值") + return analyser.operation.analyse_pic_digits("奖品价值") + + def ocr_button(): + analyser.operation.cut_pic(..., name="参与按钮") + return analyser.operation.analyse_pic_word("参与按钮") + + # 并行执行所有OCR任务 + with ThreadPoolExecutor(max_workers=6) as executor: + future_content = executor.submit(ocr_content) + future_countdown_mm = executor.submit(ocr_countdown_mm) + future_countdown_ss = executor.submit(ocr_countdown_ss) + future_value = executor.submit(ocr_value) + future_button = executor.submit(ocr_button) + + # 等待所有任务完成 + content = future_content.result() + countdown_mm = future_countdown_mm.result() + countdown_ss = future_countdown_ss.result() + value = future_value.result() + button_text = future_button.result() + + # 处理结果 + # ... +``` + +#### 13.3.3 OCR结果处理 + +```python +def extract_ocr_content(content: List, return_confidence: bool = False) -> str: + """从OCR结果中提取文本""" + texts = [] + confidences = [] + + for item in content: + if isinstance(item, (list, tuple)) and len(item) >= 2: + # EasyOCR格式: [[坐标], 文本, 置信度] + if len(item) >= 3: + text = item[1] + confidence = item[2] + # PaddleOCR格式: [[坐标], [文本, 置信度]] + elif len(item) >= 2 and isinstance(item[1], (list, tuple)): + text = item[1][0] + confidence = item[1][1] + else: + continue + + texts.append(text) + confidences.append(confidence) + + # 拼接文本 + result_text = " ".join(texts) + + if return_confidence: + avg_confidence = sum(confidences) / len(confidences) if confidences else 0.0 + return result_text, avg_confidence + + return result_text +``` + +### 13.4 并行处理技术 + +#### 13.4.1 线程池使用 + +项目使用 `concurrent.futures.ThreadPoolExecutor` 实现并行处理: + +```python +from concurrent.futures import ThreadPoolExecutor, as_completed + +# 创建线程池 +with ThreadPoolExecutor(max_workers=6) as executor: + # 提交任务 + futures = { + "task1": executor.submit(func1, arg1), + "task2": executor.submit(func2, arg2), + "task3": executor.submit(func3, arg3), + } + + # 等待所有任务完成 + results = {} + for key, future in futures.items(): + try: + results[key] = future.result(timeout=5.0) + except Exception as e: + results[key] = None + logger.error(f"任务{key}失败: {e}") +``` + +#### 13.4.2 并行处理场景 + +1. **像素检测**: 并行检测多个UI元素(弹窗、按钮等) +2. **OCR识别**: 并行识别多个文本区域(内容、倒计时、价值等) +3. **阶段诊断**: 并行执行多种检测方法(像素、模板、OCR) + +--- + +## 14. 扩展指南和最佳实践 + +### 14.1 添加新的检测方法 + +#### 14.1.1 添加像素检测函数 + +1. 在 `douyin/detection/douyin_pixel.py` 中添加新函数 +2. 在 `read_pixel_stage_state_from_screenshot()` 中添加检测任务 +3. 在阶段诊断中使用检测结果 + +**示例**: +```python +def detect_new_popup(pic_rgb: Image.Image, threshold: float = 0.5) -> bool: + """检测新弹窗""" + width, height = pic_rgb.size + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + # 定义检测区域 + x1 = int(100 * scale_x) + y1 = int(200 * scale_y) + x2 = int(980 * scale_x) + y2 = int(400 * scale_y) + + # 检测逻辑 + # ... + + return result +``` + +#### 14.1.2 添加模板匹配检测 + +1. 准备模板图片(放在 `assets/` 目录) +2. 在检测函数中使用 `cv2.matchTemplate()` +3. 在阶段诊断中调用检测函数 + +### 14.2 添加新的阶段类型 + +1. 在 `douyin/stage/douyin_stage.py` 中定义新阶段常量 +2. 在 `diagnose_stage_from_current_screen()` 中添加检测逻辑 +3. 在 `run_once_basic()` 中添加处理逻辑 + +**示例**: +```python +# 定义新阶段 +NEW_STAGE = "NEW_STAGE" + +# 在阶段诊断中添加检测 +def diagnose_stage_from_current_screen(analyser): + # ... 现有检测逻辑 + + # 检测新阶段 + if detect_new_stage(analyser): + return NEW_STAGE + + # ... + +# 在主循环中添加处理 +def run_once_basic(self): + # ... + stage = diagnose_stage_from_current_screen(self) + if stage == NEW_STAGE: + self._handle_new_stage() + # ... +``` + +### 14.3 添加新的配置项 + +1. 在 `config/config.json` 中添加配置项 +2. 在 `fudai_analyse.__init__()` 中初始化属性 +3. 在 `load_config()` 中加载配置 + +**示例**: +```python +# 在 __init__() 中 +self.new_config_item: bool = False + +# 在 load_config() 中 +self.new_config_item = self.config.get("new_config_item", False) +``` + +### 14.4 最佳实践 + +#### 14.4.1 错误处理 + +- 所有可能失败的操作都应该有异常处理 +- 使用 `try-except` 捕获异常,记录日志,返回默认值 +- 不要让异常中断主循环 + +#### 14.4.2 日志记录 + +- 使用统一的日志系统记录关键操作 +- 记录足够的上下文信息(参数、结果、错误等) +- 使用适当的日志级别(DEBUG、INFO、WARNING、ERROR) + +#### 14.4.3 性能优化 + +- 使用并行处理提高效率(像素检测、OCR识别) +- 避免频繁截图(使用最小间隔) +- 缓存识别结果(避免重复识别) + +#### 14.4.4 代码组织 + +- 使用模块化设计,功能拆分到独立模块 +- 使用Mixin模式组合功能 +- 保持函数职责单一,易于测试和维护 + +--- + +## 15. 关键文件索引和调试指南 + +### 15.1 关键文件索引 + +#### 15.1.1 入口文件 + +- **`run_cli.py`**: 命令行入口,初始化设备和分析器 +- **`gui/gui_app.py`**: Tkinter GUI入口 +- **`gui/web_gui.py`**: Web GUI入口 + +#### 15.1.2 核心文件 + +- **`douyin/core/douyin_fudai.py`**: 主调度器类 `fudai_analyse` +- **`douyin/core/douyin_main_flow.py`**: 主流程控制 +- **`douyin/core/douyin_flow_control.py`**: 流程控制辅助函数 + +#### 15.1.3 阶段诊断 + +- **`douyin/stage/douyin_stage.py`**: 阶段诊断核心逻辑 +- **`douyin/stage/douyin_stage_handler.py`**: 阶段处理逻辑 + +#### 15.1.4 检测模块 + +- **`douyin/detection/douyin_pixel.py`**: 像素检测函数 +- **`douyin/detection/douyin_detection.py`**: 综合检测逻辑 + +#### 15.1.5 福袋模块 + +- **`douyin/fudai/douyin_fudai_core.py`**: 福袋核心逻辑 +- **`douyin/fudai/douyin_fudai_detail.py`**: 福袋详情处理 +- **`douyin/fudai/douyin_fudai_finder.py`**: 福袋查找器 +- **`douyin/fudai/core/fudai_attend.py`**: 参与抽奖逻辑 +- **`douyin/fudai/core/fudai_result_checker.py`**: 开奖结果检查 + +#### 15.1.6 预约模块 + +- **`douyin/reservation/douyin_reservation_logic.py`**: 预约核心逻辑 +- **`douyin/reservation/douyin_reservation_handler.py`**: 预约处理器 + +#### 15.1.7 底层操作 + +- **`Underlying_Operations.py`**: 底层操作类(ADB、OCR、图像处理) + +#### 15.1.8 配置文件 + +- **`config/config.json`**: 主配置文件 +- **`state/reservations.json`**: 预约状态文件 + +### 15.2 调试指南 + +#### 15.2.1 启用调试日志 + +在 `config.json` 中设置: + +```json +{ + "logging": { + "level": "DEBUG", + "debug_detail_level": "detailed" + } +} +``` + +#### 15.2.2 保存调试图像 + +在 `config.json` 中设置: + +```json +{ + "fudai_detail_save_debug_images": true, + "debug_captures": { + "enabled": true, + "keep_days": 3 + } +} +``` + +调试图像保存在 `pic/debug/` 目录下。 + +#### 15.2.3 常见问题排查 + +**问题1: 截图失败** +- 检查ADB连接: `adb devices` +- 检查设备是否锁屏 +- 检查文件系统权限 + +**问题2: OCR识别失败** +- 检查OCR引擎是否初始化成功 +- 检查图片质量 +- 检查裁剪区域是否正确 + +**问题3: 阶段诊断错误** +- 检查截图是否成功 +- 检查检测阈值是否合适 +- 查看调试图像确认检测区域 + +**问题4: 预约回退失败** +- 检查预约数据是否正确 +- 检查直播间标题匹配 +- 检查滑动次数是否超限 + +#### 15.2.4 日志分析 + +日志文件位置: +- **统一日志**: `logs/unified_YYYY-MM-DD.log` +- **操作日志**: `logs/action_YYYY-MM-DD.log` + +关键日志标签: +- `[截图]`: 截图相关操作 +- `[阶段诊断]`: 阶段诊断结果 +- `[福袋查找]`: 福袋查找过程 +- `[OCR识别]`: OCR识别结果 +- `[预约]`: 预约相关操作 +- `[参与]`: 参与抽奖操作 + +#### 15.2.5 性能分析 + +启用性能跟踪: + +```json +{ + "logging": { + "performance_tracking": { + "enabled": true, + "track_function_calls": true, + "slow_operation_threshold_ms": 100 + } + } +} +``` + +查看日志中的执行时间信息,识别性能瓶颈。 + +#### 15.2.6 阶段诊断详细步骤说明 + +阶段诊断是项目的核心功能之一,以下是详细的步骤说明: + +**步骤0: 检测直播间(最优先)** + +1. **像素检测**(优先级最高) + - 检测右上角区域(60%-100%宽度,0%-40%高度)的像素特征 + - 检测x图标(白色/浅色)和xin图标(粉色/红色) + - 计算置信度(0.0~1.0) + - 如果置信度 >= `live_room_match_threshold`(默认0.8),判定为在直播间 + +2. **模板匹配**(像素检测失败时) + - 使用OpenCV模板匹配检测直播间图标 + - 匹配模板:`assets/x.png` 和 `assets/xin.png` + - 计算匹配分数(0.0~1.0) + - 如果分数 >= `live_room_match_threshold`,判定为在直播间 + +3. **OCR回退**(前两种方法都失败时) + - 裁剪直播间标题区域 + - OCR识别标题文本 + - 如果识别到文本,判定为在直播间 + +**步骤1: 并行像素检测** + +使用 `ThreadPoolExecutor` 并行执行以下检测: + +1. **优惠券弹窗检测** (`has_coupon_bg`) + - 检测区域:底部中央区域 + - 方法:模板匹配 + 像素检测 + - 阈值:`coupon_template_match_threshold`(默认0.4) + +2. **红包弹窗检测** (`has_redpacket_bg`) + - 检测区域:中央区域 + - 方法:像素检测(红色背景) + +3. **开奖结果弹窗检测** (`has_lucky_draw_result`) + - 检测区域:"我知道了"按钮区域(181, 1261)- (890, 1389) + - 方法:像素检测(红色占比) + - 阈值:`lucky_draw_red_ratio_threshold`(默认0.8) + +4. **参与按钮检测** (`has_attend_button_red`) + - 检测区域:参与按钮区域 + - 方法:像素检测(红色占比) + - 阈值:`attend_button_red_ratio_threshold`(默认0.25) + +5. **粉丝团加入按钮检测** (`has_fansclub_join_red`) + - 检测区域:粉丝团加入按钮区域 + - 方法:像素检测(红色占比) + - 阈值:`fansclub_join_red_ratio_threshold`(默认0.25) + +6. **福袋详情页检测** (`has_fudai_detail`) + - 检测区域:福袋详情页特征区域 + - 方法:模板匹配 + 像素检测 + - 阈值:`fudai_detail_template_threshold`(默认0.54) + +**步骤2: 根据检测结果判断阶段** + +1. **如果检测到开奖结果弹窗** → 返回 `FUDai_RESULT` +2. **如果检测到福袋详情页** → 返回 `FUDai_DETAIL` +3. **如果检测到粉丝团加入按钮** → 返回 `FANSCLUB_JOIN` +4. **如果检测到优惠券/红包弹窗** → 处理弹窗后继续 +5. **如果在直播间** → 返回 `IN_LIVE_ROOM` +6. **其他情况** → 返回 `UNKNOWN` 或 `RECOMMEND_PAGE` + +**超时保护**: +- 总诊断时间不超过 `stage_diag_max_time`(默认5.0秒) +- 每个步骤不超过 `stage_diag_max_step_time`(默认2.0秒) +- 超时后返回 `UNKNOWN` + +#### 15.2.7 常见错误代码和解决方案 + +| 错误代码/现象 | 可能原因 | 解决方案 | +|------------|---------|---------| +| `截图失败` | ADB连接断开、设备锁屏 | 检查ADB连接、解锁设备 | +| `OCR识别失败` | OCR引擎未初始化、图片质量差 | 检查OCR引擎、提高图片质量 | +| `阶段诊断超时` | 设备响应慢、检测步骤过多 | 增加超时时间、优化检测逻辑 | +| `福袋查找失败` | 福袋图标未出现、检测阈值过高 | 降低检测阈值、增加等待时间 | +| `预约回退失败` | 找不到目标直播间、滑动次数超限 | 检查预约数据、增加最大滑动次数 | +| `参与失败` | 按钮状态识别错误、前置条件未满足 | 检查按钮识别、处理前置条件 | + +#### 15.2.8 性能优化建议 + +1. **减少截图频率** + - 使用 `screenshot_diagnose_min_interval_seconds` 控制最小间隔 + - 缓存截图结果(如果阶段未变化) + +2. **优化OCR识别** + - 使用并行OCR处理多个区域 + - 缓存识别结果(5秒内有效) + - 使用EasyOCR(比PaddleOCR快) + +3. **优化像素检测** + - 使用并行检测多个UI元素 + - 减少采样点数(在保证准确性的前提下) + - 使用合适的阈值(避免过度检测) + +4. **优化阶段诊断** + - 优先使用快速检测方法(像素检测 > 模板匹配 > OCR) + - 设置合理的超时时间 + - 避免重复检测(使用缓存) + +#### 15.2.9 调试技巧 + +1. **启用详细日志** + ```json + { + "stage_diag_verbose": true, + "logging": { + "level": "DEBUG" + } + } + ``` + +2. **保存调试图像** + ```json + { + "fudai_detail_save_debug_images": true, + "debug_captures": { + "enabled": true + } + } + ``` + +3. **查看日志文件** + - 统一日志:`logs/unified_YYYY-MM-DD.log` + - 操作日志:`logs/action_YYYY-MM-DD.log` + - 使用 `grep` 或文本编辑器搜索关键词 + +4. **使用调试截图** + - 调试截图保存在 `pic/debug_captures/YYYY-MM-DD/` 目录 + - 文件名包含时间戳和操作类型 + - 可以查看OCR识别前后的图像对比 + +5. **性能分析** + - 启用性能跟踪:`"performance_tracking": {"enabled": true}` + - 查看日志中的执行时间信息 + - 识别性能瓶颈(慢操作阈值:100ms) + +--- + +## 16. 高级主题和深入理解 + +### 16.1 Mixin模式详解 + +#### 16.1.1 Mixin模式原理 + +Mixin模式是一种多重继承的设计模式,用于在不使用传统继承的情况下组合功能。 + +**优点**: +- **功能模块化**: 每个Mixin负责特定功能,职责清晰 +- **代码复用**: 可以在多个类中复用相同的功能 +- **灵活组合**: 可以根据需要组合不同的Mixin +- **易于测试**: 每个Mixin可以独立测试 + +**实现方式**: +```python +class fudai_analyse( + NavigationMixin, # 导航功能 + StageDetectionMixin, # 阶段检测 + PopupHandlerMixin, # 弹窗处理 + LotteryResultMixin, # 抽奖结果 + RoomUtilsMixin, # 直播间工具 + MainLogicMixin, # 主逻辑 +): + def __init__(self): + # 初始化所有Mixin需要的属性 + # ... +``` + +#### 16.1.2 Mixin方法解析顺序(MRO) + +Python使用C3线性化算法确定方法解析顺序(MRO): + +```python +# 查看MRO +print(fudai_analyse.__mro__) +# 输出: ( +# , +# , +# , +# , +# , +# , +# , +# , +# +# ) +``` + +**方法查找顺序**: +1. 首先在 `fudai_analyse` 类中查找 +2. 然后按照MRO顺序在各个Mixin中查找 +3. 找到第一个匹配的方法后停止 + +### 16.2 坐标系统详解 + +#### 16.2.1 基准分辨率 + +项目使用 **1080x2400** 作为基准分辨率,所有坐标都基于这个分辨率定义。 + +**原因**: +- 抖音App在不同设备上的UI布局是相对固定的 +- 使用基准分辨率可以适配不同设备 +- 通过缩放比例转换到实际分辨率 + +#### 16.2.2 坐标缩放 + +```python +def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]: + """从基准分辨率缩放到实际分辨率""" + rx = self.resolution_ratio_x # 实际宽度 + ry = self.resolution_ratio_y # 实际高度 + scaled_x = int(base_x * rx // 1080) + scaled_y = int(base_y * ry // 2400) + return scaled_x, scaled_y +``` + +**示例**: +- 基准坐标: (540, 1200)(屏幕中心) +- 实际分辨率: 1440x3200 +- 缩放后: (720, 1600) + +#### 16.2.3 Y轴偏移(y_pianyi) + +某些设备可能有状态栏或导航栏,需要Y轴偏移: + +```python +actual_y = base_y + y_pianyi +``` + +### 16.3 并行处理详解 + +#### 16.3.1 ThreadPoolExecutor使用 + +```python +from concurrent.futures import ThreadPoolExecutor, as_completed + +# 创建线程池 +with ThreadPoolExecutor(max_workers=6) as executor: + # 提交任务 + futures = { + "task1": executor.submit(func1, arg1), + "task2": executor.submit(func2, arg2), + "task3": executor.submit(func3, arg3), + } + + # 等待所有任务完成 + results = {} + for key, future in futures.items(): + try: + results[key] = future.result(timeout=5.0) + except Exception as e: + results[key] = None + logger.error(f"任务{key}失败: {e}") +``` + +#### 16.3.2 线程池大小选择 + +- **CPU密集型任务**: `max_workers = CPU核心数` +- **I/O密集型任务**: `max_workers = CPU核心数 * 2` 或更多 +- **混合任务**: 根据实际情况调整 + +**本项目**: +- OCR识别:I/O密集型(文件读取、图像处理) +- 像素检测:CPU密集型(像素计算) +- 综合使用:`max_workers=6`(平衡性能和资源) + +### 16.4 OCR引擎选择 + +#### 16.4.1 EasyOCR vs PaddleOCR + +| 特性 | EasyOCR | PaddleOCR | +|------|---------|-----------| +| 速度 | 快 | 慢 | +| 准确率 | 高 | 高 | +| 内存占用 | 中等 | 高 | +| 初始化时间 | 短 | 长 | +| 中文支持 | 好 | 好 | +| GPU支持 | 是 | 是 | + +**选择策略**: +1. **优先使用EasyOCR**: 速度快,准确率高 +2. **回退到PaddleOCR**: EasyOCR初始化失败时 +3. **CPU模式**: 默认使用CPU模式(避免GPU依赖) + +#### 16.4.2 OCR预处理 + +为了提高OCR识别率,项目使用多种预处理方法: + +1. **颜色转换** (`change_color`): + - `0`: 不转换(RGB) + - `1`: 转换为黑白(提高数字识别率) + - `2`: 其他转换 + +2. **图像增强**: + - 对比度增强 + - 亮度调整 + - 去噪处理 + +3. **区域裁剪**: + - 精确裁剪文本区域 + - 去除无关背景 + - 提高识别准确率 + +### 16.5 状态持久化机制 + +#### 16.5.1 预约状态持久化 + +预约数据存储在 `state/reservations.json` 文件中: + +```json +{ + "reservations": [ + { + "room_title": "直播间标题", + "room_pos": {"x": 540, "y": 1200, "title": "直播间标题"}, + "lottery_time_ts": 1704067200.0, + "prize_value_yuan": 500.0, + "fudai_x": 900, + "created_ts": 1704066900.0 + } + ], + "updated_at": 1704067200.0 +} +``` + +**持久化时机**: +- 添加预约时 +- 清理过期预约时 +- 预约回退时 +- 队列裁剪时 + +**加载时机**: +- 程序启动时 +- 每次循环开始时 + +#### 16.5.2 运行时状态 + +大部分状态标志存储在内存中(重启后丢失): +- `_waiting_for_lottery_result`: 等待开奖状态 +- `_last_successful_attend_ts`: 最后成功参与时间 +- `_swipe_times`: 滑动次数 +- `_last_diag_stage`: 上次诊断阶段 + +**恢复机制**: +- 预约数据:从文件加载 +- 运行时状态:重新初始化 + +### 16.6 预约系统完整流程详解 + +#### 16.6.1 预约添加流程 + +1. **检测高价值福袋**: + - 在福袋详情页获取福袋信息(价值、倒计时等) + - 判断价值是否 >= `high_value_fudai_threshold_yuan` + - 判断倒计时是否 > `high_value_fudai_join_ahead_seconds` + +2. **创建预约记录**: + ```python + reservation = { + "room_title": room_title, # 直播间标题(规范化) + "room_title_raw": room_title_raw, # 直播间标题(原始) + "room_pos": room_pos, # 直播间位置 + "pos_seen": room_pos, # 看到的位置(用于回退) + "lottery_time_ts": time.time() + countdown_seconds, # 开奖时间戳 + "prize_value_yuan": prize_value_yuan, # 奖品价值 + "fudai_x": fudai_x, # 福袋图标X坐标 + "created_ts": time.time() # 创建时间戳 + } + ``` + +3. **添加到预约队列**: + - 检查队列是否已满(`len(reservations) >= max_reservations`) + - 如果已满,裁剪队列(保留优先级最高的N个) + - 添加新预约到队列 + +4. **排序预约队列**: + - 主排序键: `lottery_time_ts`(升序,最早开奖的优先) + - 次排序键: `prize_value_yuan`(降序,价值高的优先) + - 第三排序键: `created_ts`(升序,最早创建的优先) + +5. **保存到文件**: + - 调用 `write_reservations_state()` 保存到 `state/reservations.json` + +#### 16.6.2 预约回退流程 + +1. **检查预约窗口**: + - 每次循环开始时调用 `process_reservation_attend_window()` + - 遍历预约列表,计算距离开奖时间 + - 如果 `remaining_seconds <= high_value_fudai_join_ahead_seconds`,触发回退 + +2. **查找目标直播间**: + - 调用 `find_room_pos_by_title()` 查找目标直播间位置 + - 如果找到,获取目标位置 `target_pos` + +3. **计算回退方向和次数**: + - 计算位置差: `pos_diff = target_pos - current_pos` + - 如果 `pos_diff < 0`,向上回退(减少位置) + - 如果 `pos_diff > 0`,向下切换(增加位置) + +4. **执行回退**: + - 向上回退: 调用 `swipe_down_back_from_live()` N次 + - 向下切换: 调用 `swipe_up_to_next_live()` N次 + - 每次滑动后延迟 `reservation_back_swipe_delay` 秒 + +5. **设置回退标志**: + - 设置 `_reservation_back_direct_attend = True` + - 设置 `reservation_focus_until_ts = lottery_time_ts + 60` + - 设置 `_skip_record_title_during_seek = True`(避免重复记录标题) + +6. **验证回退结果**(可选): + - 如果启用 `reservation_back_verify_enabled`,验证是否在目标直播间 + - 通过OCR识别直播间标题,与预约的 `room_title` 比较 + +#### 16.6.3 预约直接参与流程 + +1. **检查预约队列**: + - 如果预约队列为空,回退到正常流程(调用 `_handle_in_fudai_detail()`) + +2. **检查福袋是否过期**: + - 获取预约的 `future_ts`(开奖时间戳,从 `first_reservation.get("future_ts")` 获取) + - 计算过期阈值: `expired_threshold = future_ts + poll_before_seconds` + - 如果当前时间 > 过期阈值,清除标志并退出 + - 调用 `cleanup_expired_reservations()` 从预约队列中移除过期预约 + +3. **步骤1: 查找并打开福袋详情**: + - 调用 `find_and_open_fudai_detail()` 查找并打开福袋详情 + - 如果未找到,回退到正常流程 + - 等待详情页加载(0.5秒,减少延迟) + +4. **步骤2: 检测参与按钮**: + - 获取截图(`operation.get_screenshot()`) + - 读取截图文件(`path_config.get_screenshot_path()`) + - 调用 `detect_attend_button_red_area()` 检测参与按钮(返回 `(has_button, button_info)` 元组) + - 如果未检测到按钮,回退到正常流程 + +5. **步骤3: 点击参与按钮**: + - 计算参与按钮坐标(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) + - 根据设备分辨率缩放坐标: `attend_x = int(543 * rx / 1080)`, `attend_y = int(2070 * ry / 2400)` + - 点击参与按钮(`operation.click(device_id, attend_x, attend_y)`) + - 等待点击后的响应(0.8秒,减少延迟) + +6. **步骤4: 验证参与状态**(详细验证逻辑): + - **再次查找并点击福袋图标**: + - 调用 `find_and_open_fudai_detail()` 再次查找福袋图标 + - 如果未找到,可能已参与成功(记录日志,继续执行) + - **如果找到福袋图标**: + - 等待详情页加载(0.5秒) + - 获取截图并检测按钮状态 + - 调用 `detect_attend_button_red_area()` 再次检测参与按钮 + - 如果仍检测到按钮,可能参与失败,回退到正常流程 + - 如果未检测到按钮,说明参与成功 + +7. **步骤5: 参与成功,设置开奖等待状态并从预约队列中移除**: + - **设置开奖等待状态**: + - 计算剩余秒数: `remain_seconds = max(0, future_ts - current_time)` + - 如果 `remain_seconds > 0`,设置 `_waiting_for_lottery_result = True` + - 设置 `_lottery_result_expected_ts = future_ts - 13.0`(提前13秒检查开奖结果) + - **设置锁定期**: + - 计算锁定期: `reservation_focus_until_ts = future_ts + max(0.0, poll_before)` + - 防止过早切换直播间 + - **从预约队列中移除已参与的预约**: + - 遍历预约队列,匹配 `future_ts`(允许5秒误差: `abs(res_future_ts - future_ts) <= 5.0`) + - 移除匹配的预约,保留不匹配的预约 + - 记录移除日志 + - **清除标志**: + - 清除 `_reservation_back_direct_attend = False` + - 清除 `reservation_after_action_pending = False` + +#### 16.6.4 预约队列管理 + +**队列裁剪**: +- 当队列长度超过 `high_value_fudai_max_reservations` 时 +- 保留优先级最高的N个预约(按排序规则) +- 丢弃优先级最低的预约 + +**过期清理**: +- 每次处理预约窗口时检查 +- 如果 `lottery_time_ts <= 当前时间`,则清理该预约 +- 调用 `cleanup_expired_reservations()` 清理过期预约 + +**队列排序**: +- 每次添加预约后自动排序 +- 确保最早开奖的预约在队列最前面 + +#### 16.6.5 预约聚焦机制 + +预约回退后,需要聚焦到目标直播间,直到开奖完成: + +1. **设置聚焦时间戳**: + - `reservation_focus_until_ts = lottery_time_ts + 60` + - 聚焦到开奖后60秒(确保开奖结果处理完成) + +2. **聚焦期间限制**: + - 不允许上划离开预约直播间(`swipe_up_to_next_live()` 中检查) + - 如果 `current_time < reservation_focus_until_ts`,禁止上划 + +3. **聚焦结束后**: + - 清除聚焦标志 + - 恢复正常流程 + +### 16.7 直播间位置映射机制 + +#### 16.7.1 映射表结构 + +运行时映射表存储在 `analyser._room_pos_to_title_map` 中: + +```python +_room_pos_to_title_map: Dict[int, Tuple[str, str]] = { + 0: ("直播间标题1", "直播间标题1(原始)"), + 1: ("直播间标题2", "直播间标题2(原始)"), + 2: ("直播间标题3", "直播间标题3(原始)"), + ... +} +``` + +**键**: `room_pos`(直播间位置,整数) +**值**: `(room_title, room_title_raw)`(标题元组) + +#### 16.7.2 映射表更新 + +1. **进入直播间时**: + - 调用 `record_room_title_and_pos()` 记录标题和位置 + - 更新映射表: `_room_pos_to_title_map[room_pos] = (room_title, room_title_raw)` + +2. **切换直播间时**: + - 更新 `room_pos`(增加或减少) + - 记录新直播间的标题和位置 + +3. **回退到推荐页时**: + - 重置 `room_pos = 0` + - 清空映射表(可选,或保留历史记录) + +#### 16.7.3 映射表查找 + +使用 `find_room_pos_by_title()` 查找目标直播间位置: + +1. **规范化标题**: 规范化目标标题和记录的标题 +2. **匹配算法**: + - 完全匹配(分数 = 1.0) + - 子串匹配(分数 = 0.8) + - 相似度匹配(使用 `difflib.SequenceMatcher`) +3. **选择最佳匹配**: 选择匹配分数 >= 0.6 且最高的位置 + +--- + +## 17. 预约验证和错误处理模块 + +### 17.1 预约验证模块 (`douyin_reservation_verify.py`) + +预约验证模块提供回退到预约直播间后的详细校验功能,确保在正确的直播间和正确的福袋。 + +#### 17.1.1 `match_reservation(item, detail) -> Tuple[bool, str, Dict]` + +- **作用**: 校验回退后的福袋详情是否匹配预约记录 +- **匹配策略**: + 1. **观看任务检测**: 优先检测是否为"观看X分钟"类任务,如果是则直接判为不匹配 + 2. **future_ts验证**: 必须同时有 `expected_future` 和 `actual_future`,否则无法确认回退成功 + 3. **价值或内容匹配**(二选一命中即可): + - 价值匹配: 允许25%误差或至少50元误差 + - 内容匹配: 子串匹配(`expected_content in actual_content` 或 `actual_content in expected_content`) + 4. **future_ts精确匹配**: + - 正常情况下 `future_diff <= 180` 秒 + - 如果 `future_diff > 180` 但 `<= 1200` 且价值+内容都匹配,允许放宽匹配(`future_mismatch_relaxed`) + +**匹配结果**: +- `(True, "ok", debug_dict)`: 完全匹配 +- `(True, "future_mismatch_relaxed", debug_dict)`: 放宽匹配(future_ts偏差较大但价值+内容匹配) +- `(False, "watch_task_detected", debug_dict)`: 检测到观看任务 +- `(False, "future_missing", debug_dict)`: future_ts缺失 +- `(False, "content_or_value_mismatch", debug_dict)`: 价值和内容都不匹配 +- `(False, "future_mismatch", debug_dict)`: future_ts偏差过大 + +#### 17.1.2 `validate_back_to_reservation(analyser, item, quick=False, max_checks=3) -> Tuple[bool, Optional[Tuple]]` + +- **作用**: 回退后校验直播间标题,确保在正确的直播间 +- **验证流程**: + 1. **检查验证开关**: 如果 `reservation_back_verify_enabled = False`,直接返回 `True` + 2. **标题规范化**: 使用 `_normalize_room_title()` 规范化标题,去除无关词 + 3. **运行时映射表验证**: 从 `_room_pos_to_title_map` 获取目标位置的记录标题,增强验证信心 + 4. **读取当前标题**: 调用 `read_live_room_title_core()` 读取当前直播间标题 + 5. **相似度计算**: 使用 `difflib.SequenceMatcher` 计算标题相似度 + 6. **匹配判断**: + - 如果 `expected_title in current_title` 或 `current_title in expected_title` 或 `ratio >= 0.45`,验证通过 + - 如果标题不匹配(`ratio < 0.45`),尝试根据映射表找到正确位置并回退 + 7. **自动回退**: 如果标题不匹配,调用 `_find_room_pos_by_title()` 和 `_seek_reservation_room()` 自动回退到正确位置 + +**验证结果**: +- `(True, None)`: 验证通过 +- `(False, None)`: 验证失败(标题不匹配且无法自动回退) + +### 17.2 预约错误处理工具模块 (`reservation_error_utils.py`) + +预约错误处理工具模块提供统一的预约相关错误处理和日志记录功能。 + +#### 17.2.1 `format_reservation_context(item=None, reservations=None, **kwargs) -> Dict[str, Any]` + +- **作用**: 格式化预约上下文信息,用于错误日志记录 +- **返回内容**: + - `reservation_item`: 预约项信息(future_ts、prize_value_yuan、room_title等) + - `queue_info`: 预约队列信息(队列长度、前5个预约项) + - 其他上下文信息(通过 `**kwargs` 传入) + +#### 17.2.2 `log_reservation_error(analyser, error, context, level="WARNING", stage="") -> None` + +- **作用**: 统一的预约错误日志记录函数 +- **参数**: + - `analyser: Any`: 分析器对象 + - `error: Exception`: 异常对象 + - `context: Dict[str, Any]`: 错误上下文信息字典 + - `level: str`: 日志级别(ERROR/WARNING/INFO) + - `stage: str`: 操作阶段描述(如"添加预约"、"回退验证"等) +- **功能**: + - 构建详细的错误信息(错误类型、错误消息、上下文信息) + - 对于严重错误(ERROR级别),添加调用栈信息 + - 调用 `analyser._log_kv()` 记录日志 + +#### 17.2.3 `safe_write_state(write_callback, analyser=None, context=None) -> bool` + +- **作用**: 安全的状态文件写入,带详细的错误处理 +- **错误处理**: + - `PermissionError`: 权限错误 + - `OSError`: 系统错误 + - `ValueError/TypeError`: 数据序列化错误 + - 其他异常: 未知错误 +- **返回**: `bool` - 是否成功写入 + +#### 17.2.4 `validate_reservation_item(item) -> Tuple[bool, Optional[str]]` + +- **作用**: 验证预约项数据的有效性 +- **验证内容**: + - 检查必需字段: `future_ts`, `prize_value_yuan` + - 验证 `future_ts` 格式和有效性(必须 > 0) + - 验证 `prize_value_yuan` 格式和有效性(必须 >= 0) +- **返回**: `(是否有效, 错误信息)` + +### 17.3 福袋筛选模块 (`fudai_filter.py`) + +福袋筛选模块包含福袋内容过滤、观看任务检测、配置筛选等功能。 + +#### 17.3.1 `check_contain(analyser, contains="") -> bool` + +- **作用**: 检查福袋内容是否命中"黑名单"关键词 +- **返回值语义**: + - `True`: "建议丢弃"(内容命中黑名单 `contains_not_want`) + - `False`: "可以保留"(未命中黑名单,或凌晨时段不做内容过滤) +- **特殊处理**: + - 凌晨时段(0-7点): 不对内容做要求(不过滤),直接返回 `False` + +#### 17.3.2 `is_watch_task_fudai(content) -> bool` + +- **作用**: 检测是否为"观看X分钟"类任务福袋 +- **匹配模式**: + - `(?:观看|看)(?:直播)?(?:.*?)?(?:\d+|[\u4e00-\u9fff]+)\s*分钟` + - `需要(?:观看|看)(?:.*?)?(?:\d+|[\u4e00-\u9fff]+)\s*分钟` + - `观看时长(?:.*?)?(?:\d+|[\u4e00-\u9fff]+)\s*分钟` + - `看播(?:.*?)?(?:\d+|[\u4e00-\u9fff]+)\s*分钟` +- **返回**: `True` 表示是"观看X分钟"类任务,应放弃 + +#### 17.3.3 `should_skip_fudai_by_config(analyser, detail) -> Tuple[bool, str]` + +- **作用**: 根据 `config.json` 中的阈值与关键词,判断是否应丢弃当前福袋 +- **筛选规则**: + 1. **单间模式**: 如果 `needswitch = False`,忽略所有阈值配置,永远不因为配置而跳过 + 2. **观看任务检测**: 优先检查是否为"观看X分钟"类任务,如果是则直接放弃 + 3. **价值过滤**: 如果 `prize_value_yuan < min_prize_value_yuan`,丢弃 + 4. **参与人数过滤**: + - 如果 `participants < min_participants`,丢弃 + - 如果 `participants > max_participants`,丢弃 + 5. **倒计时过滤**: + - 如果 `remain_seconds < skip_if_countdown_lt_seconds`,丢弃(不参与) + - 如果 `remain_seconds > skip_if_countdown_gt_seconds`,丢弃(不参与,但高价值福袋可预约) + 6. **内容关键词过滤**: 调用 `check_contain()` 检查是否命中黑名单 +- **返回**: `(skip, reason)` - 是否跳过、原因 + +#### 17.3.4 `basic_join_decision(analyser, detail) -> bool` + +- **作用**: 基础版参与决策,根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约 +- **决策流程**: + 1. **检查强制参与标志**: 如果 `_force_attend_after_reservation_back = True`,跳过验证 + 2. **检查状态**: 如果 `_last_fudai_detail_status == "coupon_popup"` 或 `"validation_failed"`,跳过处理 + 3. **数据验证**: 调用 `validate_fudai_detail()` 验证数据合理性 + 4. **单间模式**: 如果 `needswitch = False`,直接参与,不做任何阈值过滤 + 5. **检查重复参与**: 通过 `future_ts` 匹配 `_participated_fudai_future_ts`(允许5秒误差) + 6. **高价值判断**: 如果价值 >= `high_value_fudai_threshold_yuan`,标记为高价值福袋 + 7. **执行筛选**: 调用 `should_skip_fudai_by_config()` 检查是否应丢弃 + 8. **特殊处理高价值福袋**: + - 如果被倒计时过滤筛掉(倒计时 > 阈值),但价值达到高价值阈值: + - 检查是否为观看任务(如果是,直接丢弃) + - 如果剩余秒数 <= `high_value_fudai_join_ahead_seconds` 或强制参与,立即参与 + - 否则记录预约 + 9. **参与抽奖**: 如果通过筛选,调用 `attend_choujiang()` 参与抽奖 + 10. **丢弃处理**: 如果被筛掉,关闭详情页,如果允许切换直播间则切换 +- **返回**: `True` 表示已经参与或已处理完成,`False` 表示未参与 + +### 17.4 福袋结果检查模块 (`fudai_result_checker.py`) + +福袋结果检查模块提供开奖结果检测和奖励领取功能。 + +#### 17.4.1 `check_lucky_draw_result(analyser) -> int | bool` + +- **作用**: 检查开奖结果(是否中奖) +- **检测方法**: + - 使用像素检测检测开奖结果区域的颜色特征 + - 使用OCR识别开奖结果文字 +- **返回**: + - `1`: 中奖 + - `0`: 未中奖 + - `False`: 检测失败 + +#### 17.4.2 `check_have_reward_notice_confirm(analyser) -> bool` + +- **作用**: 检查是否有奖励通知确认按钮 +- **返回**: `bool` - 是否有奖励通知 + +#### 17.4.3 `check_in_order_confirm_page(analyser) -> bool` + +- **作用**: 检查是否在订单确认页面 +- **返回**: `bool` - 是否在订单确认页面 + +#### 17.4.4 `get_reward(analyser, reward_y: int = 0) -> None` + +- **作用**: 自动领取奖励 +- **流程**: + 1. 检测开奖结果 + 2. 如果中奖,点击领取按钮 + 3. 处理订单确认页面 + 4. 保存奖励截图 + +--- + +## 18. 核心处理函数详解补充 + +### 18.1 福袋详情处理函数补充 + +#### 18.1.1 `fudai_analyse._handle_in_fudai_detail() -> None` + +- **文件位置**: `douyin/core/douyin_fudai.py` +- **作用**: 已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑 +- **参数**: 无 +- **返回值**: 无 +- **调用位置**: `run_once_basic()` 中诊断到 `FUDai_DETAIL` 阶段时调用 +- **主要逻辑**: + 1. **检查是否是第二次打开福袋详情**: + - 如果 `_fudai_detail_first_read = True`,说明已经读取过详情 + - 第二次打开时,直接使用第一次保存的详情数据(`_last_fudai_detail_tuple`) + - 设置 `_current_fudai_future_ts`,供 `attend_choujiang()` 使用 + - 直接调用 `attend_choujiang()`,跳过验证和内容识别 + - 清除第一次读取标志,下次打开新福袋时重新识别 + 2. **第一次打开:完整读取详情**: + - 调用 `read_fudai_detail_with_retries()` 读取福袋详情 + - 进行数据验证(`validate_fudai_detail()`) + - 如果验证失败,关闭详情页并返回 + - 保存详情数据到 `_last_fudai_detail_tuple` + - 设置 `_fudai_detail_first_read = True` + - 调用 `basic_join_decision()` 进行筛选和参与决策 + +**关键状态变量**: +- `_fudai_detail_first_read`: 是否已经第一次读取过详情 +- `_last_fudai_detail_tuple`: 第一次读取的详情数据 +- `_current_fudai_future_ts`: 当前福袋的开奖时间戳 + +**优化说明**: +- 第二次打开时跳过OCR识别,直接使用第一次的数据,提高效率 +- 避免重复识别导致的延迟和资源浪费 + +#### 18.1.2 `fudai_analyse._handle_live_room_has_or_not_fudai() -> None` + +- **文件位置**: `douyin/core/douyin_fudai.py` +- **作用**: 在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号" +- **参数**: 无 +- **返回值**: 无 +- **调用位置**: `run_once_basic()` 中诊断到 `LIVE_ROOM` 阶段时调用 +- **主要逻辑**: + 1. **检查是否已验证过详情页**: + - 如果 `_fudai_detail_verified = True`,直接调用 `_handle_in_fudai_detail()`,不查找福袋 + 2. **检查锁定期和时间窗口**: + - 如果 `reservation_focus_until_ts > 当前时间` 且 `queue_full_waiting_at_earliest = True`: + - 检查预约队列中最早预约的时间窗口 + - 计算 `time_window_start_ts = future_ts - join_ahead_seconds` + - 如果当前时间 < 时间窗口开始时间,避免重复打开福袋详情,直接返回 + 3. **查找并打开福袋详情**: + - 调用 `find_and_open_fudai_detail()` 查找福袋图标并打开详情 + - 如果未找到福袋,调用 `handle_no_fudai_situation()` 处理无福袋情况 + - 如果成功打开详情,调用 `_handle_in_fudai_detail()` 处理详情 + +**关键配置参数**: +- `reservation_focus_until_ts`: 预约锁定期时间戳 +- `queue_full_waiting_at_earliest`: 队列满等待标志 +- `high_value_fudai_join_ahead_seconds`: 提前参与秒数 + +**优化说明**: +- 锁定期内避免重复打开福袋详情,减少不必要的操作 +- 时间窗口检查确保在合适的时机打开福袋详情 + +### 18.2 主流程控制函数补充 + +#### 18.2.1 `MainFlowController.fudai_choujiang(analyser, device_id, y_pianyi, needswitch, wait_minutes) -> None` + +- **文件位置**: `douyin/core/douyin_main_flow.py` +- **作用**: 主流程控制器的主循环入口(兼容原 `fudai_choujiang` 接口) +- **参数**: 同 `fudai_analyse.fudai_choujiang()` +- **返回值**: 无 +- **调用位置**: 可能被 `fudai_analyse.fudai_choujiang()` 内部调用 +- **主要逻辑**: + 1. **初始化设备信息**(同 `fudai_analyse.fudai_choujiang()`) + 2. **安全检查**: + - 最大循环次数限制:`max_loops = 10000` + - 最大运行时间限制:24小时 + - 如果达到限制,停止运行并记录日志 + 3. **主循环**: + - 循环计数:`loop_count` + - 每次循环调用 `MainFlowController.run_once_basic(analyser)` + - 等待指定时间(如果配置了 `wait_minutes`) + +**安全机制**: +- 防止无限循环:最大循环次数限制 +- 防止长时间运行:最大运行时间限制(24小时) +- 异常捕获:每次循环捕获异常,记录日志,继续运行 + +#### 18.2.2 `MainFlowController.run_once_basic(analyser) -> None` + +- **文件位置**: `douyin/core/douyin_main_flow.py` +- **作用**: 单轮基础抢福袋流程(包含简化版高价值福袋预约回退) +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: 无 +- **调用位置**: `MainFlowController.fudai_choujiang()` 中调用 +- **主要逻辑**: + - 由于 `run_once_basic` 方法非常复杂(1500+行),当前实现调用 `analyser.run_once_basic_original()` 保持原实现 + - 通过模块化组织,后续可以进一步拆分 + +**设计说明**: +- 保持向后兼容:调用原有的 `run_once_basic_original()` 方法 +- 模块化设计:为后续拆分做准备 + +### 18.3 流程控制辅助函数 + +#### 18.3.1 `douyin_flow_control.handle_stage_after_diagnosis(analyser, stage, seen, loop_count) -> bool` + +- **文件位置**: `douyin/core/douyin_flow_control.py` +- **作用**: 记录阶段诊断结果,当前不改变主流程走向 +- **参数**: + - `analyser: Any`: 分析器对象 + - `stage: str`: 阶段类型 + - `seen: str`: 阶段描述 + - `loop_count: int`: 循环计数 +- **返回值**: `bool` - 当前实现返回 `False`(不改变主流程) +- **调用位置**: 阶段诊断后调用(当前主要用于日志记录) + +**设计说明**: +- 预留接口:为后续扩展阶段处理逻辑做准备 +- 当前实现:仅记录日志,不改变主流程 + +#### 18.3.2 `douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) -> bool` + +- **文件位置**: `douyin/core/douyin_flow_control.py` +- **作用**: 在当前直播间查找福袋图标并尝试点击打开详情 +- **参数**: + - `analyser: Any`: 分析器对象 + - `room_pos_ref: List[int]`: 直播间位置引用(用于更新位置) +- **返回值**: `bool` - `True`=成功打开详情, `False`=未找到福袋或打开失败 +- **调用位置**: `_handle_live_room_has_or_not_fudai()` 中调用 +- **主要逻辑**: + 1. **检查等待开奖状态**: + - 如果 `_waiting_for_lottery_result = True`,跳过打开福袋详情,返回 `False` + 2. **像素检测福袋图标**: + - 在配置的最大等待时间内(`fudai_icon_max_wait_seconds`)重复检测 + - 使用 `check_have_fudai_with_ready_screenshot()` 检测福袋图标X坐标 + - 重试延迟:`fudai_icon_retry_delay_seconds` + 3. **点击福袋图标**: + - 如果找到福袋图标,点击打开详情 + - 等待详情页加载(`fudai_click_wait_seconds`) + 4. **验证是否成功打开**: + - 重新诊断阶段,确认是否在福袋详情页 + - 如果成功,返回 `True`;否则返回 `False` + +**配置参数**: +- `fudai_icon_max_wait_seconds`: 福袋图标最大等待时间(秒,默认5.0) +- `fudai_icon_retry_delay_seconds`: 福袋图标重试延迟(秒,默认0.6) +- `fudai_click_wait_seconds`: 点击福袋后等待时间(秒) + +**优化说明**: +- 重试机制:在最大等待时间内重复检测,提高找到福袋的概率 +- 状态检查:等待开奖时不打开新福袋,避免干扰 + +#### 18.3.3 `douyin_flow_control.handle_no_fudai_situation(analyser, ...) -> bool` + +- **文件位置**: `douyin/core/douyin_flow_control.py` +- **作用**: 在没有福袋时做简单的等待/上滑切换 +- **参数**: 多个参数,包括 `needswitch`、`reservations`、回调函数等 +- **返回值**: `bool` - 是否已处理 +- **调用位置**: `_handle_live_room_has_or_not_fudai()` 中未找到福袋时调用 +- **主要逻辑**: + 1. **检查是否允许切换直播间**: + - 如果 `needswitch = False`,只等待不切换 + 2. **处理预约回退窗口**: + - 如果启用预约功能,调用 `process_reservation_attend_window()` 检查是否需要回退 + 3. **切换直播间或等待**: + - 如果允许切换,调用 `swipe_up_switch_callback()` 上滑切换 + - 如果不允许切换,等待一段时间 + +**设计说明**: +- 灵活配置:根据 `needswitch` 决定是否切换直播间 +- 预约集成:与预约回退逻辑集成,统一处理无福袋情况 + +## 19. 工具函数和辅助模块详解 + +### 19.1 辅助函数模块 (`douyin_helpers.py`) + +`HelperFunctions` 类提供了一系列通用的工具方法,用于简化常见操作。 + +#### 19.1.1 `HelperFunctions.click(analyser, x, y) -> None` + +- **文件位置**: `douyin/utils/douyin_helpers.py` +- **作用**: 兼容原版 `fudai_analyse.click`,转发到底层 `operation.click` +- **参数**: + - `analyser: Any`: 分析器对象 + - `x: int`: X坐标 + - `y: int`: Y坐标 +- **返回值**: 无 +- **调用位置**: 所有需要点击的地方 +- **主要逻辑**: + - 调用 `analyser.operation.click(device_id, x, y)` 执行点击 + - 如果耗时超过0.1秒,记录日志(用于性能分析) + +#### 19.1.2 `HelperFunctions.read_pixel_stage_state(analyser, return_details=False) -> Union[Dict, Tuple]` + +- **文件位置**: `douyin/utils/douyin_helpers.py` +- **作用**: 读取像素阶段状态(封装 `read_pixel_stage_state_from_screenshot`) +- **参数**: + - `analyser: Any`: 分析器对象 + - `return_details: bool`: 是否返回每个检测步骤的详细信息(包括分数) +- **返回值**: + - `dict`: 检测结果(`return_details=False` 时) + - `tuple[dict, dict]`: (检测结果, 详细信息)(`return_details=True` 时) +- **调用位置**: 阶段诊断时调用 +- **主要逻辑**: + - 获取截图路径(`path_config.get_screenshot_path()`) + - 获取分辨率比例和Y偏移参数 + - 获取模板匹配阈值(优先使用福袋详情页专用阈值) + - 调用 `read_pixel_stage_state_from_screenshot()` 执行检测 + +#### 19.1.3 `HelperFunctions.check_lottery_result_by_ocr(analyser) -> Optional[str]` + +- **文件位置**: `douyin/utils/douyin_helpers.py` +- **作用**: 通过OCR识别开奖结果按钮区域,返回识别到的文本类型 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: `Optional[str]` - "我知道了" 或 "立即领取奖品" 或 `None` +- **调用位置**: 检查开奖结果时调用 +- **主要逻辑**: + 1. 裁剪开奖结果按钮区域 + 2. 使用OCR识别按钮文字 + 3. 根据识别结果返回对应的文本类型 + +#### 19.1.4 `HelperFunctions.handle_lottery_result_by_ocr(analyser, result_type, use_direct_click=False) -> None` + +- **文件位置**: `douyin/utils/douyin_helpers.py` +- **作用**: 根据OCR识别结果处理开奖结果 +- **参数**: + - `analyser: Any`: 分析器对象 + - `result_type: str`: "我知道了" 或 "立即领取奖品" + - `use_direct_click: bool`: 是否使用直接点击(默认False) +- **返回值**: 无 +- **调用位置**: 检查到开奖结果后调用 +- **主要逻辑**: + 1. 根据 `result_type` 确定点击坐标 + 2. 点击对应的按钮 + 3. 处理后续流程(如领取奖品) + +#### 19.1.5 `HelperFunctions.shot_and_diagnose(tag, msg, device_id, diagnose=True) -> None` + +- **文件位置**: `douyin/utils/douyin_helpers.py` +- **作用**: 截图并执行阶段诊断(兼容旧版调用方式) +- **参数**: + - `tag: str`: 日志标签 + - `msg: str`: 日志消息 + - `device_id: str`: 设备ID + - `diagnose: bool`: 是否执行阶段诊断(默认True) +- **返回值**: 无 +- **调用位置**: 需要截图和诊断的地方 +- **主要逻辑**: + 1. 获取截图(`operation.get_screenshot()`) + 2. 如果 `diagnose=True`,执行阶段诊断 + 3. 记录日志 + +### 19.2 截图管理模块 (`douyin_screenshot_manager.py`) + +截图管理模块提供双截图记录机制和调试图像保存功能。 + +#### 19.2.1 双截图记录机制 + +**实时操作截图** (`latest_attempt.png`): +- 每次识别操作都覆盖保存 +- 用于查看最新的操作截图 +- 路径: `pic/ocr/latest_attempt_{operation_type}.png` + +**成功识别存档截图** (`last_success.png`): +- 仅在成功时保存,不会被覆盖 +- 用于查看最近一次成功的识别截图 +- 路径: `pic/ocr/last_success_{operation_type}.png` + +#### 19.2.2 `save_latest_attempt(image, operation_type="") -> bool` + +- **作用**: 保存实时操作截图(覆盖保存) +- **参数**: + - `image: Image.Image`: PIL Image 对象 + - `operation_type: str`: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") +- **返回值**: `bool` - 是否保存成功 + +#### 19.2.3 `save_last_success(image, operation_type="") -> bool` + +- **作用**: 保存成功识别存档截图(不覆盖) +- **参数**: 同 `save_latest_attempt()` +- **返回值**: `bool` - 是否保存成功 + +#### 19.2.4 `save_debug_image(image, operation_type="", picname="", step="", coords=None, extra_info=None, annotate=True, auto_cleanup=True) -> Optional[str]` + +- **作用**: 保存调试图像,支持标注和自动清理 +- **参数**: + - `image: Image.Image`: PIL Image 对象 + - `operation_type: str`: 操作类型 + - `picname: str`: 图片名称 + - `step: str`: 步骤描述 + - `coords: Optional[Tuple[int, int, int, int]]`: 坐标区域 (x1, y1, x2, y2) + - `extra_info: Optional[dict]`: 额外信息 + - `annotate: bool`: 是否标注(默认True) + - `auto_cleanup: bool`: 是否自动清理旧文件(默认True) +- **返回值**: `Optional[str]` - 保存的文件路径 +- **主要功能**: + 1. 在图像上标注坐标区域(如果 `annotate=True`) + 2. 添加额外信息文本(OCR识别结果等) + 3. 保存到 `pic/debug_captures/` 目录 + 4. 自动清理旧文件(如果 `auto_cleanup=True`) + +#### 19.2.5 `cleanup_ocr_dir(keep_latest_attempt=True, keep_last_success=True, keep_success_files=True, max_files=50) -> int` + +- **作用**: 清理OCR目录中的旧文件 +- **参数**: + - `keep_latest_attempt: bool`: 是否保留最新尝试文件 + - `keep_last_success: bool`: 是否保留最后成功文件 + - `keep_success_files: bool`: 是否保留成功文件 + - `max_files: int`: 最大保留文件数(默认50) +- **返回值**: `int` - 清理的文件数量 + +### 19.3 截图处理模块 (`douyin_screenshot_handler.py`) + +#### 19.3.1 `ScreenshotHandler.scale_from_base(analyser, base_x, base_y) -> Tuple[int, int]` + +- **作用**: 从基准分辨率缩放坐标 +- **参数**: + - `analyser: Any`: 分析器对象 + - `base_x: int`: 基准X坐标(1080基准) + - `base_y: int`: 基准Y坐标(2400基准) +- **返回值**: `Tuple[int, int]` - 缩放后的坐标 +- **主要逻辑**: + - 根据设备分辨率比例缩放坐标 + - 考虑Y轴偏移(`y_pianyi`) + +#### 19.3.2 `ScreenshotHandler.save_step_screenshot(analyser, label) -> None` + +- **作用**: 保存当前截图到 `pic/steps/` 目录,供调试使用 +- **参数**: + - `analyser: Any`: 分析器对象 + - `label: str`: 标签(用于文件名) +- **返回值**: 无 +- **主要逻辑**: + 1. 获取最新截图 + 2. 保存到 `pic/steps/{run_id}_{log_seq:04d}_{label}.png` + 3. 文件名包含运行ID和日志序号,便于追踪 + +### 19.4 文本处理工具模块 (`douyin_utils.py`) + +#### 19.4.1 `normalize_countdown_text(text) -> str` + +- **作用**: 对福袋倒计时类OCR文本做标准化 +- **参数**: + - `text: str`: OCR识别的倒计时文本 +- **返回值**: `str` - 标准化后的倒计时文本(格式:`mm:ss` 或 `mm:ss后开奖`) +- **主要逻辑**: + 1. **OCR混淆纠正**: 将常见OCR错误字符替换为正确数字 + - `O/o/Q/D` → `0` + - `I/l/|/!` → `1` + - `S/s` → `5` + - `B` → `8` + - `G` → `6` + - `Z` → `2` + 2. **格式解析**: + - 中文格式:`x分y秒` → `mm:ss` + - 仅分钟:`x分钟` → `mm:00` + - 仅秒数:`x秒` → `mm:ss` + - 标准样式:`11:37后开奖` → `11:37后开奖` + - 无分割符:`1413后开奖` → `14:13后开奖` + 3. **分秒交换处理**: 如果识别结果不合理(如秒数>=60),尝试交换分秒 + +#### 19.4.2 `extract_prize_value_yuan(text) -> float` + +- **作用**: 从OCR文本中提取奖品价值(元) +- **参数**: + - `text: str`: OCR识别的价值文本 +- **返回值**: `float` - 提取的价值(元),如果提取失败返回0.0 +- **主要逻辑**: + 1. 提取数字和单位("元"、"¥"等) + 2. 转换为浮点数 + 3. 支持格式:`200元`、`¥200`、`价值200元` 等 + +### 19.5 OCR预处理模块 (`ocr_preprocess.py`) + +#### 19.5.1 `preprocess_for_ocr(analyser, cut_pic_name) -> str` + +- **作用**: 对图片进行OCR预处理,生成可供OCR使用的图片 +- **参数**: + - `analyser: Any`: 分析器对象 + - `cut_pic_name: str`: 裁剪后的图片名称 +- **返回值**: `str` - 预处理后的图片名称(如果预处理失败,返回原名称) +- **主要逻辑**: + 1. 查找裁剪后的图片路径 + 2. 对图片进行预处理(如二值化、去噪等) + 3. 保存预处理后的图片 + 4. 返回预处理后的图片名称 + +**预处理技术**: +- 图像二值化:提高OCR识别准确率 +- 去噪处理:去除图像中的噪声 +- 对比度增强:提高文字清晰度 + +### 19.6 文本工具模块 (`douyin_text_utils.py`) + +#### 19.6.1 `extract_fudai_content(text) -> str` + +- **作用**: 从OCR文本中提取福袋内容 +- **参数**: + - `text: Optional[str]`: OCR识别的文本 +- **返回值**: `str` - 提取的福袋内容 +- **主要逻辑**: + - 清理无关字符 + - 提取福袋内容描述 + +#### 19.6.2 `_safe_str(text) -> str` + +- **作用**: 将输入安全地转换为字符串,`None` → 空字符串 +- **参数**: + - `text: Optional[str]`: 输入文本 +- **返回值**: `str` - 转换后的字符串 + +### 19.7 配置管理模块 (`douyin_config.py`) + +#### 19.7.1 `ConfigManager.load_config_from_file(analyser, config_path=None) -> None` + +- **作用**: 从配置文件加载配置并设置到 `analyser` 对象 +- **参数**: + - `analyser: Any`: `fudai_analyse` 实例 + - `config_path: Optional[str]`: 配置文件路径,如果为 `None` 则使用 `analyser.config_path` +- **返回值**: 无 +- **主要逻辑**: + 1. 确定配置文件路径(优先使用传入的路径,否则使用 `analyser.config_path`) + 2. 如果配置文件不存在,直接返回(使用默认值) + 3. 读取JSON配置文件 + 4. 将配置项设置到 `analyser` 对象的属性上 + 5. 保留 `needswitch` 的原始值(如果已通过命令行设置) + +**配置项映射**: +- `min_prize_value_yuan` → `analyser.min_prize_value_yuan` +- `min_participants` → `analyser.min_participants` +- `max_participants` → `analyser.max_participants` +- 等等... + +## 20. 检测功能详解 + +### 20.1 像素检测功能详解 + +#### 20.1.1 `detect_live_room_icons_by_pixel(pic_rgb) -> Tuple[bool, float]` + +- **文件位置**: `douyin/detection/douyin_pixel.py` +- **作用**: 通过像素检测右上角x和xin图标区域,判断是否在直播间 +- **参数**: + - `pic_rgb: Image.Image`: PIL Image对象(RGB格式) +- **返回值**: `Tuple[bool, float]` - (是否检测到, 置信度) +- **检测区域**: `(972, 147)` 到 `(1047, 216)`(基准1080x2400) +- **检测特征**: + - **x图标**: 通常是白色或浅色的X形状 + - **xin图标**: 通常是粉色/红色的心形图标 +- **检测逻辑**: + 1. 缩放坐标到实际分辨率 + 2. 采样检测点(步长:区域宽高的1/20) + 3. 统计白色/浅色像素(x图标)和粉色/红色像素(xin图标) + 4. 计算置信度:`confidence = (white_ratio + pink_red_ratio) / 2` + 5. 如果置信度 >= 0.1,返回 `(True, confidence)` + +**调试支持**: +- 保存调试图像:标注检测区域和检测结果 +- 记录检测统计信息(白色像素数、粉色/红色像素数、总采样数) + +#### 20.1.2 `detect_fudai_detail_page(pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi, template_threshold, return_info=False, analyser=None) -> bool | Tuple[bool, dict]` + +- **文件位置**: `douyin/detection/douyin_pixel.py` +- **作用**: 检测是否在福袋详情页,并检测任务数量 +- **参数**: + - `pic_rgb: Image.Image`: PIL Image对象(RGB格式,保留用于兼容性,实际不使用) + - `resolution_ratio_x: int`: 分辨率X比例(默认1080,保留用于兼容性) + - `resolution_ratio_y: int`: 分辨率Y比例(默认2400,保留用于兼容性) + - `y_pianyi: int`: Y轴偏移(默认0,保留用于兼容性) + - `template_threshold: float`: 模板匹配阈值(保留用于兼容性,不再使用) + - `return_info: bool`: 是否返回详细信息(默认False) + - `analyser: Any`: 分析器对象(必需,用于任务数量检测) +- **返回值**: + - `bool`: 是否在福袋详情页(`return_info=False` 时) + - `Tuple[bool, dict]`: (是否在福袋详情页, 详细信息)(`return_info=True` 时) +- **检测策略**: 任务数量检测 + 1. 通过检测任务数量来判断是否在福袋详情页 + 2. 如果任务数量 <= 0,则认为不在福袋详情页 + 3. 如果任务数量 >= 1,则认为在福袋详情页,并返回任务数量 +- **实现**: 调用 `check_detail_height(analyser)` 执行任务数量检测 + +**详细信息字典** (`return_info=True` 时): +```python +{ + "method": "task_count", # 检测方法 + "task_count": 2, # 检测到的任务数量(0、1、2或3) + "reason": "detection_exception: ..." # 如果检测失败,包含失败原因 +} +``` + +**调试支持**: +- 保存调试图像:标注检测区域、检测点、检测结果 +- 记录检测统计信息(任务数量、检测Y坐标、检测X坐标、检测点数量) + +#### 20.1.2.1 `check_detail_height(analyser) -> int` + +- **文件位置**: `douyin/detection/douyin_detection.py` +- **作用**: 检测福袋详情页中需要完成的任务数量 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: `int` - 任务数量(0、1、2或3) +- **检测原理**: + - 在参与按钮附近的特定Y坐标处检测像素颜色特征 + - 不同任务数量对应不同的Y坐标位置 + - 通过检测特定颜色的像素来判断任务数量 +- **检测点配置**: + ```python + check_points = [ + (983, 0, 2), # 2个任务:Y坐标983(基准2400) + (983, y_pianyi, 2), # 2个任务:Y坐标983 + y_pianyi + (983, -y_pianyi, 2),# 2个任务:Y坐标983 - y_pianyi + (883, 0, 3), # 3个任务:Y坐标883 + (883, y_pianyi, 3), # 3个任务:Y坐标883 + y_pianyi + (883, -y_pianyi, 3),# 3个任务:Y坐标883 - y_pianyi + (1058, 0, 1), # 1个任务:Y坐标1058 + (1058, y_pianyi, 1),# 1个任务:Y坐标1058 + y_pianyi + (1058, -y_pianyi, 1),# 1个任务:Y坐标1058 - y_pianyi + ] + ``` +- **检测X坐标**: `x = 536 * rx // 1080`(参与按钮的X坐标) +- **像素颜色检测**: + - 检测RGB值是否在特定范围内:`28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86` + - 这个颜色范围对应任务项的特征颜色 +- **检测流程**: + 1. 读取截图(最多重试3次) + 2. 缩放X坐标到实际分辨率 + 3. 遍历检测点列表,检查每个检测点的像素颜色 + 4. 如果检测到匹配的像素颜色,返回对应的任务数量 + 5. 如果所有检测点都不匹配,返回0 + 6. 保存调试图像(标注检测区域和检测点) + +**调试支持**: +- 保存调试图像:标注检测区域、所有检测点、检测结果 +- 记录检测统计信息(任务数量、检测Y坐标、检测X坐标、检测点数量) +- 记录截图时间戳和当前时间,便于分析时间差 + +#### 20.1.3 `detect_attend_button_red_area(pic_rgb, return_info=False, red_ratio_threshold=None, analyser=None) -> bool | Tuple[bool, dict]` + +- **文件位置**: `douyin/detection/douyin_pixel.py` +- **作用**: 检测参与按钮红色区域(用于判断是否可以参与) +- **参数**: + - `pic_rgb: Image.Image`: PIL Image对象(RGB格式) + - `return_info: bool`: 是否返回详细信息(默认False) + - `red_ratio_threshold: float | None`: 红色比例阈值(默认None,使用配置值) + - `analyser: Any`: 分析器对象(用于日志和调试图像) +- **返回值**: + - `bool`: 是否检测到参与按钮(`return_info=False` 时) + - `Tuple[bool, dict]`: (是否检测到, 详细信息)(`return_info=True` 时) +- **检测区域**: `(306, 2030)` 到 `(780, 2110)`(基准1080x2400,参与按钮区域) +- **检测逻辑**: + 1. 缩放坐标到实际分辨率 + 2. 采样检测点(步长:区域宽高的1/20) + 3. 统计红色像素数量(RGB值在红色范围内) + 4. 计算红色比例:`red_ratio = red_count / total_samples` + 5. 如果红色比例 >= 阈值(默认0.25),返回 `True` + +**详细信息字典** (`return_info=True` 时): +```python +{ + "method": "pixel_detect", + "red_ratio": 0.35, # 红色比例 + "red_count": 45, # 红色像素数 + "total_samples": 128, # 总采样数 + "threshold": 0.25, # 使用的阈值 + "result": "success" # 检测结果 +} +``` + +#### 20.1.4 `detect_fansclub_join_red_area(pic_rgb, return_info=False, red_ratio_threshold=None, analyser=None) -> bool | Tuple[bool, dict]` + +- **文件位置**: `douyin/detection/douyin_pixel.py` +- **作用**: 检测粉丝团加入按钮红色区域 +- **参数**: 同 `detect_attend_button_red_area()` +- **返回值**: 同 `detect_attend_button_red_area()` +- **检测区域**: `(200, 1940)` 到 `(880, 2140)`(基准1080x2400,粉丝团加入按钮区域) +- **检测逻辑**: 同 `detect_attend_button_red_area()` + +#### 20.1.5 `detect_lucky_draw_result_popup(pic_rgb, red_ratio_threshold=0.8, return_info=False) -> bool | Tuple[bool, dict]` + +- **文件位置**: `douyin/detection/douyin_pixel.py` +- **作用**: 检测开奖结果弹窗(通过检测红色区域) +- **参数**: + - `pic_rgb: Image.Image`: PIL Image对象(RGB格式) + - `red_ratio_threshold: float`: 红色比例阈值(默认0.8) + - `return_info: bool`: 是否返回详细信息(默认False) +- **返回值**: 同 `detect_attend_button_red_area()` +- **检测区域**: `(181, 1261)` 到 `(890, 1389)`(基准1080x2400,开奖结果弹窗区域) +- **检测逻辑**: 同 `detect_attend_button_red_area()` + +### 20.2 并行像素检测 (`read_pixel_stage_state_from_screenshot`) + +#### 20.2.1 并行检测机制 + +`read_pixel_stage_state_from_screenshot()` 使用 `ThreadPoolExecutor` 并行执行所有检测函数,提高性能。 + +**并行检测任务**: +1. `has_coupon_bg`: 检测优惠券弹窗背景(模板匹配) +2. `has_redpacket_bg`: 检测购物红包弹窗背景(像素检测) +3. `has_lucky_draw_result`: 检测开奖结果弹窗(像素检测) +4. `has_attend_button_red`: 检测参与按钮红色区域(像素检测) +5. `has_fansclub_join_red`: 检测粉丝团加入按钮红色区域(像素检测) +6. `has_fudai_detail`: 检测福袋详情页(模板匹配 + 任务数量检测) + +**并行执行流程**: +1. 创建线程池(`ThreadPoolExecutor`) +2. 提交所有检测任务 +3. 等待所有任务完成 +4. 收集检测结果 +5. 返回检测结果字典 + +**性能优化**: +- 并行执行:所有检测任务同时执行,减少总耗时 +- 线程池大小:根据CPU核心数自动调整 +- 异常处理:单个检测任务失败不影响其他任务 + +### 20.3 任务数量检测详解 + +#### 20.3.1 检测原理 + +任务数量检测通过检测福袋详情页任务列表区域的特征来判断任务数量(1、2或3个任务)。 + +**检测区域**: `(486, 783)` 到 `(586, 1158)`(基准1080x2400) + +**检测方法**: +1. **Y坐标检测**: 在Y坐标1058处检测任务项的位置 +2. **X坐标检测**: 在X坐标536附近检测任务项的特征 +3. **检测点统计**: 统计检测点数量(通常为9个点) +4. **任务数量判断**: + - 检测点数量 ≈ 3 → 1个任务 + - 检测点数量 ≈ 6 → 2个任务 + - 检测点数量 ≈ 9 → 3个任务 + +**检测流程**: +1. 裁剪任务列表区域 +2. 在指定Y坐标处检测X坐标附近的像素特征 +3. 统计检测点数量 +4. 根据检测点数量判断任务数量 +5. 保存调试图像(标注检测区域和检测结果) + +#### 20.3.2 使用场景 + +任务数量检测主要用于: +1. **福袋详情验证**: 验证是否在福袋详情页 +2. **任务类型判断**: 判断福袋是否有多个任务(用于筛选) +3. **参与决策**: 某些任务类型的福袋可能需要特殊处理 + +#### 20.3.3 调试支持 + +**调试图像保存**: +- 保存检测前图像:标注检测区域 +- 保存检测后图像:标注检测区域、检测点、检测结果 +- 图像文件名包含:操作类型、图片名称、步骤、坐标、检测结果等 + +**调试信息记录**: +- 检测区域坐标 +- 检测到的任务数量 +- 检测Y坐标和X坐标 +- 检测点数量 +- 检测结果(成功/失败) + +### 20.4 调试图像系统详解 + +#### 20.4.1 调试图像保存机制 + +**保存位置**: `pic/debug_captures/YYYY-MM-DD/` + +**文件命名规则**: +``` +{timestamp}_{operation_type}_{picname}_{step}_{coords}_{result_info}.png +``` + +**示例文件名**: +``` +20251230_123632_detection_福袋任务数量_task_count_detection_(486,783)-(586,1158)_task_count_1_detected_y_1058_check_x_536_check_points_count_9_区域_(486,783)-(586,1158).png +``` + +**文件命名组成部分**: +1. **时间戳**: `YYYYMMDD_HHMMSS` 格式 +2. **操作类型**: `pixel_detect`、`ocr`、`template_match`、`detection`、`cut_pic` +3. **图片名称**: 操作的图片名称(如"福袋任务数量"、"开奖结果按钮") +4. **步骤**: 操作步骤(如"检测前"、"识别后"、"预处理后") +5. **坐标**: 检测/识别区域坐标 `(x1,y1)-(x2,y2)` +6. **结果信息**: 检测/识别结果(如"检测成功"、"task_count_1") + +#### 20.4.2 图像标注功能 + +**标注内容**: +1. **坐标区域标注**: 在图像上绘制矩形框,标注检测/识别区域 +2. **文本标注**: 在图像上添加文本信息(OCR识别结果、检测结果等) +3. **统计信息标注**: 标注检测统计信息(红色比例、检测点数量等) + +**标注样式**: +- 矩形框:绿色(成功)或红色(失败) +- 文本:白色背景,黑色文字 +- 字体大小:根据图像尺寸自动调整 + +#### 20.4.3 自动清理机制 + +**清理策略**: +- 按日期目录组织:每天一个目录 +- 自动清理旧目录:保留最近N天(默认3天) +- 配置控制:通过 `debug_captures.keep_days` 配置保留天数 + +**清理时机**: +- 每天第一次保存调试图像时执行清理 +- 清理超过保留天数的目录 + +#### 20.4.4 启用调试图像 + +**配置方法**: +在 `config.json` 中设置: +```json +{ + "debug_captures": { + "enabled": true, + "keep_days": 3 + } +} +``` + +**注意事项**: +- 调试图像会占用磁盘空间,建议定期清理 +- 生产环境建议关闭调试图像保存(`enabled: false`) +- 调试时启用调试图像,便于排查问题 + +--- + +## 21. 导航和滑动操作详解 + +### 21.1 上滑切换直播间 + +#### `SwipeHandler.swipe_up_to_next_live(analyser) -> None` + +- **文件位置**: `douyin/handlers/douyin_swipe_handler.py` +- **作用**: 上滑切换到下一个直播间 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: None +- **调用位置**: `swipe_up_to_next_live()` 中调用 +- **主要逻辑**: + + 1. **预约锁定期检查**: + - 检查是否在预约锁定期内(`reservation_focus_until_ts > 当前时间`) + - 如果在锁定期内,不允许上划离开预约直播间,直接返回 + - 记录日志:锁定期剩余秒数 + + 2. **执行上滑操作**: + - 调用 `swipe_up_switch_live()` 执行上滑 + - 基准坐标(1080x2400):从 `(540, 1700)` 滑动到 `(540, 700)` + - 滑动距离约1000像素 + - 滑动持续时间:`swipe_duration_ms`(默认600ms) + + 3. **更新直播间位置**: + - `room_pos += 1`(上滑后位置+1) + - `_swipe_times += 1`(滑动次数+1) + + 4. **检查滑动次数重置**: + - 调用 `maybe_reset_after_swipes()` 检查是否需要重置 + + 5. **设置标志**: + - `_just_switched_room = True`(标记刚刚切换了直播间) + - `_fudai_detail_first_read = False`(清除第一次读取标志) + - `_last_fudai_detail_tuple = None`(清除上次详情数据) + + 6. **记录直播间标题和位置**: + - 调用 `_record_room_title_and_pos()` 记录当前直播间的标题和位置 + - 用于回退校验(如果不在回退过程中) + +**配置参数**: +- `swipe_duration_ms`: 滑动持续时间(毫秒,默认600) +- `reservation_focus_until_ts`: 预约聚焦时间戳(如果 > 当前时间,不允许上划) + +**代码示例**: +```python +def swipe_up_to_next_live(analyser: Any) -> None: + # 检查预约锁定期 + focus_until = float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0) + now_ts = time.time() + if focus_until > 0 and now_ts < focus_until: + # 在锁定期内,不允许上划 + return + + # 执行上滑 + swipe_up_switch_live(analyser) + + # 更新位置 + analyser.room_pos += 1 + analyser._swipe_times += 1 + + # 检查重置 + maybe_reset_after_swipes(analyser) + + # 设置标志 + analyser._just_switched_room = True + analyser._fudai_detail_first_read = False +``` + +### 21.2 下滑回退直播间 + +#### `SwipeHandler.swipe_down_back_from_live(analyser) -> None` + +- **文件位置**: `douyin/handlers/douyin_swipe_handler.py` +- **作用**: 下滑回退到上一个直播间(供预约/无福袋逻辑使用) +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: None +- **调用位置**: `swipe_down_back_from_live()` 中调用 +- **主要逻辑**: + + 1. **执行下滑操作**: + - 调用 `swipe_down_back_live()` 执行下滑 + - 基准坐标(1080x2400):从 `(540, 800)` 滑动到 `(540, 1600)` + - 滑动距离约800像素 + - 滑动持续时间:`swipe_duration_ms`(默认600ms) + - 如果下滑失败,退化为点击返回键 + + 2. **更新直播间位置**: + - `room_pos -= 1`(下滑后位置-1) + + 3. **记录直播间标题和位置**: + - 调用 `_record_room_title_and_pos()` 记录当前直播间的标题和位置 + - 用于回退校验(如果不在回退过程中) + +**配置参数**: +- `swipe_duration_ms`: 滑动持续时间(毫秒,默认600) +- `reservation_back_swipe_delay_s`: 回退滑动延迟(秒,默认0.6) + +**代码示例**: +```python +def swipe_down_back_from_live(analyser: Any) -> None: + try: + swipe_down_back_live(analyser) + except Exception: + # 退化为点击返回键 + analyser.operation.click_back(analyser.device_id) + + # 更新位置 + analyser.room_pos -= 1 + + # 记录标题和位置 + if not getattr(analyser, "_skip_record_title_during_seek", False): + analyser._record_room_title_and_pos() +``` + +### 21.3 滑动次数重置 + +#### `SwipeHandler.maybe_reset_after_swipes(analyser) -> int` + +- **文件位置**: `douyin/handlers/douyin_swipe_handler.py` +- **作用**: 达到切换阈值后,在当前直播间页面回退到第一个直播间 +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: `int` - 重置后的滑动次数(通常为0) +- **调用位置**: `swipe_up_to_next_live()` 中调用 +- **主要逻辑**: + + 1. **检查是否启用重置功能**: + - 如果 `needswitch = False`(单间模式),不执行重置 + - 如果 `reset_after_swipes_enabled = False`,不执行重置 + + 2. **检查是否达到阈值**: + - 获取当前滑动次数 `_swipe_times` + - 获取阈值 `reset_after_swipes`(默认50) + - 如果 `_swipe_times < threshold`,不执行重置 + + 3. **执行回退操作**: + - 计算回退次数:`back_times = min(swipe_times, 100)`(最多100次) + - 循环执行下滑操作(从上往下滑动): + - 基准坐标(1080x2400):从 `(760, 800)` 滑动到 `(760, 1600)` + - 滑动持续时间:`swipe_duration_ms`(默认300ms) + - 每次滑动后延迟2秒 + + 4. **重置计数器和位置**: + - `_swipe_times = 0` + - `room_pos = 0` + - 延迟3秒后返回 + +**配置参数**: +- `reset_after_swipes_enabled`: 是否启用滑动次数重置(bool,默认False) +- `reset_after_swipes`: 滑动次数阈值(默认50) +- `swipe_duration_ms`: 滑动持续时间(毫秒,默认300) + +**代码示例**: +```python +def maybe_reset_after_swipes(analyser: Any) -> int: + if not needswitch or not reset_after_swipes_enabled: + return analyser._swipe_times + + swipe_times = analyser._swipe_times + threshold = analyser.reset_after_swipes + + if swipe_times < threshold: + return swipe_times + + # 执行回退 + back_times = min(swipe_times, 100) + for i in range(back_times): + # 从上往下滑动 + swipe_down_back_live(analyser) + analyser.operation.delay(2) + + # 重置 + analyser._swipe_times = 0 + analyser.room_pos = 0 + return 0 +``` + +### 21.4 返回推荐页面并重新进入直播间 + +#### `SwipeHandler.return_to_recommend_and_reenter_live(analyser) -> None` + +- **文件位置**: `douyin/handlers/douyin_swipe_handler.py` +- **作用**: 返回推荐页面并重新进入直播间(用于30分钟超时等场景) +- **参数**: + - `analyser: Any`: 分析器对象 +- **返回值**: None +- **调用位置**: `_return_to_recommend_and_reenter_live()` 中调用 +- **主要逻辑**: + + 1. **多次点击返回键**: + - 最多点击 `MAX_BACK_CLICKS_TO_RECOMMEND` 次(默认10次) + - 每次点击后: + - 获取截图 + - 执行阶段诊断 + - 如果阶段为 `RECOMMEND_PAGE`,跳出循环 + - 延迟 `BACK_KEY_CLICK_DELAY` 秒(默认1.0秒) + + 2. **等待页面稳定**: + - 延迟 `PAGE_STABLE_DELAY` 秒(默认2.0秒) + + 3. **确认当前阶段**: + - 再次截图并执行阶段诊断 + - 记录日志 + + 4. **点击关注标签并进入直播间**: + - 点击关注标签:坐标 `(709, 169)`(基准1080x2400) + - 延迟 `FOLLOW_TAB_CLICK_DELAY` 秒(默认2.0秒) + - 点击进入直播间位置:坐标 `(103, 385)`(基准1080x2400),连点两次 + - 延迟 `ENTER_LIVE_CLICK_DELAY` 秒(默认0.6秒) + - 延迟 `ENTER_LIVE_FINAL_DELAY` 秒(默认2.0秒) + + 5. **设置标志和重置时间戳**: + - `_just_switched_room = True`(标记刚刚切换进入直播间) + - `_last_successful_attend_ts = time.time()`(重置最后成功参与时间) + - `_run_start_ts = time.time()`(重置运行开始时间) + +**类常量**: +- `MAX_BACK_CLICKS_TO_RECOMMEND = 10`: 返回推荐页面的最大返回键点击次数 +- `BACK_KEY_CLICK_DELAY = 1.0`: 返回键点击后的延迟(秒) +- `PAGE_STABLE_DELAY = 2.0`: 页面稳定等待时间(秒) +- `FOLLOW_TAB_CLICK_DELAY = 2.0`: 点击关注标签后的延迟(秒) +- `ENTER_LIVE_CLICK_DELAY = 0.6`: 点击进入直播间的延迟(秒) +- `ENTER_LIVE_FINAL_DELAY = 2.0`: 进入直播间后的最终等待时间(秒) + +**代码示例**: +```python +def return_to_recommend_and_reenter_live(analyser: Any) -> None: + # 多次点击返回键 + max_back_clicks = analyser.MAX_BACK_CLICKS_TO_RECOMMEND + for i in range(max_back_clicks): + analyser.operation.get_screenshot(analyser.device_id) + stage, seen = analyser._diagnose_stage_from_current_screen() + + if stage == "RECOMMEND_PAGE": + break + + analyser.operation.click_back(analyser.device_id) + analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY) + + # 等待页面稳定 + analyser.operation.delay(analyser.PAGE_STABLE_DELAY) + + # 点击关注标签 + follow_tab_x = int(709 * analyser.resolution_ratio_x // 1080) + follow_tab_y = int(169 * analyser.resolution_ratio_y // 2400) + analyser.operation.click(analyser.device_id, follow_tab_x, follow_tab_y) + analyser.operation.delay(analyser.FOLLOW_TAB_CLICK_DELAY) + + # 点击进入直播间 + enter_live_x = int(103 * analyser.resolution_ratio_x // 1080) + enter_live_y = int(385 * analyser.resolution_ratio_y // 2400) + analyser.operation.click(analyser.device_id, enter_live_x, enter_live_y) + analyser.operation.delay(analyser.ENTER_LIVE_CLICK_DELAY) + analyser.operation.click(analyser.device_id, enter_live_x, enter_live_y) + analyser.operation.delay(analyser.ENTER_LIVE_FINAL_DELAY) + + # 设置标志和重置时间戳 + analyser._just_switched_room = True + analyser._last_successful_attend_ts = time.time() + analyser._run_start_ts = time.time() +``` + +### 21.5 预约直播间查找 + +#### `ReservationHandler.seek_reservation_room(analyser, item) -> bool` + +- **文件位置**: `douyin/reservation/douyin_reservation_handler.py` +- **作用**: 根据预约记录里的 `pos_seen` 与当前 `room_pos` 进行回退,靠近目标直播间 +- **参数**: + - `analyser: Any`: 分析器对象 + - `item: dict`: 预约记录(包含 `pos_seen`、`room_title` 等) +- **返回值**: `bool` - `True`=成功找到, `False`=未找到 +- **调用位置**: `_seek_reservation_room()` 中调用 +- **主要逻辑**: + + 1. **计算回退次数**: + - `back_times = abs(room_pos - pos_seen)` + - 限制最大回退次数:`min(back_times, high_value_fudai_max_swipe_back)` + + 2. **执行回退操作**: + - 循环执行下滑操作(`swipe_down_back_from_live()`) + - 每次回退后延迟 `reservation_back_swipe_delay_s` 秒 + - 更新 `room_pos` + + 3. **回退校验**(如果启用): + - 读取直播间标题 + - 验证标题是否匹配预约记录中的 `room_title` + - 如果标题不匹配,尝试自动回退 + + 4. **记录标题和位置**: + - 调用 `_record_room_title_and_pos()` 记录当前直播间的标题和位置 + +**配置参数**: +- `high_value_fudai_max_swipe_back`: 最大回退次数(默认10) +- `reservation_back_swipe_delay_s`: 回退滑动延迟(秒,默认0.6) +- `high_value_fudai_back_verify_enabled`: 是否启用回退校验(bool,默认False) + +**代码示例**: +```python +def seek_reservation_room(analyser: Any, item: dict) -> bool: + pos_seen = item.get("pos_seen", 0) + current_pos = analyser.room_pos + back_times = abs(current_pos - pos_seen) + + # 限制最大回退次数 + max_back = analyser.high_value_fudai_max_swipe_back + back_times = min(back_times, max_back) + + # 执行回退 + for i in range(back_times): + swipe_down_back_from_live(analyser) + analyser.operation.delay(analyser.reservation_back_swipe_delay_s) + + # 回退校验 + if analyser.high_value_fudai_back_verify_enabled: + title = read_live_room_title(analyser) + if title != item.get("room_title", ""): + # 标题不匹配,尝试自动回退 + # ... + + return True +``` + +--- + +## 22. 桌面检测和自救机制详解 + +### 22.1 桌面检测机制 + +#### 22.1.1 检测原理 + +桌面检测通过检查当前前台应用的包名来判断是否在抖音前台: + +1. **获取前台包名**: + - 调用 `operation.get_top_package(device_id)` 获取前台应用包名 + - 使用ADB命令:`adb shell dumpsys window windows | grep mCurrentFocus` + +2. **判断是否为抖音包**: + - 检查包名是否包含以下关键词: + - `"aweme"`(抖音包名) + - `"douyin"`(抖音) + - `"com.ss.android.ugc"`(抖音包名前缀) + - 如果包名存在且不包含以上关键词,判定为不在抖音前台 + +3. **检测时机**: + - 在 `run_once_basic()` 中,阶段诊断后执行 + - 每次循环都会检测,确保及时发现异常 + +### 22.1.2 检测实现 + +**代码位置**: `douyin/core/douyin_fudai.py` 的 `run_once_basic()` 方法中 + +**检测流程**: +```python +# 1. 获取前台包名 +top_pkg = analyser.operation.get_top_package(analyser.device_id) + +# 2. 判断是否为抖音包 +is_douyin_pkg = top_pkg and ( + "aweme" in top_pkg + or "douyin" in top_pkg + or "com.ss.android.ugc" in top_pkg +) + +# 3. 如果不在抖音前台,触发自救 +if top_pkg and not is_douyin_pkg: + # 执行自救操作 + # ... +``` + +### 22.2 自救机制 + +#### 22.2.1 自救流程 + +当检测到不在抖音前台时,执行以下自救操作: + +1. **点击桌面图标**: + - 优先使用配置的坐标:`desktop_icon_x`, `desktop_icon_y` + - 如果配置不存在,使用默认坐标:`(153, 260)`(基准1080x2400) + - 延迟2秒 + +2. **点击直播按钮**: + - 使用配置的坐标:`yanghao_fallback_live_x`, `yanghao_fallback_live_y` + - 延迟1.5秒 + +3. **点击进入直播间**: + - 使用配置的坐标:`yanghao_fallback_enter_live_x`, `yanghao_fallback_enter_live_y` + - 连点两次(确保进入直播间) + - 延迟0.6秒(第一次点击后) + - 延迟2.0秒(第二次点击后) + +4. **重新执行主流程**: + - 延迟0.5秒 + - 递归调用 `run_once_basic()` 重新执行主流程 + - 自救完成后前台包名应为抖音,下一次循环不会再次进入自救分支 + +#### 22.2.2 配置参数 + +**桌面图标坐标**: +- `desktop_icon_x`: 桌面图标X坐标(默认153) +- `desktop_icon_y`: 桌面图标Y坐标(默认260) + +**直播按钮坐标**: +- `yanghao_fallback_live_x`: 直播按钮X坐标(默认540) +- `yanghao_fallback_live_y`: 直播按钮Y坐标(默认2000) + +**进入直播间坐标**: +- `yanghao_fallback_enter_live_x`: 进入直播间X坐标(默认540) +- `yanghao_fallback_enter_live_y`: 进入直播间Y坐标(默认1200) + +**配置示例**: +```json +{ + "desktop_icon_x": 153, + "desktop_icon_y": 260, + "yanghao_fallback_live_x": 540, + "yanghao_fallback_live_y": 2000, + "yanghao_fallback_enter_live_x": 540, + "yanghao_fallback_enter_live_y": 1200 +} +``` + +### 22.3 自救机制代码实现 + +**代码位置**: `douyin/core/douyin_fudai.py` 的 `run_once_basic()` 方法中 + +**完整实现**: +```python +# 检测是否意外返回桌面 +try: + top_pkg = analyser.operation.get_top_package(analyser.device_id) or "" + + # 判断是否为抖音包 + is_douyin_pkg = top_pkg and ( + "aweme" in top_pkg + or "douyin" in top_pkg + or "com.ss.android.ugc" in top_pkg + ) + + if top_pkg and not is_douyin_pkg: + # 执行自救操作 + try: + # 点击桌面图标 + try: + analyser.click( + int(analyser.desktop_icon_x), + int(analyser.desktop_icon_y) + ) + except Exception: + # 退化为默认硬编码位置 + analyser.click(153, 260) + analyser.operation.delay(2) + + # 点击直播按钮 + try: + lx = int(analyser.yanghao_fallback_live_x) + ly = int(analyser.yanghao_fallback_live_y) + analyser.click(lx, ly) + analyser.operation.delay(1.5) + except Exception: + pass + + # 点击进入直播间 + try: + ex = int(analyser.yanghao_fallback_enter_live_x) + ey = int(analyser.yanghao_fallback_enter_live_y) + analyser.click(ex, ey) + analyser.operation.delay(0.6) + analyser.click(ex, ey) + analyser.operation.delay(2.0) + except Exception: + pass + + # 重新执行主流程 + analyser.operation.delay(0.5) + analyser.run_once_basic() # 递归调用 + return + except Exception as e: + analyser._log_kv("自救", "恢复失败", error=str(e)) +except Exception as exc: + analyser._log_kv("自救", "桌面检测异常", error=str(exc)) +``` + +### 22.4 自救机制的特点 + +1. **自动检测**: 每次循环都会检测,无需手动触发 +2. **自动恢复**: 检测到异常后自动执行恢复操作 +3. **递归调用**: 自救完成后递归调用 `run_once_basic()`,确保流程连续性 +4. **防止重复**: 自救完成后前台包名应为抖音,下一次循环不会再次进入自救分支 +5. **错误处理**: 每个步骤都有异常处理,确保自救流程的健壮性 + +### 22.5 使用场景 + +桌面检测和自救机制主要用于以下场景: + +1. **意外返回桌面**: 用户手动返回桌面或系统自动返回桌面 +2. **应用切换**: 用户切换到其他应用 +3. **系统弹窗**: 系统弹窗导致抖音不在前台 +4. **应用崩溃**: 抖音应用崩溃后自动恢复 + +### 22.6 注意事项 + +1. **坐标配置**: 不同设备的桌面图标和按钮位置可能不同,需要根据实际情况调整配置 +2. **延迟时间**: 自救操作中的延迟时间需要根据设备性能调整 +3. **递归深度**: 自救机制使用递归调用,但只递归一次,不会导致栈溢出 +4. **日志记录**: 自救过程中的所有操作都会记录日志,便于排查问题 + +--- + +## 23. 日志系统详解 + +### 23.1 日志系统架构 + +项目采用**分层日志系统**,包含以下组件: + +1. **LoggingWrapper**: 统一日志包装器,提供增强的日志记录功能 +2. **ActionLogger**: 行为日志记录器,记录关键操作和耗时 +3. **PerformanceTracker**: 性能追踪器,统计函数和操作的耗时 +4. **ErrorLogger**: 错误日志记录器,记录异常和错误信息 +5. **DebugLogger**: 调试日志记录器,记录调试信息 +6. **track_action**: 操作追踪装饰器,自动记录函数耗时 + +### 23.2 LoggingWrapper 详解 + +#### 23.2.1 核心功能 + +**文件位置**: `douyin/logging/douyin_logging_wrapper.py` + +**主要方法**: +- `enhanced_log_kv()`: 增强的日志记录方法 +- `log_step_time()`: 记录步骤耗时 + +#### 23.2.2 `enhanced_log_kv()` 方法 + +**功能**: 增强的日志记录方法,始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging + +**参数**: +- `analyser: Any`: 分析器对象 +- `*args`: 位置参数,第一个是tag,第二个是msg +- `**fields`: 关键字参数字典 + +**主要特性**: + +1. **参数解析**: + - 优先使用位置参数(tag, msg) + - 支持关键字参数(tag, msg, level等) + - 自动处理参数冲突 + +2. **日志格式**: + ``` + [时间戳] [级别] [标签] [调用者] 消息 字段... + ``` + - 时间戳:`YYYY-MM-DD HH:MM:SS.mmm` 格式 + - 级别:DEBUG, INFO, WARNING, ERROR, CRITICAL + - 标签:日志分类(如"流程"、"错误"、"参与"等) + - 调用者:`文件名:函数名:行号` + - 消息:日志消息内容 + - 字段:键值对形式(如 `价值元=500.0`) + +3. **字段映射**: + - 自动将英文字段名映射为中文(如 `value_yuan` → `价值元`) + - 支持自定义字段映射 + +4. **自动分隔符**: + - 错误/警告发生时自动添加分隔符 + - 运行开始时添加分隔符 + - 阶段变化时添加分隔符 + - 重要操作时添加分隔符 + +5. **调用者信息提取**: + - 自动提取调用栈信息 + - 跳过日志包装层,找到真正的调用者 + - 格式:`文件名:函数名:行号` + +**代码示例**: +```python +# 使用位置参数 +analyser._log_kv("流程", "开始处理福袋", value_yuan=500.0, countdown=60) + +# 使用关键字参数 +analyser._log_kv(tag="错误", msg="处理失败", error="连接超时", level="ERROR") + +# 输出格式: +# [2025-12-30 13:22:35.123] [INFO] [流程] [douyin_fudai.py:run_once_basic:551] 开始处理福袋 价值元=500.0 倒计时=60 +``` + +#### 23.2.3 `log_step_time()` 方法 + +**功能**: 记录步骤耗时 + +**参数**: +- `analyser: Any`: 分析器对象 +- `step_name: str`: 步骤名称 +- `start_time: float`: 开始时间(时间戳) + +**代码示例**: +```python +start_time = time.time() +# ... 执行操作 ... +LoggingWrapper.log_step_time(analyser, "处理福袋详情", start_time) +``` + +### 23.3 ActionLogger 详解 + +#### 23.3.1 核心功能 + +**文件位置**: `douyin/logging/action_logger.py` + +**主要方法**: +- `log_operation()`: 记录操作 +- `log_ocr()`: 记录OCR操作 +- `log_decision()`: 记录决策 +- `log_state_change()`: 记录状态变化 +- `log_step()`: 记录步骤 + +#### 23.3.2 日志输出 + +**输出位置**: +- 控制台输出(stdout) +- 文件输出:`logs/actions.log`(轮转文件,最大10MB,保留5个备份) + +**日志格式**: +``` +时间戳 - 操作类型: 详细信息 耗时=秒数 +``` + +**代码示例**: +```python +action_logger = ActionLogger() + +# 记录OCR操作 +action_logger.log_ocr("福袋内容", "价值500元", elapsed=2.5) + +# 记录决策 +action_logger.log_decision("参与福袋", elapsed=0.1) + +# 记录状态变化 +action_logger.log_state_change("等待中", "已参与", elapsed=1.2) + +# 记录步骤 +action_logger.log_step("处理福袋详情", elapsed=3.5) +``` + +### 23.4 PerformanceTracker 详解 + +#### 23.4.1 核心功能 + +**文件位置**: `douyin/logging/performance_tracker.py` + +**主要方法**: +- `start_timer()`: 启动计时器 +- `end_timer()`: 结束计时器并返回耗时 +- `get_elapsed()`: 获取当前耗时(不结束计时器) +- `get_statistics()`: 获取统计信息(平均耗时) + +#### 23.4.2 使用方式 + +**手动计时**: +```python +perf = PerformanceTracker() + +# 启动计时器 +timer_id = perf.start_timer("处理福袋") + +# ... 执行操作 ... + +# 结束计时器并获取耗时 +elapsed = perf.end_timer(timer_id) +``` + +**装饰器方式**: +```python +perf = PerformanceTracker() + +@perf.track_function +def process_fudai(): + # ... 执行操作 ... + pass +``` + +**统计信息**: +```python +# 获取平均耗时统计 +stats = perf.get_statistics() +# 返回: {"处理福袋": 2.5, "OCR识别": 1.2, ...} +``` + +### 23.5 track_action 装饰器 + +#### 23.5.1 功能 + +**文件位置**: `douyin/logging/action_tracker.py` + +**功能**: 自动记录函数耗时与操作信息 + +**使用方式**: +```python +from douyin.logging import track_action + +@track_action("swipe_up_to_next_live") +def swipe_up_to_next_live(analyser): + # ... 执行操作 ... + pass +``` + +**工作原理**: +1. 函数执行前:启动计时器 +2. 函数执行后:结束计时器并记录日志 +3. 自动记录到 `ActionLogger` + +### 23.6 ErrorLogger 详解 + +#### 23.6.1 核心功能 + +**文件位置**: `douyin/logging/error_logger.py` + +**主要方法**: +- `log_exception()`: 记录异常 +- `log_error()`: 记录错误 +- `log_warning()`: 记录警告 +- `capture_error_context()`: 捕获错误上下文 + +#### 23.6.2 使用方式 + +```python +error_logger = ErrorLogger() + +try: + # ... 执行操作 ... +except Exception as e: + # 记录异常 + error_logger.log_exception(e, context={"device_id": device_id}) + +# 记录错误 +error_logger.log_error("处理失败", context={"reason": "超时"}) + +# 记录警告 +error_logger.log_warning("配置缺失", context={"key": "min_prize_value_yuan"}) +``` + +### 23.7 DebugLogger 详解 + +#### 23.7.1 核心功能 + +**文件位置**: `douyin/logging/debug_logger.py` + +**主要方法**: +- `log_function_entry()`: 记录函数入口 +- `log_function_exit()`: 记录函数退出 +- `log_variable()`: 记录变量快照 +- `log_call_stack()`: 记录调用栈 +- `log_exception()`: 记录异常 + +#### 23.7.2 使用方式 + +```python +debug_logger = DebugLogger(enabled=True) + +# 记录函数入口 +debug_logger.log_function_entry("process_fudai", value=500.0) + +# 记录变量 +debug_logger.log_variable("room_pos", 5) + +# 记录调用栈 +debug_logger.log_call_stack() + +# 记录异常 +debug_logger.log_exception(e, context={"step": "处理福袋"}) +``` + +### 23.8 日志系统配置 + +#### 23.8.1 日志级别 + +- **DEBUG**: 调试信息(函数入口/退出、变量快照等) +- **INFO**: 一般信息(操作记录、状态变化等) +- **WARNING**: 警告信息(配置缺失、非关键错误等) +- **ERROR**: 错误信息(异常、失败操作等) +- **CRITICAL**: 严重错误(系统级错误等) + +#### 23.8.2 日志文件 + +**统一日志文件**: `logs/unified_YYYY-MM-DD.log` +- 按日期轮转 +- 包含所有日志信息 + +**行为日志文件**: `logs/actions.log` +- 轮转文件(最大10MB,保留5个备份) +- 包含操作记录和耗时信息 + +**错误日志文件**: `logs/errors.log` +- 轮转文件(最大10MB,保留5个备份) +- 包含错误和异常信息 + +### 23.9 日志系统最佳实践 + +1. **使用合适的日志级别**: 根据信息重要性选择合适的级别 +2. **提供上下文信息**: 在日志中包含足够的上下文信息(设备ID、状态等) +3. **记录耗时信息**: 对关键操作记录耗时,便于性能分析 +4. **使用字段映射**: 使用标准字段名,自动映射为中文 +5. **避免敏感信息**: 不要在日志中记录敏感信息(密码、密钥等) + +--- + +## 24. OCR预处理和优化详解 + +### 24.1 OCR预处理系统 + +#### 24.1.1 `preprocess_for_ocr()` 函数 + +**文件位置**: `douyin/utils/ocr_preprocess.py` + +**功能**: 对已由 `cut_pic` 生成的裁剪图做预处理,返回可传入 `analyse_pic_*` 的图片名 + +**参数**: +- `analyser: Any`: fudai_analyse 实例 +- `cut_pic_name: str`: cut_pic 时使用的名称(不含扩展名) + +**返回值**: `str` - 预处理后图片的名称(不含扩展名) + +**预处理流程**: + +1. **转灰度**: + - 使用 `Image.convert("L")` 将图像转换为灰度图 + - 减少颜色信息,提高OCR识别准确率 + +2. **放大两倍**: + - 使用 `Image.resize()` 和 `Image.LANCZOS` 算法放大图像 + - 放大倍数:2倍(宽度和高度都放大2倍) + - 提高小字体的识别准确率 + +3. **自动对比度调整**: + - 使用 `ImageOps.autocontrast()` 自动调整对比度 + - 增强文字与背景的对比度 + +4. **锐化处理**: + - 使用 `ImageFilter.SHARPEN` 锐化图像 + - 提高文字边缘清晰度 + +**代码示例**: +```python +from douyin.utils.ocr_preprocess import preprocess_for_ocr + +# 裁剪图像 +analyser.cut_pic(200, 600, 880, 900, "福袋内容", "内容区域") + +# 预处理图像 +preprocessed_name = preprocess_for_ocr(analyser, "福袋内容") + +# 使用预处理后的图像进行OCR +result = analyser.operation.analyse_pic_word(preprocessed_name, 0) +``` + +#### 24.1.2 预处理效果 + +**预处理前**: +- 原始彩色图像 +- 可能包含背景干扰 +- 文字可能较小或模糊 + +**预处理后**: +- 灰度图像(减少颜色干扰) +- 放大2倍(提高小字体识别率) +- 对比度增强(文字更清晰) +- 锐化处理(边缘更清晰) + +### 24.2 OCR引擎优化 + +#### 24.2.1 OCR引擎初始化 + +**文件位置**: `operations/ocr_operations.py` + +**初始化优化**: + +1. **环境变量设置**: + ```python + # 禁用模型源连通性检查(避免启动耗时/卡死) + os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True") + + # 抑制冗余信息 + os.environ.setdefault("GLOG_minloglevel", "2") + os.environ.setdefault("OMP_NUM_THREADS", "1") + ``` + +2. **延迟初始化**: + - 支持延迟初始化(测试流程/只做点击时不需要 OCR) + - 通过 `SKIP_OCR_INIT` 环境变量控制 + +3. **CPU模式**: + - 默认使用CPU模式(删除GPU检测) + - 如果需要GPU加速,需要手动配置 + +#### 24.2.2 OCR识别优化 + +**文件位置**: `Underlying_Operations.py` + +**优化措施**: + +1. **图像预处理**: + - 锐化处理:使用 `ImageFilter.UnsharpMask` + - 对比度增强:使用 `ImageEnhance.Contrast` + - 提高数字识别准确率 + +2. **调试图像保存**: + - 保存OCR前的预处理图像 + - 使用完整截图(如果可用) + - 标注OCR区域坐标 + +3. **OCR结果缓存**: + - 对于相同的图像区域,可以缓存OCR结果 + - 避免重复识别相同内容 + +### 24.3 并行OCR处理 + +#### 24.3.1 并行OCR实现 + +**文件位置**: `douyin/fudai/core/fudai_detail_reader.py` + +**实现方式**: +```python +from concurrent.futures import ThreadPoolExecutor + +def get_fudai_contain(analyser, renwu: int = 2): + # 使用线程池并行执行OCR任务 + with ThreadPoolExecutor(max_workers=6) as executor: + # 提交多个OCR任务 + future_task_list = executor.submit(ocr_task_list) + future_content = executor.submit(ocr_content) + future_countdown_mm = executor.submit(ocr_countdown_mm) + future_countdown_ss = executor.submit(ocr_countdown_ss) + future_value = executor.submit(ocr_value) + future_button = executor.submit(ocr_button) + + # 等待所有任务完成 + task_list_raw = future_task_list.result() + fudai_content_raw = future_content.result() + # ... 其他结果 ... +``` + +#### 24.3.2 并行OCR优势 + +1. **提高效率**: 多个OCR任务同时执行,减少总耗时 +2. **充分利用资源**: 充分利用多核CPU资源 +3. **独立任务**: 每个OCR任务独立,互不影响 + +#### 24.3.3 并行OCR任务 + +**福袋详情读取中的并行OCR任务**: + +1. **任务列表OCR**: 识别任务列表区域 +2. **福袋内容OCR**: 识别福袋内容描述 +3. **倒计时分钟OCR**: 识别倒计时分钟数字 +4. **倒计时秒OCR**: 识别倒计时秒数字 +5. **价值OCR**: 识别奖品价值 +6. **按钮状态OCR**: 识别参与按钮状态 + +### 24.4 OCR性能优化建议 + +#### 24.4.1 硬件优化 + +1. **启用GPU加速**(如果可用): + ```python + self.ocr = easyocr.Reader( + gpu=True, # 如果GPU可用 + verbose=False + ) + ``` + +2. **多线程处理**: + - 使用 `ThreadPoolExecutor` 并行执行OCR任务 + - 充分利用多核CPU资源 + +#### 24.4.2 软件优化 + +1. **减少OCR调用次数**: + - 如果任务列表OCR检测到"观看X分钟"任务,可以提前返回 + - 优化倒计时识别,减少分割OCR的使用 + +2. **优化图像预处理**: + - 缓存裁剪后的图像,避免重复裁剪 + - 优化图像保存路径,使用内存缓存 + +3. **OCR结果缓存**: + - 对于相同的图像区域,可以缓存OCR结果 + - 避免重复识别相同内容 + +4. **减少OCR区域大小**: + - 精确裁剪OCR区域,减少不必要的图像内容 + - 提高OCR识别速度 + +#### 24.4.3 当前性能 + +根据日志分析: +- **单次OCR耗时**: 约3-4秒(CPU模式) +- **福袋详情总OCR耗时**: 约3-4秒(并行执行) +- **阶段诊断OCR耗时**: 约3-4秒 + +#### 24.4.4 预期优化效果 + +**如果启用GPU加速**: +- **单次OCR耗时**: 可能降至0.5-1秒 +- **总耗时**: 可能降至1-2秒 + +**如果优化OCR调用次数**: +- **减少1次OCR调用**: 节省约3-4秒 +- **提前返回**: 可以节省后续OCR调用 + +### 24.5 OCR预处理最佳实践 + +1. **统一使用预处理**: 所有OCR操作前都使用 `preprocess_for_ocr()` 预处理 +2. **保存预处理图像**: 保存预处理后的图像,便于调试和分析 +3. **调整预处理参数**: 根据实际效果调整预处理参数(放大倍数、对比度等) +4. **监控OCR性能**: 定期监控OCR耗时,识别性能瓶颈 +5. **优化OCR区域**: 精确裁剪OCR区域,减少不必要的图像内容 + +--- + +## 文档总结 + +本文档详细介绍了抖音福袋挂机项目的技术实现,包括: + +1. **项目概述**: 项目简介、核心功能、技术栈 +2. **项目架构**: 整体架构、目录结构、设计模式 +3. **完整流程图**: 主循环流程、阶段诊断流程、福袋处理流程 +4. **关键函数说明**: 所有关键函数的详细说明(参数、返回值、调用位置、实现细节) +5. **底层操作函数**: ADB操作、截图、OCR、图像处理等 +6. **核心类和数据结构**: `fudai_analyse` 类、预约数据结构等 +7. **配置系统**: 所有配置项的详细说明 +8. **状态管理机制**: 运行状态、预约状态、等待开奖状态等 +9. **错误处理和异常情况**: 常见错误和恢复机制 +10. **代码示例**: 完整运行示例、各模块使用示例 +11. **模块详解**: 各模块的职责和实现 +12. **数据流和状态管理**: 数据流图、状态转换图 +13. **关键技术实现**: 像素检测、模板匹配、OCR、并行处理 +14. **扩展指南和最佳实践**: 如何扩展功能、最佳实践 +15. **关键文件索引和调试指南**: 文件索引、调试方法 + +**文档版本**: V3.0 +**最后更新**: 2025-12-30 +**维护者**: AI助手、开发者 + +--- + +**文档状态**: ✅ 已完成 +**当前进度**: 已完成所有章节(1-26章) +**文档完整性**: 100% + +**新增章节**: +- 第16章:高级主题和深入理解 +- 第17章:预约验证和错误处理模块 +- 第18章:核心处理函数详解补充 +- 第19章:工具函数和辅助模块详解 +- 第20章:检测功能详解 +- 第21章:导航和滑动操作详解 +- 第22章:桌面检测和自救机制详解 +- 第23章:日志系统详解 +- 第24章:OCR预处理和优化详解 +- 第25章:路径配置系统详解 +- 第26章:文本处理工具函数详解 + diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 00d7ace..8666f86 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -22,7 +22,6 @@ from douyin.detection import douyin_detection from douyin.fudai import douyin_fudai_detail from douyin.fudai import douyin_fudai_core from douyin.core import douyin_flow_control -from douyin.logging.action_tracker import track_action from douyin.other import douyin_live_room from douyin.reservation import douyin_reservation_logic from douyin.utils import douyin_config @@ -34,24 +33,8 @@ from douyin.handlers import douyin_swipe_handler from douyin.reservation import douyin_reservation_handler from douyin.stage import douyin_stage_handler -from .fudai_modules import ( - NavigationMixin, - StageDetectionMixin, - PopupHandlerMixin, - LotteryResultMixin, - RoomUtilsMixin, - MainLogicMixin, -) - -class fudai_analyse( - NavigationMixin, - StageDetectionMixin, - PopupHandlerMixin, - LotteryResultMixin, - RoomUtilsMixin, - MainLogicMixin, -): +class fudai_analyse: """福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。""" # 类常量:魔法数字提取 @@ -74,12 +57,7 @@ class fudai_analyse( # 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部) self.operation = underlying_operations() - try: - import path_config - self.config_path = path_config.get_config_path() - except Exception: - import path_config - self.config_path = path_config.get_config_path() + self.config_path = "config/config.json" # 日志相关字段:完全独立的日志系统(不依赖原始代码) try: @@ -98,31 +76,6 @@ class fudai_analyse( self._last_log_tag = None # 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告 self._std_logger = None # type: ignore[assignment] - # 后台 tick:供等待循环期间执行轻量后台任务(可被覆盖) - # 示例用途:在等待直播间标题出现时处理弹窗、更新小状态等 - def _default_background_tick(): - try: - # 处理优惠券弹窗(如果存在) - if hasattr(self, "_check_coupon_popup") and callable(getattr(self, "_check_coupon_popup")): - try: - self._check_coupon_popup() - except Exception: - pass - # 处理购物红包弹窗(如果存在) - if hasattr(self, "_check_shopping_redpacket_popup") and callable(getattr(self, "_check_shopping_redpacket_popup")): - try: - self._check_shopping_redpacket_popup() - except Exception: - pass - except Exception: - pass - - # 绑定为实例方法 - try: - self.background_tick = _default_background_tick # type: ignore[assignment] - except Exception: - # 若绑定失败,保证属性存在 - self.background_tick = lambda: None # type: ignore[assignment] # 初始化统一日志系统和traceId # 确保日志系统已配置(在实例化之前) @@ -278,14 +231,9 @@ class fudai_analyse( self.queue_full_waiting_at_earliest: bool = False # 预约队列状态文件(供 WebGUI / 其他进程查看) - try: - import path_config - self._reservations_state_path: str = path_config.get_reservations_path() - except Exception: - # 回退到旧路径(向后兼容) - self._reservations_state_path: str = os.path.join( - os.path.dirname(__file__), "state", "reservations.json" - ) + self._reservations_state_path: str = os.path.join( + os.path.dirname(__file__), "state", "reservations.json" + ) # 运行时直播间标题和位置映射表(用于回退校验) # 格式:{room_pos: (room_title, room_title_raw)} @@ -313,9 +261,32 @@ class fudai_analyse( self.load_config() # ===== 兼容原始脚本的一些简单封装方法 ===== - # RoomUtilsMixin 已提供 _find_room_pos_by_title 和 _record_room_title_and_pos 方法 + def _find_room_pos_by_title( + self, target_title: str, target_title_raw: str = "" + ) -> int | None: + """根据直播间标题在运行时映射表中查找对应的位置。 - # NavigationMixin 已提供 click 和 load_config 方法 + 返回: + 如果找到匹配的位置,返回位置值;否则返回 None + """ + return douyin_reservation_handler.ReservationHandler.find_room_pos_by_title( + self, target_title, target_title_raw + ) + + def _record_room_title_and_pos(self) -> None: + """记录当前直播间的标题和位置到运行时映射表。 + + 用于预约回退校验时验证位置信息。 + """ + douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self) + + def click(self, x: int, y: int) -> None: + """兼容原版 fudai_analyse.click:转发到底层 operation.click。""" + douyin_helpers.HelperFunctions.click(self, x, y) + + def load_config(self) -> None: + """从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。""" + douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined] # ========== 兼容旧入口:主循环 ========== def fudai_choujiang( @@ -347,21 +318,10 @@ class fudai_analyse( start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] try: - try: - import path_config - actions_log_path = path_config.get_actions_log_path() - log_dir = path_config.get_logs_dir() - except Exception: - # 回退到旧路径(向后兼容) - try: - import path_config - actions_log_path = path_config.get_actions_log_path() - log_dir = path_config.get_logs_dir() - except Exception: - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - log_dir = os.path.dirname(actions_log_path) + actions_log_path = os.path.join( + os.path.dirname(__file__), "logs", "actions.log" + ) + log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( @@ -418,16 +378,10 @@ class fudai_analyse( end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - try: - import path_config - actions_log_path = path_config.get_actions_log_path() - log_dir = path_config.get_logs_dir() - except Exception: - # 回退到旧路径(向后兼容) - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - log_dir = os.path.dirname(actions_log_path) + actions_log_path = os.path.join( + os.path.dirname(__file__), "logs", "actions.log" + ) + log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( @@ -498,10 +452,56 @@ class fudai_analyse( time.sleep(1.0) # ========== 阶段诊断 ========== - # StageDetectionMixin 已提供 _diagnose_stage_from_current_screen 方法 + def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]: + """封装到子模块的阶段诊断入口。""" + return douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen( + self + ) # ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ========== - # NavigationMixin 和 StageDetectionMixin 已提供截图和坐标转换相关方法 + def cut_pic( + self, + x_top: int = 1, + y_top: int = 1, + x_bottom: int = 2, + y_bottom: int = 2, + target: str = "", + cut_pic_name: str = "", + y_pianyi: int = 0, + ) -> None: + """裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。""" + douyin_screenshot_handler.ScreenshotHandler.cut_pic( + self, x_top, y_top, x_bottom, y_bottom, target, cut_pic_name, y_pianyi + ) + + def _read_pixel_stage_state( + self, return_details: bool = False + ) -> dict | tuple[dict, dict]: + """读取像素阶段状态(用于阶段诊断)。 + + 参数: + return_details: 是否返回每个检测步骤的详细信息(包括分数) + + 返回: + dict: 检测结果(return_details=False时) + tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时) + """ + return douyin_helpers.HelperFunctions.read_pixel_stage_state( + self, return_details + ) + + def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]: + """将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。 + + 返回 (scaled_x, scaled_y) + """ + return douyin_screenshot_handler.ScreenshotHandler.scale_from_base( + self, base_x, base_y + ) + + def _save_step_screenshot(self, label: str) -> None: + """保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。""" + douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label) def _check_in_live_room_by_icon( self, @@ -538,38 +538,24 @@ class fudai_analyse( ) # ========== 弹窗 / 人机校验 ========== - # PopupHandlerMixin 已提供 _check_coupon_popup 和 _check_shopping_redpacket_popup 方法 + def _check_coupon_popup(self) -> bool: + """购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。""" + return douyin_popup_handler.PopupHandler.check_coupon_popup(self) + + def _check_shopping_redpacket_popup(self) -> bool: + """购物红包中央弹窗。""" + return douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup(self) # ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ========== - @track_action("run_once_basic") - def run_once_basic(self, recursion_depth: int = 0) -> None: # type: ignore[complexity] + def run_once_basic(self) -> None: # type: ignore[complexity] """单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。 - 参数: - recursion_depth: 递归深度,用于防止栈溢出(默认 0) - 注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。 """ from douyin.reservation import douyin_reservation_logic # 确保在函数作用域内可用 start_time = time.time() - - # 0.1. 优先检查预约回退直接参与标志(避免陷入循环) - reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False) - if reservation_direct_attend: - try: - self._log_kv( - "预约", - "[预约] 检测到预约回退直接参与标志,立即执行参与逻辑", - reservation_direct_attend=reservation_direct_attend, - ) - except Exception: - pass - # 执行直接参与逻辑(跳过其他检查) - self._handle_reservation_direct_attend() - return - - # 0.2. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 + # 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 if getattr(self, "_waiting_for_lottery_result", False): try: # 检查是否有高价值预约需要处理(除非遇到高价值预约,否则应该等待福袋开奖) @@ -852,24 +838,31 @@ class fudai_analyse( # 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间" try: - # 从状态文件加载预约队列,保持预约记录的持久化 + # 每次开始运行时丢弃旧的预约队列,不加载状态文件 try: - # 检查是否已经初始化预约队列 - if not hasattr(self, "reservations") or self.reservations is None: - self.reservations = [] - # 如果是第一次运行,从状态文件加载预约队列 + # 如果是第一次运行,清空预约队列,不加载状态文件 is_first_run = getattr(self, "_first_run_once_basic", True) + # 记录清空前的队列状态(用于调试) + old_reservations_count = 0 + try: + old_reservations_count = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + except Exception: + pass if is_first_run: try: self._log_kv( "预约", - "[预约] 第一次运行:清空预约队列,确保每次启动都是干净状态", + "[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件", + old_reservations_count=old_reservations_count, ) except Exception: pass - # 清空预约队列(强制清空,确保每次启动时队列为空) try: # 先记录清空前的状态 @@ -887,6 +880,7 @@ class fudai_analyse( # 同时清空状态文件,确保外部查看时也是空的 try: + state_path = getattr(self, "_reservations_state_path", None) if state_path: # 写入空队列到状态文件 @@ -932,14 +926,13 @@ class fudai_analyse( ) except Exception: pass - # 标记已运行过 try: self._first_run_once_basic = False except Exception: pass else: - # 如果不是第一次运行,保持当前内存中的预约队列 + # 如果不是第一次运行,也记录日志(用于调试) try: current_count = ( len(self.reservations) @@ -954,6 +947,9 @@ class fudai_analyse( ) except Exception: pass + + # 不再从状态文件加载预约数据,每次启动时都从空队列开始 + # 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空 except Exception as exc: try: self._log_kv( @@ -1626,23 +1622,11 @@ class fudai_analyse( pass # 为避免递归过深,仅在当前检测到不在抖音前台的场景下递归一次; # 自救完成后前台包名应为抖音,下一次 run_once_basic 将不会再次进入自救分支。 - MAX_RECURSION_DEPTH = 3 - if recursion_depth >= MAX_RECURSION_DEPTH: - try: - self._log_kv( - "流程", - "run_once_basic:达到最大递归深度,停止递归", - recursion_depth=recursion_depth, - max_depth=MAX_RECURSION_DEPTH, - ) - except Exception: - pass - return try: self.operation.delay(0.5) except Exception: time.sleep(0.5) - self.run_once_basic(recursion_depth + 1) + self.run_once_basic() return except Exception as e: try: @@ -2204,11 +2188,6 @@ class fudai_analyse( 次数=2, ) self.operation.delay(self.ENTER_LIVE_FINAL_DELAY) - # 标记刚刚切换直播间,后续读取标题时会等待标题出现 - try: - self._just_switched_room = True - except Exception: - pass except Exception as e: self._log_kv("流程", "处理推荐页面时出错", error=str(e)) # 如果出错,尝试回退 @@ -2265,26 +2244,79 @@ class fudai_analyse( elapsed_seconds=round(elapsed, 2), ) - # LotteryResultMixin 已提供 _check_lottery_result_by_ocr 和 _handle_lottery_result_by_ocr 方法 + def _check_lottery_result_by_ocr(self) -> Optional[str]: + """通过OCR识别开奖结果按钮区域,返回识别到的文本类型。""" + return douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(self) -def _shot_and_diagnose(self, tag: str, msg: str, device_id: str, diagnose: bool = True) -> None: - """截图并执行阶段诊断(兼容旧版调用方式)。""" - douyin_helpers.HelperFunctions.shot_and_diagnose(self, tag, msg, device_id, diagnose) + def _handle_lottery_result_by_ocr(self, result_type: str) -> None: + """根据OCR识别结果处理开奖结果。 + + 参数: + result_type: "我知道了" 或 "立即领取奖品" + """ + douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type) + + def _shot_and_diagnose( + self, tag: str, msg: str, device_id: str, diagnose: bool = True + ) -> None: + """截图并执行阶段诊断(兼容旧版调用方式)。 + + Args: + tag: 日志标签 + msg: 日志消息 + device_id: 设备ID + diagnose: 是否执行阶段诊断(默认True) + """ + douyin_helpers.HelperFunctions.shot_and_diagnose( + self, tag, msg, device_id, diagnose + ) # ========== 基础动作封装 ========== - # NavigationMixin 已提供导航相关方法 + def swipe_up_to_next_live(self) -> None: + """上滑切换直播间(简单版封装)。 - # RoomUtilsMixin 已提供 _seek_reservation_room 方法 + 注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间), + 则不允许上划离开预约直播间,直接返回。 + """ + douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(self) + + def _return_to_recommend_and_reenter_live(self) -> None: + """返回推荐页面并重新进入直播间。 + + 通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。 + """ + douyin_swipe_handler.SwipeHandler.return_to_recommend_and_reenter_live(self) + + def swipe_down_back_from_live(self) -> None: + """上划回退到上一个直播间(供预约/无福袋逻辑使用)。""" + douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(self) + + def _maybe_reset_after_swipes(self) -> int: + """达到切换阈值后,在当前直播间页面回退到第一个直播间。 + + 返回: + 重置后的滑动次数(通常为0) + """ + return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self) + + def _seek_reservation_room(self, item: dict[str, Any]) -> bool: + """根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。 + + 说明: + - 使用 high_value_fudai_max_swipe_back 约束最大回退次数; + - 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。 + """ + return douyin_reservation_handler.ReservationHandler.seek_reservation_room( + self, item + ) # ========== 福袋相关 ========== - @track_action("handle_reservation_direct_attend") def _handle_reservation_direct_attend(self) -> None: """预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。""" douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend( self ) - @track_action("handle_in_fudai_detail") def _handle_in_fudai_detail(self) -> None: """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。""" start_time = time.time() @@ -3014,23 +3046,6 @@ def _shot_and_diagnose(self, tag: str, msg: str, device_id: str, diagnose: bool remain_seconds=remain_seconds, future_ts=int(future_timestamp), ) - # 参与成功,重置兜底重试计数,避免后续兜底逻辑误触 - try: - self._fudai_detail_retry_count = 0 - except Exception: - pass - # 增加额外诊断日志,便于排查进入等待开奖阶段的时序问题 - try: - self._log_kv( - "参与", - "进入等待开奖阶段", - remain_seconds=remain_seconds, - future_ts=int(future_timestamp), - ) - except Exception: - pass - except Exception: - pass # 检查是否是预约福袋,如果是,清除锁定期并从预约队列中移除已完成的预约 try: @@ -3229,13 +3244,6 @@ def _shot_and_diagnose(self, tag: str, msg: str, device_id: str, diagnose: bool except Exception: pass - # 重置详情页验证标志,开始新一轮福袋查找 - try: - self._fudai_detail_verified = False - self._fudai_detail_verified_retry = False - except Exception: - pass - room_pos_ref: List[int] = [0] opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref) if not opened: diff --git a/douyin/core/fudai_modules/base_interface.py b/douyin/core/fudai_modules/base_interface.py index 143e363..33aebba 100644 --- a/douyin/core/fudai_modules/base_interface.py +++ b/douyin/core/fudai_modules/base_interface.py @@ -86,3 +86,25 @@ class BaseFudaiMixin: + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/core/fudai_modules/fudai_lottery_result.py b/douyin/core/fudai_modules/fudai_lottery_result.py index 336c82a..d6caccc 100644 --- a/douyin/core/fudai_modules/fudai_lottery_result.py +++ b/douyin/core/fudai_modules/fudai_lottery_result.py @@ -41,3 +41,5 @@ class LotteryResultMixin: + + diff --git a/douyin/core/fudai_modules/fudai_main_logic.py b/douyin/core/fudai_modules/fudai_main_logic.py index 3d0ca01..694f95f 100644 --- a/douyin/core/fudai_modules/fudai_main_logic.py +++ b/douyin/core/fudai_modules/fudai_main_logic.py @@ -70,9 +70,39 @@ class MainLogicMixin(BaseFudaiMixin): self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400 # 加载配置 + # #region agent log + import json + import time as time_module + from path_config import get_debug_log_path + current_ts = int(time_module.time() * 1000) + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{current_ts}_load_config_call", + "timestamp": current_ts, + "location": "fudai_main_logic.py:73", + "message": "调用 load_config 方法", + "data": {"method": "load_config", "action": "call"}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp2" + }) + '\n') + # #endregion self._safe_operation_call("load_config") # 主循环 + # #region agent log + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{current_ts}_run_once_basic_call", + "timestamp": current_ts, + "location": "fudai_main_logic.py:76", + "message": "调用 run_once_basic 方法", + "data": {"method": "run_once_basic", "action": "call"}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp2" + }) + '\n') + # #endregion self._safe_operation_call("run_once_basic") def _handle_reservation_direct_attend(self) -> None: @@ -83,45 +113,157 @@ class MainLogicMixin(BaseFudaiMixin): ) def _handle_in_fudai_detail(self) -> None: - """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。""" + """已经在福袋详情页:执行点击参与福袋的核心逻辑。""" start_time = time.time() - # 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋 - # 这里应该包含主要的福袋处理逻辑 - # 由于代码太长,这里暂时保留调用原有handler的逻辑 + # #region agent log + import json + from path_config import get_debug_log_path + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{int(start_time * 1000)}_call_check", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:85", + "message": "开始检查 _handle_in_fudai_detail 方法调用", + "data": {"method": "_handle_in_fudai_detail", "action": "start"}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1" + }) + '\n') + # #endregion + try: - from douyin.fudai import douyin_fudai_flow - # 动态检查FudaiFlow是否存在 - if hasattr(douyin_fudai_flow, 'FudaiFlow'): - flow_class = getattr(douyin_fudai_flow, 'FudaiFlow') - if hasattr(flow_class, 'handle_in_fudai_detail'): - flow_class.handle_in_fudai_detail(self) - else: - self._safe_log("警告", "FudaiFlow.handle_in_fudai_detail 方法不可用") + # 直接调用福袋参与功能 + from douyin.fudai import douyin_fudai_core + + # #region agent log + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{int(start_time * 1000)}_import_check", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:91", + "message": "导入 douyin_fudai_core 模块成功", + "data": {"module": "douyin.fudai.douyin_fudai_core", "status": "imported"}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1" + }) + '\n') + # #endregion + + # 检查方法是否存在 + # #region agent log + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{int(start_time * 1000)}_method_check", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:93", + "message": "检查 attend_choujiang 方法存在性", + "data": { + "method_exists": hasattr(douyin_fudai_core, 'attend_choujiang'), + "module_attrs": [attr for attr in dir(douyin_fudai_core) if 'attend' in attr.lower()] + }, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1" + }) + '\n') + # #endregion + + attend_result = douyin_fudai_core.attend_choujiang(self) + + # #region agent log + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{int(start_time * 1000)}_method_call", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:93", + "message": "调用 attend_choujiang 方法完成", + "data": {"method": "attend_choujiang", "result": attend_result}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1" + }) + '\n') + # #endregion + + if attend_result: + self._safe_log("参与", "福袋参与成功") else: - self._safe_log("警告", "FudaiFlow 类不可用") + self._safe_log("参与", "福袋参与失败") + except Exception as e: - self._safe_log("错误", "_handle_in_fudai_detail 调用失败", error=str(e)) + # #region agent log + with open(get_debug_log_path(), 'a', encoding='utf-8') as f: + f.write(json.dumps({ + "id": f"log_{int(start_time * 1000)}_error", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:100", + "message": "_handle_in_fudai_detail 执行异常", + "data": {"error": str(e), "error_type": type(e).__name__}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1" + }) + '\n') + # #endregion + + self._safe_log("错误", "_handle_in_fudai_detail 执行失败", error=str(e)) elapsed = time.time() - start_time - self._safe_log( - "性能", - "_handle_in_fudai_detail 耗时", - elapsed_seconds=round(elapsed, 2) - ) + # 限制性能日志输出频率,避免过多输出 + current_time = time.time() + last_perf_log_time = getattr(self, "_last_perf_log_time", 0) + if current_time - last_perf_log_time >= 5.0: # 至少间隔5秒才输出性能日志 + self._safe_log( + "性能", + "_handle_in_fudai_detail 耗时", + elapsed_seconds=round(elapsed, 2) + ) + self._last_perf_log_time = current_time def _handle_live_room_has_or_not_fudai(self) -> None: """直播间有无福袋的处理逻辑。""" try: - from douyin.fudai import douyin_fudai_flow - # 动态检查FudaiFlow是否存在 - if hasattr(douyin_fudai_flow, 'FudaiFlow'): - flow_class = getattr(douyin_fudai_flow, 'FudaiFlow') - if hasattr(flow_class, 'handle_live_room_has_or_not_fudai'): - flow_class.handle_live_room_has_or_not_fudai(self) - else: - self._safe_log("警告", "FudaiFlow.handle_live_room_has_or_not_fudai 方法不可用") + # 使用 flow_control 来查找和打开福袋 + from douyin.core import douyin_flow_control + room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)] + opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref) + + if opened: + # 成功打开福袋详情,调用参与逻辑 + self._handle_in_fudai_detail() + self._safe_log("流程", "_handle_live_room_has_or_not_fudai:成功处理福袋") else: - self._safe_log("警告", "FudaiFlow 类不可用") + # 无福袋,交给 flow_control 的"无福袋处理"逻辑 + # 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房) + try: + needswitch_cfg = bool(getattr(self, "needswitch", True)) + except Exception: + needswitch_cfg = True + + wait_times_ref = [0] + swipe_times_ref = [0] + reservation_focus_until_ts_ref = [0.0] + reset_to_list_after_reservations_ref = [False] + douyin_flow_control.handle_no_fudai_situation( + self, + x=0, + swipe_times=0, + wait_times_ref=wait_times_ref, + needswitch=needswitch_cfg, + reservation_focus_until_ts=0.0, + reservations=[], + room_pos=room_pos_ref[0], + post_switch_delay_s=1.5, + swipe_up_switch_callback=self.swipe_up_to_next_live, # type: ignore[attr-defined] + swipe_down_back_callback=lambda: None, + sort_reservations_callback=lambda: None, + clear_reservations_callback=lambda: None, + write_state_callback=lambda: None, + back_to_list_callback=lambda: None, + into_list_callback=lambda: None, + reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, + reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, + swipe_times_ref=swipe_times_ref, + ) + self._safe_log("流程", "_handle_live_room_has_or_not_fudai:未找到福袋,已处理切换逻辑") + except Exception as e: - self._safe_log("错误", "_handle_live_room_has_or_not_fudai 调用失败", error=str(e)) + self._safe_log("错误", "_handle_live_room_has_or_not_fudai 执行失败", error=str(e)) diff --git a/douyin/core/fudai_modules/fudai_room_utils.py b/douyin/core/fudai_modules/fudai_room_utils.py index c1d1322..5362c49 100644 --- a/douyin/core/fudai_modules/fudai_room_utils.py +++ b/douyin/core/fudai_modules/fudai_room_utils.py @@ -60,3 +60,25 @@ class RoomUtilsMixin: + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index d880313..5ac62cd 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767009711.8732166, + "updated_ts": 1767105402.1814883, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/detection/core/__init__.py b/douyin/detection/core/__init__.py index 222b4eb..ed5963b 100644 --- a/douyin/detection/core/__init__.py +++ b/douyin/detection/core/__init__.py @@ -32,3 +32,25 @@ __all__ = [ + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/detection/douyin_pixel.py b/douyin/detection/douyin_pixel.py index 3b32246..1b97fbf 100644 --- a/douyin/detection/douyin_pixel.py +++ b/douyin/detection/douyin_pixel.py @@ -644,84 +644,84 @@ def detect_fansclub_join_red_area( def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: - """通过像素检测右上角x和xin图标区域,判断是否在直播间。 + """通过像素检测多边形区域内的白色像素,判断是否在直播间。 - 检测右上角区域(60%-100%宽度,0%-40%高度)的像素特征: - - x图标:通常是白色或浅色的X形状 - - xin图标:通常是粉色/红色的心形图标 + 检测指定多边形区域内的白色像素比例,基于1080x2400分辨率: + - 多边形顶点坐标(12个点): + (1002,172), (999,174), (1011,186), (999,199), (1002,202), (1013,190), + (1025,201), (1028,198), (1017,187), (1028,174), (1025,172), (1014,184) + - 白色像素比例 >= 0.8 则认为在直播间内 返回: - (detected, confidence) 其中 confidence 为置信度(0.0~1.0) + (detected, confidence) 其中 confidence 为白色像素比例(0.0~1.0) """ try: + from PIL import ImageDraw + import numpy as np + width, height = pic_rgb.size # 缩放坐标到实际尺寸(基于1080x2400) scale_x = width / 1080.0 scale_y = height / 2400.0 - # 检测区域:右上角(60%-100%宽度,0%-40%高度) - x1 = int(648 * scale_x) # 60%宽度 = 648 - y1 = 0 - x2 = width # 100%宽度 - y2 = int(960 * scale_y) # 40%高度 = 960 + # 多边形顶点坐标(基于1080x2400基准分辨率) + polygon_base_points = [ + (1002, 172), (999, 174), (1011, 186), (999, 199), (1002, 202), (1013, 190), + (1025, 201), (1028, 198), (1017, 187), (1028, 174), (1025, 172), (1014, 184) + ] + + # 缩放多边形坐标到实际截图尺寸 + polygon_points = [ + (int(x * scale_x), int(y * scale_y)) + for x, y in polygon_base_points + ] - # 确保坐标在范围内 - x1 = max(0, min(x1, width)) - y1 = max(0, min(y1, height)) - x2 = max(0, min(x2, width)) - y2 = max(0, min(y2, height)) + # 创建多边形mask + mask = Image.new('L', (width, height), 0) + draw = ImageDraw.Draw(mask) + + # 绘制多边形(填充为白色) + draw.polygon(polygon_points, fill=255) - if x1 >= x2 or y1 >= y2: + # 将mask转换为numpy数组 + mask_array = np.array(mask) + + # 获取原始图像的像素数据 + img_array = np.array(pic_rgb) + + # 计算多边形内部的总像素数 + total_pixels = np.sum(mask_array > 0) + + if total_pixels == 0: return False, 0.0 - # 采样检测点 - step_x = max(1, (x2 - x1) // 20) - step_y = max(1, (y2 - y1) // 20) - - # 检测特征: - # 1. 白色/浅色像素(x图标) - # 2. 粉色/红色像素(xin图标) + # 计算多边形内部的白色像素(RGB值都>=240) white_count = 0 - pink_red_count = 0 - total_samples = 0 - - for y in range(y1, y2, step_y): - for x in range(x1, x2, step_x): - try: - r, g, b = pic_rgb.getpixel((x, y)) - total_samples += 1 - - # 检测白色/浅色(x图标):RGB值都较高且接近 - if ( - r > 200 - and g > 200 - and b > 200 - and abs(r - g) < 30 - and abs(g - b) < 30 - ): + for y in range(height): + for x in range(width): + if mask_array[y, x] > 0: # 在多边形内部 + r, g, b = img_array[y, x] + if r >= 240 and g >= 240 and b >= 240: # 白色阈值 white_count += 1 - # 检测粉色/红色(xin图标):R值高,G和B相对较低 - if r > 200 and (r - g) > 50 and (r - b) > 50: - pink_red_count += 1 - except Exception as e: # type: ignore[general-exception] - continue + white_ratio = white_count / total_pixels if total_pixels > 0 else 0.0 - if total_samples == 0: - return False, 0.0 + # 白色像素比例 >= 0.8 则认为在直播间内 + detected = white_ratio >= 0.8 + confidence = white_ratio # 置信度就是白色比例 - # 计算置信度 - white_ratio = white_count / total_samples if total_samples > 0 else 0 - pink_red_ratio = pink_red_count / total_samples if total_samples > 0 else 0 + # 计算多边形边界框(用于调试图像) + if polygon_points: + x_coords = [p[0] for p in polygon_points] + y_coords = [p[1] for p in polygon_points] + x1 = max(0, min(x_coords)) + y1 = max(0, min(y_coords)) + x2 = min(width, max(x_coords)) + y2 = min(height, max(y_coords)) + else: + x1, y1, x2, y2 = 0, 0, 0, 0 - # 如果白色或粉色/红色像素占比足够高,认为检测到图标 - # 阈值:白色>=5% 或 粉色/红色>=3% - detected = white_ratio >= 0.05 or pink_red_ratio >= 0.03 - - # 计算置信度(基于检测到的像素比例) - confidence = min(1.0, max(white_ratio * 10, pink_red_ratio * 15)) - - # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 + # 保存调试图像(检测结果) try: from douyin.handlers import douyin_screenshot_manager @@ -730,15 +730,15 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: operation_type="pixel_detect", picname="live_room_icons", step="detected" if detected else "not_detected", - coords=(x1, y1, x2, y2), # 标注识别区域 + coords=(x1, y1, x2, y2), # 标注识别区域边界框 extra_info={ "white_ratio": round(white_ratio, 4), - "pink_red_ratio": round(pink_red_ratio, 4), "white_count": white_count, - "pink_red_count": pink_red_count, - "total_samples": total_samples, + "total_pixels": total_pixels, "confidence": round(confidence, 4), + "threshold": 0.8, "result": "success" if detected else "failed", + "polygon_points": len(polygon_points), }, ) if debug_path: @@ -746,10 +746,11 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: import logging logging.info( - "[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, pink_red_ratio=%.4f, confidence=%.4f, result=%s", + "[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s", debug_path, white_ratio, - pink_red_ratio, + white_count, + total_pixels, confidence, "success" if detected else "failed", ) @@ -758,7 +759,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: except Exception as e: # type: ignore[general-exception] pass - return detected, confidence + return bool(detected), float(confidence) except Exception as e: # type: ignore[general-exception] return False, 0.0 @@ -868,6 +869,7 @@ def read_pixel_stage_state_from_screenshot( "has_attend_button_red": False, "has_fansclub_join_red": False, "has_fudai_detail": False, + "has_live_room_pixel": False, # 直播间图标像素检测(多边形区域白色像素检测) } details: dict[str, dict] = {} @@ -884,6 +886,7 @@ def read_pixel_stage_state_from_screenshot( coupon_threshold = None attend_button_threshold = None fansclub_threshold = None + live_room_pixel_threshold = None if analyser is not None: try: coupon_threshold = float( @@ -903,7 +906,30 @@ def read_pixel_stage_state_from_screenshot( ) except Exception as e: # type: ignore[general-exception] pass + try: + live_room_pixel_threshold = float( + getattr(analyser, "live_room_match_threshold", None) or 0.8 + ) + except Exception as e: # type: ignore[general-exception] + pass + # 定义直播间图标像素检测包装函数 + def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]: + """直播间图标像素检测包装函数,返回 (bool, dict) 格式""" + try: + detected, confidence = detect_live_room_icons_by_pixel(pic) + threshold = live_room_pixel_threshold or 0.8 + is_detected = detected and confidence >= threshold + return is_detected, { + "method": "pixel_detection", + "confidence": confidence, + "effective_threshold": threshold, + } + except Exception as e: # type: ignore[general-exception] + return False, {"method": "pixel_detection", "error": str(e)} + + # 模板匹配已删除,只使用像素检测 + detection_tasks = { "has_coupon_bg": lambda pic: detect_coupon_popup_background( pic, @@ -936,10 +962,11 @@ def read_pixel_stage_state_from_screenshot( return_info=True, analyser=analyser, ), + "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测) } - # 使用线程池并行执行检测 - with ThreadPoolExecutor(max_workers=6) as executor: + # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) + with ThreadPoolExecutor(max_workers=8) as executor: # 提交所有任务 future_to_key = { executor.submit(detect_func, pic_rgb): key @@ -962,6 +989,7 @@ def read_pixel_stage_state_from_screenshot( "detected": bool(is_detected), "method": info.get("method", "unknown"), "template_score": info.get("template_score"), + "confidence": info.get("confidence"), # 添加confidence支持(用于像素检测) "task_count": info.get("task_count"), # 添加task_count支持 "red_ratio": info.get("red_ratio"), # 添加red_ratio支持 "effective_threshold": info.get("effective_threshold"), @@ -987,3 +1015,91 @@ def read_pixel_stage_state_from_screenshot( if return_details: return state, details return state + + # 模板匹配已删除,只使用像素检测 + + detection_tasks = { + "has_coupon_bg": lambda pic: detect_coupon_popup_background( + pic, + return_info=True, + template_threshold=coupon_threshold, + analyser=analyser, + ), + "has_redpacket_bg": detect_redpacket_popup_background, + "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup( + pic, lucky_draw_red_ratio_threshold, return_info=True + ), + "has_attend_button_red": lambda pic: detect_attend_button_red_area( + pic, + return_info=True, + red_ratio_threshold=attend_button_threshold, + analyser=analyser, + ), + "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area( + pic, + return_info=True, + red_ratio_threshold=fansclub_threshold, + analyser=analyser, + ), + "has_fudai_detail": lambda pic: detect_fudai_detail_page( + pic, + resolution_ratio_x, + resolution_ratio_y, + y_pianyi, + fudai_template_threshold, + return_info=True, + analyser=analyser, + ), + "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测) + } + + # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) + with ThreadPoolExecutor(max_workers=8) as executor: + # 提交所有任务 + future_to_key = { + executor.submit(detect_func, pic_rgb): key + for key, detect_func in detection_tasks.items() + } + + # 收集结果 + for future in as_completed(future_to_key): + key = future_to_key[future] + try: + result = future.result() + + # 处理结果 + if isinstance(result, tuple): + # 检测函数返回 (bool, dict) 格式 + is_detected, info = result + state[key] = bool(is_detected) + if return_details: + details[key] = { + "detected": bool(is_detected), + "method": info.get("method", "unknown"), + "template_score": info.get("template_score"), + "confidence": info.get("confidence"), # 添加confidence支持(用于像素检测) + "task_count": info.get("task_count"), # 添加task_count支持 + "red_ratio": info.get("red_ratio"), # 添加red_ratio支持 + "effective_threshold": info.get("effective_threshold"), + "reason": info.get("reason"), + } + else: + # 其他检测返回 bool(不应该发生,因为所有检测都支持return_info) + state[key] = bool(result) + if return_details: + details[key] = { + "detected": bool(result), + "method": "unknown", + } + except Exception as e: # type: ignore[general-exception] + # 如果某个检测失败,保持默认值 False + state[key] = False + if return_details: + details[key] = { + "detected": False, + "error": str(e), + } + + if return_details: + return state, details + return state \ No newline at end of file diff --git a/douyin/detection/douyin_pixel.py.backup b/douyin/detection/douyin_pixel.py.backup new file mode 100644 index 0000000..b9a012d --- /dev/null +++ b/douyin/detection/douyin_pixel.py.backup @@ -0,0 +1,1129 @@ +# pyright: reportGeneralTypeIssues=false +# pyright: reportAttributeAccessIssue=false +# pyright: reportMissingModuleSource=false +# pyright: reportUnknownMemberType=false +# pyright: reportUnknownVariableType=false +import os +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Any, Optional + +from PIL import Image + + +def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]: + try: + if not pic_path or (not os.path.exists(pic_path)): + return None + pic = Image.open(pic_path) + pic.load() # Force load to catch truncated files early + return pic.convert("RGB") + except (OSError, IOError, SyntaxError): + # Handle truncated image files + return None + except Exception as e: # type: ignore[general-exception] + return None + + +def detect_coupon_popup_background( + pic_rgb: Image.Image, + return_info: bool = False, + template_threshold: float | None = None, + analyser: Any = None, +) -> bool | tuple[bool, dict]: + """检测底部优惠券大弹窗(仅模板匹配)。 + + 模板匹配区域(基于1080x2400基准): + - 左上: (9, 1173) + - 右下: (1079, 2255) + 使用 `assets/coupon.png` 作为模板。 + + 参数: + pic_rgb: RGB格式的整屏截图 + return_info: 是否返回详细信息(包含检测分数) + template_threshold: 模板匹配阈值(默认0.75,如果提供则使用,否则从analyser读取) + analyser: analyser对象,用于读取配置阈值 + + 返回: + bool: 是否检测到优惠券背景(return_info=False时) + tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时) + """ + try: + try: + import cv2 # type: ignore[import-untyped] + import numpy as np # type: ignore[import-untyped] + except Exception as e: # type: ignore[general-exception] + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": "opencv_unavailable", + } + return False + + width, height = pic_rgb.size + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + x1 = int(9 * scale_x) + y1 = int(1173 * scale_y) + x2 = int(1079 * scale_x) + y2 = int(2255 * scale_y) + + x1 = max(0, min(x1, width)) + y1 = max(0, min(y1, height)) + x2 = max(0, min(x2, width)) + y2 = max(0, min(y2, height)) + + if x1 >= x2 or y1 >= y2: + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": "invalid_region", + } + return False + + bgr = cv2.cvtColor( # type: ignore[attr-defined] + np.array(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined] + ) + roi = bgr[y1:y2, x1:x2] # type: ignore[index] + if roi.size == 0: + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": "empty_roi", + } + return False + + # 使用统一的模板路径配置 + try: + import path_config + template_path = path_config.get_assets_dir() + "/coupon.png" + except Exception: + # 回退到旧路径(向后兼容) + base_dir = os.path.dirname(__file__) + template_path = os.path.join(base_dir, "assets", "coupon.png") + if not os.path.exists(template_path): + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": "template_not_found", + } + return False + + template = cv2.imread( # type: ignore[attr-defined,assignment] + template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined] + ) + if template is None: + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": "template_load_failed", + } + return False + if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]: + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": "template_too_large", + } + return False + + res = cv2.matchTemplate( # type: ignore[attr-defined] + roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _, max_val, _, _ = cv2.minMaxLoc(res) # type: ignore[attr-defined] + # 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值 + if template_threshold is not None: + threshold = float(template_threshold) + elif analyser is not None: + try: + threshold = float( + getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75 + ) + except Exception as e: # type: ignore[general-exception] + threshold = 0.75 + else: + threshold = 0.75 + result = max_val >= threshold + + if return_info: + reason_value: Optional[str] = None if result else "score_below_threshold" + return result, { + "method": "template_match", + "template_score": float(max_val), + "effective_threshold": threshold, + "reason": reason_value, + } + return result + except Exception as e: # type: ignore[general-exception] + if return_info: + return False, { + "method": "template_match", + "template_score": None, + "reason": f"exception: {str(e)}", + } + return False + + +def detect_redpacket_popup_background(_pic_rgb: Image.Image) -> bool: + """中央购物红包弹窗检测(暂时禁用,始终返回 False)。""" + return False + + +def detect_lucky_draw_result_popup( + pic_rgb: Image.Image, red_ratio_threshold: float = 0.8, return_info: bool = False +) -> bool | tuple[bool, dict]: + """检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。 + + 使用基准 1080x2400 坐标的检测区域: + - 左上: (181, 1261) + - 右下: (890, 1389) + """ + try: + width, height = pic_rgb.size + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + x1 = int(181 * scale_x) + y1 = int(1261 * scale_y) + x2 = int(890 * scale_x) + y2 = int(1389 * scale_y) + + # 边界与顺序 + x1, x2 = max(0, min(x1, width)), max(0, min(x2, width)) + y1, y2 = max(0, min(y1, height)), max(0, min(y2, height)) + if x1 > x2: + x1, x2 = x2, x1 + if y1 > y2: + y1, y2 = y2, y1 + + if x1 >= x2 or y1 >= y2: + return False + + # 双截图记录:保存实时操作截图(像素检测区域) + detect_roi = None + try: + from douyin.handlers import douyin_screenshot_manager + + detect_roi = pic_rgb.crop((x1, y1, x2, y2)) + douyin_screenshot_manager.save_latest_attempt( + detect_roi, operation_type="pixel_detect" + ) + + # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="lucky_draw_result", + step="before_detect", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "threshold": red_ratio_threshold, + "region_size": f"{x2-x1}x{y2-y1}", + }, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 像素检测前保存: %s, threshold=%s", + debug_path, + red_ratio_threshold, + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + red_count = 0 + total_samples = 0 + step_x = max(1, (x2 - x1) // 10) + step_y = max(1, (y2 - y1) // 10) + + for y in range(y1, y2, step_y): + for x in range(x1, x2, step_x): + try: + r, g, b = pic_rgb.getpixel((x, y)) + total_samples += 1 + # 根据实际检测结果:R: 245-255, G: 44-255, B: 85-255 + # 红色按钮检测:R >= 245 且 R 明显大于 G 和 B + if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50: + red_count += 1 + except Exception as e: # type: ignore[general-exception] + continue + + if total_samples == 0: + return False + + red_ratio = red_count / total_samples + result = red_ratio >= red_ratio_threshold + + # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + if result: + # 检测成功 + if detect_roi is None: + detect_roi = pic_rgb.crop((x1, y1, x2, y2)) + douyin_screenshot_manager.save_last_success( + detect_roi, operation_type="pixel_detect" + ) + + # 无论成功失败都保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="lucky_draw_result", + step="detected" if result else "not_detected", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "red_ratio": round(red_ratio, 4), + "red_count": red_count, + "total_samples": total_samples, + "threshold": red_ratio_threshold, + "result": "success" if result else "failed", + }, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f", + debug_path, + red_ratio, + red_ratio_threshold, + red_ratio, + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + # 如果请求详细信息,返回包含red_ratio的字典 + if return_info: + reason_value: Optional[str] = ( + None if result else "red_ratio_below_threshold" + ) + return result, { + "method": "pixel_detect", + "red_ratio": red_ratio, + "red_count": red_count, + "total_samples": total_samples, + "effective_threshold": red_ratio_threshold, + "reason": reason_value, + } + + return result + except Exception as e: # type: ignore[general-exception] + return False + + +def detect_attend_button_red_area( + pic_rgb: Image.Image, + return_info: bool = False, + red_ratio_threshold: float | None = None, + analyser: Any = None, +) -> bool | tuple[bool, dict]: + """检测参与按钮:大片红色区域。 + + 参与按钮通常在屏幕底部,有大片红色背景。 + 检测区域:(306,2030)-(780,2110) 基准1080x2400,但实际可能更宽 + 扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮 + """ + try: + width, height = pic_rgb.size + # 缩放坐标到实际尺寸 + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + # 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮) + x1 = int(200 * scale_x) # 扩展左侧 + y1 = int(2000 * scale_y) # 稍微上移 + x2 = int(880 * scale_x) # 扩展右侧 + y2 = int(2120 * scale_y) # 稍微下移 + + # 确保坐标在范围内 + x1 = max(0, min(x1, width)) + y1 = max(0, min(y1, height)) + x2 = max(0, min(x2, width)) + y2 = max(0, min(y2, height)) + + if x1 >= x2 or y1 >= y2: + return False + + # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="attend_button", + step="before_detect", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={"region_size": f"{x2-x1}x{y2-y1}"}, + ) + if debug_path: + try: + import logging + + logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + # 采样检测点:检测大片红色区域 + red_count = 0 + step_x = max(1, (x2 - x1) // 15) + step_y = max(1, (y2 - y1) // 10) + + for y in range(y1, y2, step_y): + for x in range(x1, x2, step_x): + try: + r, g, b = pic_rgb.getpixel((x, y)) + # 检测红色:R值高,G和B相对较低 + if r > 200 and (r - g) > 50 and (r - b) > 50: + red_count += 1 + except Exception as e: # type: ignore[general-exception] + continue + + # 如果红色像素占比足够高(至少25%),认为有大片红色背景 + total_samples = len(list(range(y1, y2, step_y))) * len( + list(range(x1, x2, step_x)) + ) + if total_samples == 0: + return False + + red_ratio = red_count / total_samples if total_samples > 0 else 0 + # 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值 + if red_ratio_threshold is not None: + threshold = float(red_ratio_threshold) + elif analyser is not None: + try: + threshold = float( + getattr(analyser, "attend_button_red_ratio_threshold", 0.25) or 0.25 + ) + except Exception as e: # type: ignore[general-exception] + threshold = 0.25 + else: + threshold = 0.25 + result = red_ratio >= threshold + + # 如果请求详细信息,返回包含red_ratio的字典 + if return_info: + reason_value: Optional[str] = ( + None if result else "red_ratio_below_threshold" + ) + return result, { + "method": "pixel_detect", + "red_ratio": red_ratio, + "red_count": red_count, + "total_samples": total_samples, + "effective_threshold": threshold, + "reason": reason_value, + } + + # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 + # 无论成功失败都保存debug截图 + try: + from douyin.handlers import douyin_screenshot_manager + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="attend_button", + step="detected" if result else "not_detected", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "red_ratio": round(red_ratio, 4), + "red_count": red_count, + "total_samples": total_samples, + "threshold": threshold, + "result": "success" if result else "failed", + }, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s", + debug_path, + red_ratio, + threshold, + "success" if result else "failed", + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + return result + except Exception: + if return_info: + return False, { + "method": "pixel_detect", + "red_ratio": None, + "reason": "exception", + } + return False + + +def detect_fansclub_join_red_area( + pic_rgb: Image.Image, + return_info: bool = False, + red_ratio_threshold: float | None = None, + analyser: Any = None, +) -> bool | tuple[bool, dict]: + """检测粉丝团加入:大片红色区域。 + + 粉丝团加入按钮通常在屏幕中下部,有大片红色背景。 + 检测区域:(200,1940)-(880,2140) 基准1080x2400 + """ + try: + width, height = pic_rgb.size + # 缩放坐标到实际尺寸 + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + # 检测区域(基准1080x2400) + x1 = int(200 * scale_x) + y1 = int(1940 * scale_y) + x2 = int(880 * scale_x) + y2 = int(2140 * scale_y) + + # 确保坐标在范围内 + x1 = max(0, min(x1, width)) + y1 = max(0, min(y1, height)) + x2 = max(0, min(x2, width)) + y2 = max(0, min(y2, height)) + + if x1 >= x2 or y1 >= y2: + if return_info: + return False, { + "method": "pixel_detect", + "red_ratio": None, + "reason": "invalid_region", + } + return False + + # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="fansclub_join", + step="before_detect", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={"region_size": f"{x2-x1}x{y2-y1}"}, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 粉丝团加入检测前保存: %s", + debug_path, + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + # 采样检测点:检测大片红色区域 + red_count = 0 + step_x = max(1, (x2 - x1) // 15) + step_y = max(1, (y2 - y1) // 10) + + for y in range(y1, y2, step_y): + for x in range(x1, x2, step_x): + try: + r, g, b = pic_rgb.getpixel((x, y)) + # 检测红色:R值高,G和B相对较低 + if r > 200 and (r - g) > 50 and (r - b) > 50: + red_count += 1 + except Exception: + continue + + # 如果红色像素占比足够高(至少25%),认为有大片红色背景 + total_samples = len(list(range(y1, y2, step_y))) * len( + list(range(x1, x2, step_x)) + ) + if total_samples == 0: + if return_info: + return False, { + "method": "pixel_detect", + "red_ratio": None, + "reason": "no_samples", + } + return False + + red_ratio = red_count / total_samples if total_samples > 0 else 0 + # 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值 + if red_ratio_threshold is not None: + threshold = float(red_ratio_threshold) + elif analyser is not None: + try: + threshold = float( + getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25 + ) + except Exception as e: # type: ignore[general-exception] + threshold = 0.25 + else: + threshold = 0.25 + result = red_ratio >= threshold + + # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + # 无论成功失败都保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="fansclub_join", + step="detected" if result else "not_detected", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "red_ratio": round(red_ratio, 4), + "red_count": red_count, + "total_samples": total_samples, + "threshold": threshold, + "result": "success" if result else "failed", + }, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s", + debug_path, + red_ratio, + threshold, + "success" if result else "failed", + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + if return_info: + reason_value: Optional[str] = ( + None if result else "red_ratio_below_threshold" + ) + return result, { + "method": "pixel_detect", + "red_ratio": red_ratio, + "red_count": red_count, + "total_samples": total_samples, + "effective_threshold": threshold, + "reason": reason_value, + } + + return result + except Exception: + if return_info: + return False, { + "method": "pixel_detect", + "red_ratio": None, + "reason": "exception", + } + return False + + +def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: + """通过像素检测直播间图标区域的白色像素比例,判断是否在直播间。 + + 使用指定的多边形区域检测白色像素: + - 顶点坐标:基于1080x2400分辨率 + - 检测白色像素比例(RGB值都≥240) + - 阈值:白色像素比例≥0.8认为在直播间 + + 返回: + (detected, confidence) 其中 confidence 为置信度(0.0~1.0) + """ + try: + width, height = pic_rgb.size + # 缩放坐标到实际尺寸(基于1080x2400) + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + # 多边形顶点坐标(基于1080x2400分辨率) + polygon_points = [ + (1002, 172), (999, 174), (1011, 186), (999, 199), + (1002, 202), (1013, 190), (1025, 201), (1028, 198), + (1017, 187), (1028, 174), (1025, 172), (1014, 184) + ] + + # 缩放到实际尺寸 + scaled_points = [(int(x * scale_x), int(y * scale_y)) for x, y in polygon_points] + + # 创建多边形mask + from PIL import ImageDraw + mask = Image.new('L', (width, height), 0) + draw = ImageDraw.Draw(mask) + draw.polygon(scaled_points, fill=255) + + # 转换为numpy数组进行高效计算 + import numpy as np + mask_array = np.array(mask) + img_array = np.array(pic_rgb) + + # 计算多边形内部的总像素数和白色像素数 + total_pixels = np.sum(mask_array > 0) + white_pixels = 0 + + if total_pixels > 0: + # 只检查多边形内部的像素 + for y in range(height): + for x in range(width): + if mask_array[y, x] > 0: # 在多边形内部 + r, g, b = img_array[y, x] + if r >= 240 and g >= 240 and b >= 240: # 白色阈值 + white_pixels += 1 + + white_ratio = white_pixels / total_pixels + else: + white_ratio = 0.0 + + # 判断是否在直播间:白色像素比例≥0.8 + detected = white_ratio >= 0.8 + confidence = white_ratio # 直接使用白色比例作为置信度 + + # 保存调试图像 + try: + from douyin.handlers import douyin_screenshot_manager + + # 计算多边形的边界框用于调试图像显示 + min_x = min(x for x, y in scaled_points) + max_x = max(x for x, y in scaled_points) + min_y = min(y for y, y in scaled_points) + max_y = max(y for y, y in scaled_points) + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="pixel_detect", + picname="live_room_icons", + step="detected" if detected else "not_detected", + coords=(min_x, min_y, max_x, max_y), # 使用边界框 + extra_info={ + "white_ratio": round(white_ratio, 4), + "white_count": white_pixels, + "total_pixels": total_pixels, + "confidence": round(confidence, 4), + "result": "success" if detected else "failed", + "polygon_points": scaled_points, # 保存缩放后的多边形点 + }, + ) + if debug_path: + try: + import logging + logging.info( + "[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s", + debug_path, + white_ratio, + white_pixels, + total_pixels, + confidence, + "success" if detected else "failed", + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + + return detected, confidence + except Exception as e: # type: ignore[general-exception] + return False, 0.0 + + +def detect_fudai_detail_page( + _pic_rgb: Image.Image, + _resolution_ratio_x: int = 1080, + _resolution_ratio_y: int = 2400, + _y_pianyi: int = 0, + _template_threshold: float = 0.7, + return_info: bool = False, + analyser: Any = None, +) -> bool | tuple[bool, dict]: + """检测是否处于福袋详情页。 + + 检测策略:任务数量检测 + 1. 通过检测任务数量来判断是否在福袋详情页 + 2. 如果任务数量 <= 0,则认为不在福袋详情页 + 3. 如果任务数量 >= 1,则认为在福袋详情页,并返回任务数量 + + 参数: + pic_rgb: RGB格式的整屏截图(保留用于兼容性,实际不使用) + resolution_ratio_x: 分辨率X比例(默认1080,保留用于兼容性) + resolution_ratio_y: 分辨率Y比例(默认2400,保留用于兼容性) + y_pianyi: Y轴偏移(默认0,保留用于兼容性) + template_threshold: 模板匹配阈值(保留用于兼容性,不再使用) + return_info: 是否返回详细信息(包含任务数量) + analyser: 分析器对象(必需,用于任务数量检测) + + 返回: + bool: 是否检测到福袋详情页(return_info=False时) + tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时) + 详细信息包含: + - method: 检测方法("task_count") + - task_count: 任务数量(0/1/2/3) + """ + # ---------- 任务数量检测 ---------- + if analyser is None: + # analyser 参数必需 + if return_info: + return False, { + "method": "task_count", + "task_count": 0, + "reason": "analyser_required", + } + return False + + try: + from .douyin_detection import check_detail_height + + # 执行任务数量检测 + task_count = int(check_detail_height(analyser) or 0) + + # 判断是否在福袋详情页 + # 如果任务数量 <= 0,则认为不在福袋详情页 + # 如果任务数量 >= 1,则认为在福袋详情页 + is_in_detail = task_count >= 1 + + if return_info: + return is_in_detail, { + "method": "task_count", + "task_count": task_count, + } + return is_in_detail + except Exception as e: # type: ignore[general-exception] + # 检测异常 + if return_info: + return False, { + "method": "task_count", + "task_count": 0, + "reason": f"detection_exception: {str(e)}", + } + return False + + +def read_pixel_stage_state_from_screenshot( + pic_path: str, + resolution_ratio_x: int = 1080, + resolution_ratio_y: int = 2400, + y_pianyi: int = 0, + lucky_draw_red_ratio_threshold: float = 0.8, + fudai_template_threshold: float = 0.7, + return_details: bool = False, + analyser: Any = None, +) -> dict[str, bool] | tuple[dict[str, bool], dict[str, dict]]: + """从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。 + + 使用多线程并行执行所有检测函数以提高性能。 + + 参数: + pic_path: 截图路径 + resolution_ratio_x: 分辨率X比例(默认1080) + resolution_ratio_y: 分辨率Y比例(默认2400) + y_pianyi: Y轴偏移(默认0) + lucky_draw_red_ratio_threshold: 抽奖结果红色比例阈值(默认0.8) + fudai_template_threshold: 福袋详情模板匹配阈值(默认0.7) + return_details: 是否返回每个检测步骤的详细信息(包括分数) + + 返回: + dict[str, bool]: 检测结果(return_details=False时) + tuple[dict[str, bool], dict[str, dict]]: (检测结果, 详细信息)(return_details=True时) + """ + state: dict[str, bool] = { + "has_coupon_bg": False, + "has_redpacket_bg": False, + "has_lucky_draw_result": False, + "has_attend_button_red": False, + "has_fansclub_join_red": False, + "has_fudai_detail": False, + "has_live_room_pixel": False, # 直播间图标像素检测 + "has_live_room_template": False, # 直播间图标模板匹配 + } + details: dict[str, dict] = {} + + pic_rgb = _safe_open_screenshot_rgb(pic_path) + if pic_rgb is None: + if return_details: + return state, details + return state + + # 并行执行所有检测函数 + # 注意:优惠券检测需要额外参数,使用lambda包装 + # 注意:福袋详情检测使用任务数量检测,需要analyser参数 + # 从analyser读取阈值(如果可用) + coupon_threshold = None + attend_button_threshold = None + fansclub_threshold = None + live_room_pixel_threshold = None + if analyser is not None: + try: + coupon_threshold = float( + getattr(analyser, "coupon_template_match_threshold", None) or 0.75 + ) + except Exception as e: # type: ignore[general-exception] + pass + try: + attend_button_threshold = float( + getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25 + ) + except Exception as e: # type: ignore[general-exception] + pass + try: + fansclub_threshold = float( + getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25 + ) + except Exception as e: # type: ignore[general-exception] + pass + try: + live_room_pixel_threshold = float( + getattr(analyser, "live_room_match_threshold", None) or 0.8 + ) + except Exception as e: # type: ignore[general-exception] + pass + + # 定义直播间图标像素检测包装函数 + def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]: + """直播间图标像素检测包装函数,返回 (bool, dict) 格式""" + try: + detected, confidence = detect_live_room_icons_by_pixel(pic) + threshold = live_room_pixel_threshold or 0.8 + is_detected = detected and confidence >= threshold + return is_detected, { + "method": "pixel_detection", + "confidence": confidence, + "effective_threshold": threshold, + } + except Exception as e: # type: ignore[general-exception] + return False, {"method": "pixel_detection", "error": str(e)} + + # 定义直播间图标模板匹配包装函数 + + detection_tasks = { + "has_coupon_bg": lambda pic: detect_coupon_popup_background( + pic, + return_info=True, + template_threshold=coupon_threshold, + analyser=analyser, + ), + "has_redpacket_bg": detect_redpacket_popup_background, + "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup( + pic, lucky_draw_red_ratio_threshold, return_info=True + ), + "has_attend_button_red": lambda pic: detect_attend_button_red_area( + pic, + return_info=True, + red_ratio_threshold=attend_button_threshold, + analyser=analyser, + ), + "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area( + pic, + return_info=True, + red_ratio_threshold=fansclub_threshold, + analyser=analyser, + ), + "has_fudai_detail": lambda pic: detect_fudai_detail_page( + pic, + resolution_ratio_x, + resolution_ratio_y, + y_pianyi, + fudai_template_threshold, + return_info=True, + analyser=analyser, + ), + "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测 + } + + # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) + with ThreadPoolExecutor(max_workers=8) as executor: + # 提交所有任务 + future_to_key = { + executor.submit(detect_func, pic_rgb): key + for key, detect_func in detection_tasks.items() + } + + # 收集结果 + for future in as_completed(future_to_key): + key = future_to_key[future] + try: + result = future.result() + + # 处理结果 + if isinstance(result, tuple): + # 检测函数返回 (bool, dict) 格式 + is_detected, info = result + state[key] = bool(is_detected) + if return_details: + details[key] = { + "detected": bool(is_detected), + "method": info.get("method", "unknown"), + "template_score": info.get("template_score"), + "confidence": info.get("confidence"), # 添加confidence支持(用于像素检测) + "task_count": info.get("task_count"), # 添加task_count支持 + "red_ratio": info.get("red_ratio"), # 添加red_ratio支持 + "effective_threshold": info.get("effective_threshold"), + "reason": info.get("reason"), + } + else: + # 其他检测返回 bool(不应该发生,因为所有检测都支持return_info) + state[key] = bool(result) + if return_details: + details[key] = { + "detected": bool(result), + "method": "unknown", + } + except Exception as e: # type: ignore[general-exception] + # 如果某个检测失败,保持默认值 False + state[key] = False + if return_details: + details[key] = { + "detected": False, + "error": str(e), + } + + if return_details: + return state, details + return state + coupon_threshold = float( + getattr(analyser, "coupon_template_match_threshold", None) or 0.75 + ) + except Exception as e: # type: ignore[general-exception] + pass + try: + attend_button_threshold = float( + getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25 + ) + except Exception as e: # type: ignore[general-exception] + pass + try: + fansclub_threshold = float( + getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25 + ) + except Exception as e: # type: ignore[general-exception] + pass + try: + live_room_pixel_threshold = float( + getattr(analyser, "live_room_match_threshold", None) or 0.8 + ) + except Exception as e: # type: ignore[general-exception] + pass + + # 定义直播间图标像素检测包装函数 + def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]: + """直播间图标像素检测包装函数,返回 (bool, dict) 格式""" + try: + detected, confidence = detect_live_room_icons_by_pixel(pic) + threshold = live_room_pixel_threshold or 0.8 + is_detected = detected and confidence >= threshold + return is_detected, { + "method": "pixel_detection", + "confidence": confidence, + "effective_threshold": threshold, + } + except Exception as e: # type: ignore[general-exception] + return False, {"method": "pixel_detection", "error": str(e)} + + # 定义直播间图标模板匹配包装函数 + + detection_tasks = { + "has_coupon_bg": lambda pic: detect_coupon_popup_background( + pic, + return_info=True, + template_threshold=coupon_threshold, + analyser=analyser, + ), + "has_redpacket_bg": detect_redpacket_popup_background, + "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup( + pic, lucky_draw_red_ratio_threshold, return_info=True + ), + "has_attend_button_red": lambda pic: detect_attend_button_red_area( + pic, + return_info=True, + red_ratio_threshold=attend_button_threshold, + analyser=analyser, + ), + "has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area( + pic, + return_info=True, + red_ratio_threshold=fansclub_threshold, + analyser=analyser, + ), + "has_fudai_detail": lambda pic: detect_fudai_detail_page( + pic, + resolution_ratio_x, + resolution_ratio_y, + y_pianyi, + fudai_template_threshold, + return_info=True, + analyser=analyser, + ), + "has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测 + } + + # 使用线程池并行执行检测(增加线程数以支持直播间图标检测) + with ThreadPoolExecutor(max_workers=8) as executor: + # 提交所有任务 + future_to_key = { + executor.submit(detect_func, pic_rgb): key + for key, detect_func in detection_tasks.items() + } + + # 收集结果 + for future in as_completed(future_to_key): + key = future_to_key[future] + try: + result = future.result() + + # 处理结果 + if isinstance(result, tuple): + # 检测函数返回 (bool, dict) 格式 + is_detected, info = result + state[key] = bool(is_detected) + if return_details: + details[key] = { + "detected": bool(is_detected), + "method": info.get("method", "unknown"), + "template_score": info.get("template_score"), + "confidence": info.get("confidence"), # 添加confidence支持(用于像素检测) + "task_count": info.get("task_count"), # 添加task_count支持 + "red_ratio": info.get("red_ratio"), # 添加red_ratio支持 + "effective_threshold": info.get("effective_threshold"), + "reason": info.get("reason"), + } + else: + # 其他检测返回 bool(不应该发生,因为所有检测都支持return_info) + state[key] = bool(result) + if return_details: + details[key] = { + "detected": bool(result), + "method": "unknown", + } + except Exception as e: # type: ignore[general-exception] + # 如果某个检测失败,保持默认值 False + state[key] = False + if return_details: + details[key] = { + "detected": False, + "error": str(e), + } + + if return_details: + return state, details + return state \ No newline at end of file diff --git a/douyin/fudai/core/MODULARIZATION_PLAN.md b/douyin/fudai/core/MODULARIZATION_PLAN.md index 8b7723c..1083eba 100644 --- a/douyin/fudai/core/MODULARIZATION_PLAN.md +++ b/douyin/fudai/core/MODULARIZATION_PLAN.md @@ -73,3 +73,25 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/fudai/core/__init__.py b/douyin/fudai/core/__init__.py index 7398ad7..e69de29 100644 --- a/douyin/fudai/core/__init__.py +++ b/douyin/fudai/core/__init__.py @@ -1,76 +0,0 @@ -"""福袋核心模块 - -本目录包含从 douyin_fudai_core.py 模块化后的功能模块。 - -向后兼容:所有函数都从原文件重新导出,确保现有代码继续工作。 -""" - -# 优先从子模块导入(如果已迁移) -try: - from .fudai_debug_utils import _save_full_screenshot_with_ocr_region -except ImportError: - # 如果新模块不可用,从原文件导入 - from ..douyin_fudai_core import _save_full_screenshot_with_ocr_region - -# 优先从子模块导入 get_fudai_contain -try: - from .fudai_detail_reader import get_fudai_contain -except ImportError: - # 如果新模块不可用,从原文件导入 - from ..douyin_fudai_core import get_fudai_contain - -# 优先从子模块导入 attend_choujiang -try: - from .fudai_attend import attend_choujiang -except ImportError: - # 如果新模块不可用,从原文件导入 - from ..douyin_fudai_core import attend_choujiang - -# 优先从子模块导入结果检查函数 -try: - from .fudai_result_checker import ( - check_lucky_draw_result, - check_have_reward_notice_confirm, - check_in_order_confirm_page, - get_reward, - ) -except ImportError: - # 如果新模块不可用,从原文件导入 - from ..douyin_fudai_core import ( - check_lucky_draw_result, - check_have_reward_notice_confirm, - check_in_order_confirm_page, - get_reward, - ) - -# 优先从子模块导入过滤函数 -try: - from .fudai_filter import ( - check_contain, - is_watch_task_fudai, - should_skip_fudai_by_config, - basic_join_decision, - ) -except ImportError: - # 如果新模块不可用,从原文件导入 - from ..douyin_fudai_core import ( - check_contain, - is_watch_task_fudai, - should_skip_fudai_by_config, - basic_join_decision, - ) - -__all__ = [ - "_save_full_screenshot_with_ocr_region", - "get_fudai_contain", - "attend_choujiang", - "check_lucky_draw_result", - "check_have_reward_notice_confirm", - "check_in_order_confirm_page", - "get_reward", - "check_contain", - "is_watch_task_fudai", - "should_skip_fudai_by_config", - "basic_join_decision", -] - diff --git a/douyin/fudai/core/fudai_attend.py b/douyin/fudai/core/fudai_attend.py index ae5e7bc..54c5d2c 100644 --- a/douyin/fudai/core/fudai_attend.py +++ b/douyin/fudai/core/fudai_attend.py @@ -17,28 +17,58 @@ def attend_choujiang(analyser) -> bool: analyser.last_attend_fail_reason = "" click_times = 0 while click_times < 2: - analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字 - # 优化:尝试多种OCR模式提高精准度(优先保证精准) - attend_button_text = str( - analyser.operation.analyse_pic_word("参与按钮", 0) or "" - ) - if not attend_button_text or not any( - k in attend_button_text - for k in ( - "参与成功", - "还需看播", - "评论", - "参与抽奖", - "开始观看", - "参与", - "加入粉丝团", - "粉丝团", - ) - ): - attend_button_text = str( - analyser.operation.analyse_pic_word("参与按钮", 1) or "" - ) - analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) + # 优化:优先使用并行OCR中已识别的按钮状态(避免重复识别) + attend_button_text = None + button_status = getattr(analyser, "_fudai_button_status", None) + button_text = getattr(analyser, "_fudai_button_text", "") + + # 如果并行OCR已经识别了按钮,且识别时间较近(5秒内),直接使用 + if button_text and button_status: + try: + button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0) + current_time = time.time() + # 如果并行OCR结果在5秒内,且状态有效,直接使用 + if current_time - button_ocr_time < 5.0: + attend_button_text = button_text + analyser._log_kv( + "参与", + "使用并行OCR识别的按钮状态", + button_text=attend_button_text[:100] if attend_button_text else "", + button_status=button_status, + ) + except Exception: + pass + + # 如果并行OCR结果不可用,则重新识别 + if not attend_button_text: + analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字 + + # 统一使用预处理工具生成可供 OCR 使用的图片名(若失败则回退到原名) + try: + from douyin.utils.ocr_preprocess import preprocess_for_ocr + + use_name = preprocess_for_ocr(analyser, "参与按钮") + except Exception: + use_name = "参与按钮" + + # 优化:尝试多种OCR模式提高精准度(优先保证精准) + attend_button_text = str(analyser.operation.analyse_pic_word(use_name, 0) or "") + if not attend_button_text or not any( + k in attend_button_text + for k in ( + "参与成功", + "还需看播", + "评论", + "参与抽奖", + "开始观看", + "参与", + "加入粉丝团", + "粉丝团", + ) + ): + # 切换到模式1识别,优先使用预处理图(若存在) + attend_button_text = str(analyser.operation.analyse_pic_word(use_name, 1) or "") + analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖 analyser._log_kv("参与", "已参与,等待开奖", result="已参与") # 记录最后一次成功参与的时间 @@ -52,6 +82,24 @@ def attend_choujiang(analyser) -> bool: try: # 从 detail 中获取 future_ts(如果可用) future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 + # 如果没有从 detail 中获取到 future_ts,尝试直接解析当前详情页的倒计时文本 + if not future_ts: + try: + from douyin.fudai import douyin_fudai_core + + content, time_text, participants, copies, prize_value_yuan = douyin_fudai_core.get_fudai_contain( + analyser, renwu=1 + ) + # 尝试用 operation.check_countdown 解析 time_text + try: + res = analyser.operation.check_countdown(time_text) + if isinstance(res, tuple) and len(res) == 2: + _, parsed_future = res + future_ts = float(parsed_future or 0.0) + except Exception: + pass + except Exception: + pass if future_ts > 0: participated_fudai_ts = getattr( analyser, "_participated_fudai_future_ts", set() @@ -183,6 +231,23 @@ def attend_choujiang(analyser) -> bool: pass # 设置等待开奖标志,避免参与后立即切换直播间 + # #region agent log - set countdown + import json + from 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)}, + "sessionId": "debug-session", + "runId": "countdown_debug_run1", + "hypothesisId": "countdown_hyp2" + }) + '\n') + # #endregion + try: # 从 detail 中获取 future_ts(如果可用) future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 @@ -194,6 +259,26 @@ def attend_choujiang(analyser) -> bool: # 提前13秒,修正倒计时误差 analyser._waiting_for_lottery_result = True analyser._lottery_result_expected_ts = future_ts - 13.0 + + # #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 + }, + "sessionId": "debug-session", + "runId": "countdown_debug_run1", + "hypothesisId": "countdown_hyp2" + }) + '\n') + # #endregion analyser._log_kv( "参与", "点击参与抽奖后,设置等待开奖标志", diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index e3bc52e..976fd18 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -107,23 +107,41 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.y_pianyi, ) - # 并行执行两个OCR识别(使用轻量数字OCR) + # 并行执行两个OCR识别(使用轻量数字OCR),优先对裁剪图做预处理以提升识别率 + try: + from douyin.utils.ocr_preprocess import preprocess_for_ocr + + mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟") + ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒") + except Exception: + mm_name = "福袋倒计时_分钟" + ss_name = "福袋倒计时_秒" + with ThreadPoolExecutor(max_workers=2) as executor: future_mm = executor.submit( - analyser.operation.analyse_pic_digits, "福袋倒计时_分钟", 1 + analyser.operation.analyse_pic_digits, mm_name, 1 ) future_ss = executor.submit( - analyser.operation.analyse_pic_digits, "福袋倒计时_秒", 1 + analyser.operation.analyse_pic_digits, ss_name, 1 ) mm_raw = future_mm.result() ss_raw = future_ss.result() # 提取数字:分钟和秒都应该是1-2位数字 def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位""" + """提取数字,最多max_digits位,智能处理前导零""" digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) > max_digits: - return digits[:max_digits] + # 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况) + # 例如"002" -> "02" 而不是 "00" + candidate = digits[-max_digits:] + # 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数 + if candidate.startswith('0') and not digits.startswith('0' * len(digits)): + # 移除前导零后的长度 + actual_digits = digits.lstrip('0') or '0' + if len(actual_digits) <= max_digits: + return actual_digits.zfill(max_digits) + return candidate if len(digits) == 1: return "0" + digits return digits @@ -264,7 +282,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度,确保完整 - countdown_box = (390, 1180, 690, 1300) + # 优化:向上扩大区域,确保完整识别倒计时数字 + countdown_box = (390, 1140, 690, 1290) # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) @@ -398,7 +417,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_task_list(): """OCR识别任务列表(用于检测观看任务)""" try: - return analyser.operation.analyse_pic_word("福袋任务列表", 0) + from douyin.utils.ocr_preprocess import preprocess_for_ocr + name_tl = preprocess_for_ocr(analyser, "福袋任务列表") + return analyser.operation.analyse_pic_word(name_tl, 0) except Exception as e: try: analyser._log_kv( @@ -415,7 +436,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_content(): """OCR识别福袋内容""" try: - return analyser.operation.analyse_pic_word("福袋内容", 0) + from douyin.utils.ocr_preprocess import preprocess_for_ocr + name_fc = preprocess_for_ocr(analyser, "福袋内容") + return analyser.operation.analyse_pic_word(name_fc, 0) except Exception as e: try: analyser._log_kv( @@ -466,7 +489,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_value(): """OCR识别福袋价值(使用普通OCR)""" try: - return analyser.operation.analyse_pic_word("福袋价值", 0) + from douyin.utils.ocr_preprocess import preprocess_for_ocr + name_val = preprocess_for_ocr(analyser, "福袋价值") + return analyser.operation.analyse_pic_word(name_val, 0) except Exception as e: try: analyser._log_kv( @@ -912,10 +937,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo try: # 提取数字:分钟和秒都应该是1-2位数字 def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位""" + """提取数字,最多max_digits位,智能处理前导零""" digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) > max_digits: - return digits[:max_digits] + # 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况) + # 例如"002" -> "02" 而不是 "00" + candidate = digits[-max_digits:] + # 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数 + if candidate.startswith('0') and not digits.startswith('0' * len(digits)): + # 移除前导零后的长度 + actual_digits = digits.lstrip('0') or '0' + if len(actual_digits) <= max_digits: + return actual_digits.zfill(max_digits) + return candidate if len(digits) == 1: return "0" + digits return digits diff --git a/douyin/fudai/core/fudai_filter.py b/douyin/fudai/core/fudai_filter.py index 15d29db..55b6564 100644 --- a/douyin/fudai/core/fudai_filter.py +++ b/douyin/fudai/core/fudai_filter.py @@ -520,47 +520,44 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass - # 检查是否是预约回退后强制参与(跳过验证) - # 注意:必须在检查 _last_fudai_detail_status 之前检查,否则强制参与标志会被忽略 - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) - # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 - # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) try: last_status = getattr(analyser, "_last_fudai_detail_status", "") - if not force_attend: # 只有在非强制参与模式下才检查状态 - if last_status == "coupon_popup": - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", - ) - except Exception: - pass - elapsed = time.time() - start_time + if last_status == "coupon_popup": + try: analyser._log_kv( "参与", - "basic_join_decision完成(优惠券弹窗)", - elapsed_seconds=round(elapsed, 2), + "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", ) - return False - elif last_status == "validation_failed": - try: - analyser._log_kv( - "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", - ) - except Exception: - pass - elapsed = time.time() - start_time + except Exception: + pass + elapsed = time.time() - start_time + analyser._log_kv( + "参与", + "basic_join_decision完成(优惠券弹窗)", + elapsed_seconds=round(elapsed, 2), + ) + return False + elif last_status == "validation_failed": + try: analyser._log_kv( "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), + "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", ) - return False + except Exception: + pass + elapsed = time.time() - start_time + analyser._log_kv( + "参与", + "basic_join_decision完成(验证失败)", + elapsed_seconds=round(elapsed, 2), + ) + return False except Exception: pass + + # 检查是否是预约回退后强制参与(跳过验证) + force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) if force_attend: try: analyser._log_kv( diff --git a/douyin/fudai/core/fudai_result_checker.py b/douyin/fudai/core/fudai_result_checker.py index 1d64438..d9f09dc 100644 --- a/douyin/fudai/core/fudai_result_checker.py +++ b/douyin/fudai/core/fudai_result_checker.py @@ -7,7 +7,7 @@ from __future__ import annotations import time from typing import Any - +from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore def check_lucky_draw_result(analyser) -> int | bool: """判定福袋抽奖的结果。""" @@ -42,26 +42,30 @@ def check_lucky_draw_result(analyser) -> int | bool: if (now - cached_ts) < analyser._ocr_cache_ttl: lucky_draw_result = cached_result else: + name_lr0 = preprocess_for_ocr(analyser, "抽奖结果") lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 0) or "" + analyser.operation.analyse_pic_word(name_lr0, 0) or "" ) if not lucky_draw_result or ( "没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result ): + name_lr1 = preprocess_for_ocr(analyser, "抽奖结果") lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 1) or "" + analyser.operation.analyse_pic_word(name_lr1, 1) or "" ) analyser._ocr_cache[cache_key] = (now, lucky_draw_result) else: + name_lr0b = preprocess_for_ocr(analyser, "抽奖结果") lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 0) or "" + analyser.operation.analyse_pic_word(name_lr0b, 0) or "" ) if not lucky_draw_result or ( "没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result ): + name_lr1b = preprocess_for_ocr(analyser, "抽奖结果") lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 1) or "" + analyser.operation.analyse_pic_word(name_lr1b, 1) or "" ) analyser._ocr_cache[cache_key] = (now, lucky_draw_result) @@ -84,17 +88,30 @@ def check_lucky_draw_result(analyser) -> int | bool: # 速度优化:使用缓存避免重复OCR cache_key2 = ("no_award_confirm", 0) dur2 = 0.0 # Initialize dur2 to avoid unbound variable - if cache_key2 in analyser._ocr_cache: - cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2] - if (now - cached_ts2) < analyser._ocr_cache_ttl: - no_award_confirm = cached_result2 + # 使用统一的"我知道了"识别方法(与倒计时/开奖结果处理一致) + try: + from douyin.utils.douyin_helpers import HelperFunctions + + # 优先使用 HelperFunctions 中封装的按钮OCR方法(ROI 和多模式识别更鲁棒) + t1 = time.time() + detected = HelperFunctions.check_lottery_result_by_ocr(analyser) + dur2 = time.time() - t1 + # 将检测结果映射为之前的 no_award_confirm 表示(保留原接口) + if detected == "我知道了": + no_award_confirm = "我知道了" + elif detected == "立即领取奖品": + no_award_confirm = "立即领取奖品" else: - t1 = time.time() + # 回退到原始更大区域OCR(兼容) + t1b = time.time() analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") - no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") - analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) - dur2 = time.time() - t1 - else: + name_na = preprocess_for_ocr(analyser, "无奖励确认") + no_award_confirm = analyser.operation.analyse_pic_word(name_na) + dur2 = time.time() - t1b + + analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) + except Exception: + # 回退到原实现:直接OCR t1 = time.time() analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") @@ -138,8 +155,9 @@ def check_lucky_draw_result(analyser) -> int | bool: if not have_read_user_agreement: t2 = time.time() analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}") + name_agree = preprocess_for_ocr(analyser, f"已阅读用户协议_{y}") have_read_user_agreement = analyser.operation.analyse_pic_word( - f"已阅读用户协议_{y}" + name_agree ) analyser._ocr_cache[cache_key3] = ( time.time(), @@ -170,7 +188,8 @@ def check_have_reward_notice_confirm(analyser) -> bool: """判断是否有领奖的二次确认提醒。""" analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id) analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认") - reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1) + name_reward = preprocess_for_ocr(analyser, "奖励通知确认") + reward_notice_confirm = analyser.operation.analyse_pic_word(name_reward, 1) if "我知道了" in (reward_notice_confirm or ""): try: analyser._log_kv( @@ -188,7 +207,8 @@ def check_in_order_confirm_page(analyser) -> bool: """判断是否在中奖下单后的购买成功的页面。""" analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id) analyser.cut_pic(370, 120, 700, 220, "", "订单确认") - order_confirm = analyser.operation.analyse_pic_word("订单确认") + name_order = preprocess_for_ocr(analyser, "订单确认") + order_confirm = analyser.operation.analyse_pic_word(name_order) if "购买成功" in (order_confirm or ""): try: analyser._log_kv( diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 62e8dff..174c3b7 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -17,6 +17,7 @@ import path_config from douyin.fudai.core.fudai_debug_utils import ( _save_full_screenshot_with_ocr_region, ) +from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: @@ -114,23 +115,39 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.y_pianyi, ) - # 并行执行两个OCR识别(使用轻量数字OCR) + # 并行执行两个OCR识别(使用轻量数字OCR),优先预处理以提高识别率 + try: + mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟") + ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒") + except Exception: + mm_name = "福袋倒计时_分钟" + ss_name = "福袋倒计时_秒" + with ThreadPoolExecutor(max_workers=2) as executor: future_mm = executor.submit( - analyser.operation.analyse_pic_digits, "福袋倒计时_分钟", 1 + analyser.operation.analyse_pic_digits, mm_name, 1 ) future_ss = executor.submit( - analyser.operation.analyse_pic_digits, "福袋倒计时_秒", 1 + analyser.operation.analyse_pic_digits, ss_name, 1 ) mm_raw = future_mm.result() ss_raw = future_ss.result() # 提取数字:分钟和秒都应该是1-2位数字 def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位""" + """提取数字,最多max_digits位,智能处理前导零""" digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) > max_digits: - return digits[:max_digits] + # 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况) + # 例如"002" -> "02" 而不是 "00" + candidate = digits[-max_digits:] + # 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数 + if candidate.startswith('0') and not digits.startswith('0' * len(digits)): + # 移除前导零后的长度 + actual_digits = digits.lstrip('0') or '0' + if len(actual_digits) <= max_digits: + return actual_digits.zfill(max_digits) + return candidate if len(digits) == 1: return "0" + digits return digits @@ -275,8 +292,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.cut_pic( 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) - # 优化:稍微扩大高度,确保完整 - countdown_box = (390, 1180, 690, 1300) + # 优化:向上扩大区域,确保完整识别倒计时数字 + countdown_box = (390, 1140, 690, 1290) # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域 x1, y1, x2, y2 = countdown_box w = max(1, int(x2 - x1)) @@ -410,7 +427,26 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass - # 并行执行五个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值 + # 准备参与按钮区域的截图(用于并行OCR识别按钮状态) + try: + # 保存参与按钮区域的调试截图(仅在配置启用时) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "参与按钮", (306, 2030, 780, 2110), analyser.y_pianyi + ) + analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮", analyser.y_pianyi) + except Exception as e: + # 按钮截图失败不影响后续流程,记录日志即可 + try: + analyser._log_kv( + "福袋", + "参与按钮截图失败,继续后续流程", + error=str(e), + ) + except Exception: + pass + + # 并行执行六个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值/参与按钮 # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 ocr_start_time = time.time() task_list_raw = None @@ -418,11 +454,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_mm_raw = None countdown_ss_raw = None value_raw = None + button_text_raw = None def ocr_task_list(): """OCR识别任务列表(用于检测观看任务)""" try: - return analyser.operation.analyse_pic_word("福袋任务列表", 0) + name_tl = preprocess_for_ocr(analyser, "福袋任务列表") + return analyser.operation.analyse_pic_word(name_tl, 0) except Exception as e: try: analyser._log_kv( @@ -439,7 +477,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_content(): """OCR识别福袋内容""" try: - return analyser.operation.analyse_pic_word("福袋内容", 0) + name_fc = preprocess_for_ocr(analyser, "福袋内容") + return analyser.operation.analyse_pic_word(name_fc, 0) except Exception as e: try: analyser._log_kv( @@ -490,7 +529,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_value(): """OCR识别福袋价值(使用普通OCR)""" try: - return analyser.operation.analyse_pic_word("福袋价值", 0) + name_val = preprocess_for_ocr(analyser, "福袋价值") + return analyser.operation.analyse_pic_word(name_val, 0) except Exception as e: try: analyser._log_kv( @@ -504,15 +544,53 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass return None + def ocr_button(): + """OCR识别参与按钮(用于检测参与状态)""" + try: + name_btn = preprocess_for_ocr(analyser, "参与按钮") + # 尝试模式0和模式1,优先使用模式0 + button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "") + # 如果模式0没有识别到关键信息,尝试模式1 + if not button_text or not any( + k in button_text + for k in ( + "参与成功", + "还需看播", + "评论", + "参与抽奖", + "开始观看", + "参与", + "加入粉丝团", + "粉丝团", + "等待开奖", + "未达成", + ) + ): + button_text = str(analyser.operation.analyse_pic_word(name_btn, 1) or "") + return button_text + except Exception as e: + try: + analyser._log_kv( + "错误", + "OCR识别参与按钮失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + return None + # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 try: - with ThreadPoolExecutor(max_workers=5) as executor: + with ThreadPoolExecutor(max_workers=6) as executor: future_task_list = executor.submit(ocr_task_list) future_content = executor.submit(ocr_content) future_countdown_mm = executor.submit(ocr_countdown_mm) future_countdown_ss = executor.submit(ocr_countdown_ss) future_value = executor.submit(ocr_value) + future_button = executor.submit(ocr_button) # 等待所有操作完成 task_list_raw = future_task_list.result() @@ -520,6 +598,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_mm_raw = future_countdown_mm.result() countdown_ss_raw = future_countdown_ss.result() value_raw = future_value.result() + button_text_raw = future_button.result() # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if task_list_raw: @@ -577,6 +656,58 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 直接返回空内容,后续流程会跳过 return "", "", 0, 0, 0.0 + # 处理按钮识别结果,判断参与状态并做决策 + button_status = None + if button_text_raw: + button_text = str(button_text_raw).strip() + try: + analyser._log_kv( + "参与", + "并行OCR识别参与按钮", + button_text=button_text[:100] if button_text else "", + ) + except Exception: + pass + + # 判断按钮状态 + if "参与成功" in button_text or "等待开奖" in button_text: + button_status = "已参与" + elif "加入粉丝团" in button_text or "粉丝团" in button_text: + button_status = "需要加入粉丝团" + elif "评论" in button_text or "发表评论" in button_text or "一键发表评论" in button_text: + button_status = "需要评论" + elif "还需看播" in button_text or "开始观看" in button_text: + button_status = "需要观看" + elif "未达成" in button_text: + button_status = "未达成要求" + elif "参与抽奖" in button_text or "参与" in button_text: + button_status = "可以参与" + else: + button_status = "未知状态" + + # 将按钮状态存储到 analyser 对象中,供后续决策使用 + try: + analyser._fudai_button_status = button_status + analyser._fudai_button_text = button_text + analyser._fudai_button_ocr_time = time.time() # 记录识别时间 + analyser._log_kv( + "参与", + "按钮状态判断", + status=button_status, + button_text=button_text[:100] if button_text else "", + ) + except Exception as e: + try: + analyser._log_kv( + "错误", + "保存按钮状态失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + ocr_elapsed = time.time() - ocr_start_time try: analyser._log_kv( @@ -584,6 +715,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo "并行OCR识别完成(任务数量已在前置检测中获取)", elapsed_seconds=round(ocr_elapsed, 3), task_count=renwu, + button_status=button_status or "未识别", ) except Exception as e: try: @@ -613,7 +745,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_task_list_fallback(): try: - return analyser.operation.analyse_pic_word("福袋任务列表", 0) + name_tl2 = preprocess_for_ocr(analyser, "福袋任务列表") + return analyser.operation.analyse_pic_word(name_tl2, 0) except Exception as e: try: analyser._log_kv( @@ -691,12 +824,47 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass return None - with ThreadPoolExecutor(max_workers=5) as executor: + def ocr_button_fallback(): + try: + name_btn = preprocess_for_ocr(analyser, "参与按钮") + button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "") + if not button_text or not any( + k in button_text + for k in ( + "参与成功", + "还需看播", + "评论", + "参与抽奖", + "开始观看", + "参与", + "加入粉丝团", + "粉丝团", + "等待开奖", + "未达成", + ) + ): + button_text = str(analyser.operation.analyse_pic_word(name_btn, 1) or "") + return button_text + except Exception as e: + try: + analyser._log_kv( + "错误", + "备用OCR识别参与按钮失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + return None + + with ThreadPoolExecutor(max_workers=6) as executor: future_task_list = executor.submit(ocr_task_list_fallback) future_content = executor.submit(ocr_content_fallback) future_countdown_mm = executor.submit(ocr_countdown_mm_fallback) future_countdown_ss = executor.submit(ocr_countdown_ss_fallback) future_value = executor.submit(ocr_value_fallback) + future_button = executor.submit(ocr_button_fallback) # 等待所有操作完成 task_list_raw = future_task_list.result() @@ -704,6 +872,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_mm_raw = future_countdown_mm.result() countdown_ss_raw = future_countdown_ss.result() value_raw = future_value.result() + button_text_raw = future_button.result() # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if task_list_raw: @@ -760,6 +929,49 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass # 直接返回空内容,后续流程会跳过 return "", "", 0, 0, 0.0 + + # 处理备用并行执行的按钮识别结果 + button_status = None + if button_text_raw: + button_text = str(button_text_raw).strip() + try: + analyser._log_kv( + "参与", + "备用并行OCR识别参与按钮", + button_text=button_text[:100] if button_text else "", + ) + except Exception: + pass + + # 判断按钮状态 + if "参与成功" in button_text or "等待开奖" in button_text: + button_status = "已参与" + elif "加入粉丝团" in button_text or "粉丝团" in button_text: + button_status = "需要加入粉丝团" + elif "评论" in button_text or "发表评论" in button_text or "一键发表评论" in button_text: + button_status = "需要评论" + elif "还需看播" in button_text or "开始观看" in button_text: + button_status = "需要观看" + elif "未达成" in button_text: + button_status = "未达成要求" + elif "参与抽奖" in button_text or "参与" in button_text: + button_status = "可以参与" + else: + button_status = "未知状态" + + # 将按钮状态存储到 analyser 对象中 + try: + analyser._fudai_button_status = button_status + analyser._fudai_button_text = button_text + analyser._fudai_button_ocr_time = time.time() # 记录识别时间 + analyser._log_kv( + "参与", + "备用按钮状态判断", + status=button_status, + button_text=button_text[:100] if button_text else "", + ) + except Exception: + pass except Exception as fallback_error: # 如果备用并行执行也失败,使用串行执行作为最后兜底 try: @@ -774,7 +986,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass # 串行执行所有OCR(包括任务列表OCR) try: - task_list_raw = analyser.operation.analyse_pic_word("福袋任务列表", 0) + name_tl3 = preprocess_for_ocr(analyser, "福袋任务列表") + task_list_raw = analyser.operation.analyse_pic_word(name_tl3, 0) # 检查任务列表中是否包含"观看X分钟"任务 if task_list_raw: is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) @@ -810,6 +1023,71 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ) countdown_ss_raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) value_raw = analyser.operation.analyse_pic_word("福袋价值", 0) + # 串行执行按钮OCR + try: + name_btn3 = preprocess_for_ocr(analyser, "参与按钮") + button_text_raw = str(analyser.operation.analyse_pic_word(name_btn3, 0) or "") + if not button_text_raw or not any( + k in button_text_raw + for k in ( + "参与成功", + "还需看播", + "评论", + "参与抽奖", + "开始观看", + "参与", + "加入粉丝团", + "粉丝团", + "等待开奖", + "未达成", + ) + ): + button_text_raw = str(analyser.operation.analyse_pic_word(name_btn3, 1) or "") + + # 处理串行执行的按钮识别结果 + button_status = None + if button_text_raw: + button_text = str(button_text_raw).strip() + # 判断按钮状态 + if "参与成功" in button_text or "等待开奖" in button_text: + button_status = "已参与" + elif "加入粉丝团" in button_text or "粉丝团" in button_text: + button_status = "需要加入粉丝团" + elif "评论" in button_text or "发表评论" in button_text or "一键发表评论" in button_text: + button_status = "需要评论" + elif "还需看播" in button_text or "开始观看" in button_text: + button_status = "需要观看" + elif "未达成" in button_text: + button_status = "未达成要求" + elif "参与抽奖" in button_text or "参与" in button_text: + button_status = "可以参与" + else: + button_status = "未知状态" + + # 将按钮状态存储到 analyser 对象中 + try: + analyser._fudai_button_status = button_status + analyser._fudai_button_text = button_text + analyser._fudai_button_ocr_time = time.time() # 记录识别时间 + analyser._log_kv( + "参与", + "串行按钮状态判断", + status=button_status, + button_text=button_text[:100] if button_text else "", + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "错误", + "串行OCR识别参与按钮失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass # 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息) is_watch_task = False @@ -936,10 +1214,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo try: # 提取数字:分钟和秒都应该是1-2位数字 def _extract_digits(text: str, max_digits: int = 2) -> str: - """提取数字,最多max_digits位""" + """提取数字,最多max_digits位,智能处理前导零""" digits = "".join(ch for ch in str(text or "") if ch.isdigit()) if len(digits) > max_digits: - return digits[:max_digits] + # 如果超过max_digits,优先考虑后max_digits位(处理前导零的情况) + # 例如"002" -> "02" 而不是 "00" + candidate = digits[-max_digits:] + # 如果候选结果以0开头但原始字符串不全是0,尝试取更少的位数 + if candidate.startswith('0') and not digits.startswith('0' * len(digits)): + # 移除前导零后的长度 + actual_digits = digits.lstrip('0') or '0' + if len(actual_digits) <= max_digits: + return actual_digits.zfill(max_digits) + return candidate if len(digits) == 1: return "0" + digits return digits @@ -1201,13 +1488,24 @@ def check_contain(analyser, contains: str = "") -> bool: def attend_choujiang(analyser) -> bool: """点击参与抽奖。""" + # 优先委派到 core/fudai_attend.py 中的实现(该实现包含预处理与增强OCR) + try: + from douyin.fudai.core.fudai_attend import attend_choujiang as external_attend # type: ignore + + # 如果外部实现存在,直接调用并返回结果 + return external_attend(analyser) + except Exception: + # 无法委派时回退到本地实现(保持向后兼容) + pass + analyser.last_attend_fail_reason = "" click_times = 0 while click_times < 2: analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字 # 优化:尝试多种OCR模式提高精准度(优先保证精准) + name_part0b = preprocess_for_ocr(analyser, "参与按钮") attend_button_text = str( - analyser.operation.analyse_pic_word("参与按钮", 0) or "" + analyser.operation.analyse_pic_word(name_part0b, 0) or "" ) if not attend_button_text or not any( k in attend_button_text @@ -1222,8 +1520,9 @@ def attend_choujiang(analyser) -> bool: "粉丝团", ) ): + name_part1b = preprocess_for_ocr(analyser, "参与按钮") attend_button_text = str( - analyser.operation.analyse_pic_word("参与按钮", 1) or "" + analyser.operation.analyse_pic_word(name_part1b, 1) or "" ) analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖 diff --git a/douyin/fudai/douyin_fudai_finder.py b/douyin/fudai/douyin_fudai_finder.py index 7717e68..594576b 100644 --- a/douyin/fudai/douyin_fudai_finder.py +++ b/douyin/fudai/douyin_fudai_finder.py @@ -18,6 +18,9 @@ from typing import Any, Optional, Tuple, Dict from PIL import Image import path_config +# OCR 预处理接口(直接导入) +from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore + class FudaiImageAcquirer: """图像获取器:负责截图和图像预处理""" @@ -456,14 +459,14 @@ class FudaiDetector: threshold = 0.6 # 降低默认阈值,因为添加了多种匹配方法 # 读取模板(彩色和灰度) - template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined] - template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined] + template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined, misc] + template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined, misc] if template_color is None or template_gray is None: return None width, height = pic.size pic_rgb = pic.convert("RGB") - screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) + screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) # type: ignore[attr-defined, misc] # 提取搜索区域(扩大Y范围用于模板匹配,提高成功率) if "y_top" in region: @@ -491,13 +494,13 @@ class FudaiDetector: return None # 转换为灰度图(用于灰度匹配) - search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY) + search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined, misc] # 图像预处理:增强对比度和去噪 try: # 直方图均衡化(增强对比度) - search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray) - template_gray_enhanced = cv2.equalizeHist(template_gray) + search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray) # type: ignore[attr-defined, misc] + template_gray_enhanced = cv2.equalizeHist(template_gray) # type: ignore[attr-defined, misc] except Exception: search_roi_gray_enhanced = search_roi_gray template_gray_enhanced = template_gray @@ -516,9 +519,9 @@ class FudaiDetector: # 多种匹配方法(按优先级排序) match_methods = [ - (cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # 归一化相关系数(最常用) - (cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # 归一化相关匹配 - (cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # 归一化平方差(值越小越好) + (cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关系数(最常用) + (cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关匹配 + (cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化平方差(值越小越好) ] for scale in scales: @@ -530,24 +533,22 @@ class FudaiDetector: continue # 缩放模板(彩色和灰度) - scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) - scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) - scaled_template_gray_enhanced = cv2.resize( - template_gray_enhanced, (scaled_tw, scaled_th) - ) + scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc] + scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc] + scaled_template_gray_enhanced = cv2.resize(template_gray_enhanced, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc] # 尝试多种匹配方法 for method, method_name in match_methods: try: # 方法1:彩色匹配 - res_color = cv2.matchTemplate( + res_color = cv2.matchTemplate( # type: ignore[attr-defined, misc] search_roi_bgr, scaled_template_color, method ) if method == cv2.TM_SQDIFF_NORMED: - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc] score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好 else: - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc] score = max_val if score > best_score: @@ -557,14 +558,14 @@ class FudaiDetector: best_method = f"{method_name}_color" # 方法2:灰度匹配(更稳定,不受光照影响) - res_gray = cv2.matchTemplate( + res_gray = cv2.matchTemplate( # type: ignore[attr-defined, misc] search_roi_gray, scaled_template_gray, method ) if method == cv2.TM_SQDIFF_NORMED: - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc] score = 1.0 - max_val else: - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc] score = max_val if score > best_score: @@ -574,16 +575,16 @@ class FudaiDetector: best_method = f"{method_name}_gray" # 方法3:增强对比度后的灰度匹配 - res_gray_enhanced = cv2.matchTemplate( + res_gray_enhanced = cv2.matchTemplate( # type: ignore[attr-defined, misc] search_roi_gray_enhanced, scaled_template_gray_enhanced, method ) if method == cv2.TM_SQDIFF_NORMED: - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc] res_gray_enhanced ) score = 1.0 - max_val else: - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc] res_gray_enhanced ) score = max_val @@ -603,11 +604,11 @@ class FudaiDetector: if th > rh or tw > rw: scale = min(rh / max(th, 1), rw / max(tw, 1)) if scale > 0: - template_color = cv2.resize( + template_color = cv2.resize( # type: ignore[attr-defined, misc] template_color, (max(1, int(tw * scale)), max(1, int(th * scale))), ) - template_gray = cv2.resize( + template_gray = cv2.resize( # type: ignore[attr-defined, misc] template_gray, (max(1, int(tw * scale)), max(1, int(th * scale))), ) @@ -615,10 +616,10 @@ class FudaiDetector: if th <= rh and tw <= rw: try: - res = cv2.matchTemplate( + res = cv2.matchTemplate( # type: ignore[attr-defined, misc] search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED ) - _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined, misc] best_score = max_val best_x = max_loc[0] best_scale = 1.0 @@ -1003,8 +1004,9 @@ class FudaiClickExecutor: ) # OCR识别 + name_chk = preprocess_for_ocr(self.analyser, "檢查紅包特徵") check_text = str( - self.analyser.operation.analyse_pic_word("檢查紅包特徵", 0) or "" + self.analyser.operation.analyse_pic_word(name_chk, 0) or "" ).strip() # 检查是否包含红包关键词 @@ -1214,9 +1216,10 @@ class FudaiDetailVerifier: self.analyser.cut_pic( 238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi ) + name_invite = preprocess_for_ocr(self.analyser, "验证邀你抢红包区域") ocr_text = str( self.analyser.operation.analyse_pic_word( - "验证邀你抢红包区域", 0 + name_invite, 0 ) or "" ) @@ -1231,9 +1234,10 @@ class FudaiDetailVerifier: kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气") ) ): + name_invite1 = preprocess_for_ocr(self.analyser, "验证邀你抢红包区域") ocr_text = str( self.analyser.operation.analyse_pic_word( - "验证邀你抢红包区域", 1 + name_invite1, 1 ) or "" ) diff --git a/douyin/fudai/finder/__init__.py b/douyin/fudai/finder/__init__.py index faa1d0f..cfef123 100644 --- a/douyin/fudai/finder/__init__.py +++ b/douyin/fudai/finder/__init__.py @@ -37,3 +37,25 @@ __all__ = [ + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 3ba1419..89c9956 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -555,6 +555,70 @@ def init_debug_captures_cleanup() -> None: pass +# 操作类型和步骤的中文映射 +_OPERATION_TYPE_CN = { + "cut_pic": "裁剪图片", + "ocr": "ocr", # 保持ocr不变 + "pixel_detect": "像素检测", + "template_match": "模板匹配", +} + +_STEP_CN = { + "before_ocr": "识别前", + "preprocessed": "预处理后", + "after_ocr": "识别后", + "before_detect": "检测前", + "detected": "检测成功", + "not_detected": "未检测到", + "matched": "匹配成功", + "failed": "匹配失败", +} + +# picname 的中文映射 +_PICNAME_CN = { + "live_room_title_mid": "直播间标题", # 现在只使用一个区域,简化为"直播间标题" + "live_room_title_large": "直播间标题_大", # 保留以兼容旧代码 + "live_room_title_small": "直播间标题_小", # 保留以兼容旧代码 + "live_room_title_mid_tmp": "直播间标题_临时", # 保留以兼容旧代码 + "live_room_title_large_tmp": "直播间标题_大_临时", # 保留以兼容旧代码 + "fudai_icon": "福袋图标", + "lucky_draw_result": "抽奖结果", + "attend_button": "参与按钮", + "live_room_icons": "直播间图标", + "fudai_content": "福袋内容", + "fudai_countdown": "福袋倒计时", + "fudai_value": "福袋价值", + "fudai_task_list": "福袋任务列表", + "fudai_coupon": "优惠券", + "shopping_redpacket": "购物红包", +} + +# extra_info 键名的中文映射 +_EXTRA_INFO_KEY_CN = { + "mode": "模式", + "size": "尺寸", + "used_img2": "使用图片2", + "avg_confidence": "平均置信度", + "min_confidence": "最小置信度", + "max_confidence": "最大置信度", + "confidence_items": "置信度项数", + "text_preview": "文本预览", + "text_len": "文本长度", + "source": "来源", + "has_full_screenshot": "有完整截图", + "has_coords": "有坐标", + "digits": "数字", + "type": "类型", + "region": "区域", + "y_offset": "Y偏移", + "region_size": "区域尺寸", + "content": "内容", + "threshold": "阈值", + "score": "分数", + "loc": "位置", +} + + def _sanitize_filename_part(text: str) -> str: """清理文件名部分,移除Windows不允许的字符 @@ -594,7 +658,7 @@ def _sanitize_filename_part(text: str) -> str: return sanitized -def save_debug_image( +def save_debug_image( # type: ignore image: Image.Image, operation_type: str = "", picname: str = "", @@ -745,18 +809,30 @@ def save_debug_image( parts = [] if operation_type: - parts.append(_sanitize_filename_part(operation_type)) + # 转换为中文 + operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type) + parts.append(_sanitize_filename_part(operation_type_cn)) if picname: - parts.append(_sanitize_filename_part(picname)) + # 转换为中文 + picname_cn = _PICNAME_CN.get(picname, picname) + parts.append(_sanitize_filename_part(picname_cn)) if step: - parts.append(_sanitize_filename_part(step)) + # 转换为中文 + step_cn = _STEP_CN.get(step, step) + parts.append(_sanitize_filename_part(step_cn)) if coords: parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") if extra_info: for key, value in extra_info.items(): + # 将键名转换为中文 + key_cn = _EXTRA_INFO_KEY_CN.get(key, key) # 清理键名和值 - clean_key = _sanitize_filename_part(str(key)) - clean_value = _sanitize_filename_part(str(value)) + clean_key = _sanitize_filename_part(str(key_cn)) + # 处理值的转换(布尔值转为中文) + if isinstance(value, bool): + clean_value = "是" if value else "否" + else: + clean_value = _sanitize_filename_part(str(value)) # 限制值的长度,避免文件名过长 # 对于 text_preview 等长文本,限制更短(20字符) if key == "text_preview" or key == "content": @@ -778,11 +854,17 @@ def save_debug_image( # 优先保留:时间戳、操作类型、图片名、步骤 base_parts = [timestamp] if operation_type: - base_parts.append(_sanitize_filename_part(operation_type)) + # 转换为中文 + operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type) + base_parts.append(_sanitize_filename_part(operation_type_cn)) if picname: - base_parts.append(_sanitize_filename_part(picname)) + # 转换为中文 + picname_cn = _PICNAME_CN.get(picname, picname) + base_parts.append(_sanitize_filename_part(picname_cn)) if step: - base_parts.append(_sanitize_filename_part(step)) + # 转换为中文 + step_cn = _STEP_CN.get(step, step) + base_parts.append(_sanitize_filename_part(step_cn)) base = "_".join(base_parts) @@ -792,8 +874,15 @@ def save_debug_image( important_keys = ["mode", "size", "used_img2", "avg_confidence"] for key in important_keys: if key in extra_info and remaining > 0: - clean_key = _sanitize_filename_part(str(key)) - clean_value = _sanitize_filename_part(str(extra_info[key])) + # 将键名转换为中文 + key_cn = _EXTRA_INFO_KEY_CN.get(key, key) + clean_key = _sanitize_filename_part(str(key_cn)) + # 处理值的转换(布尔值转为中文) + value = extra_info[key] + if isinstance(value, bool): + clean_value = "是" if value else "否" + else: + clean_value = _sanitize_filename_part(str(value)) if len(clean_value) > 15: clean_value = clean_value[:15] part = f"{clean_key}_{clean_value}" @@ -963,3 +1052,162 @@ def save_debug_image( except Exception: pass return None + + # 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在) + try: + ensure_debug_captures_dir() + except Exception: + pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理 + + # 保存图像的辅助函数,带重试机制 + def save_image_with_retry( + img_to_save: Image.Image, path: str, max_retries: int = 2 + ) -> bool: + """保存图像,如果目录不存在则创建后重试""" + last_error = None + for attempt in range(max_retries): + try: + img_to_save.save(path, "PNG") + return True + except FileNotFoundError as e: + # 目录不存在,尝试创建后重试 + last_error = e + if attempt < max_retries - 1: + try: + ensure_debug_captures_dir() + except Exception as dir_error: + # 记录目录创建失败 + try: + print(f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}") + except Exception: + pass + else: + # 最后一次尝试失败,抛出异常 + raise + except PermissionError as e: + # 权限错误,不重试 + try: + print(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") + except Exception: + pass + raise + except OSError as e: + # 系统级错误(磁盘空间不足等),不重试 + try: + print(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") + except Exception: + pass + raise + except Exception as e: + # 其他异常直接抛出 + last_error = e + raise + # 所有重试都失败 + if last_error: + raise last_error + return False + + # 如果需要标注,在图像上添加信息 + if annotate and (coords or extra_info): + try: + from PIL import ImageDraw, ImageFont + + annotated_image = image.copy() + draw = ImageDraw.Draw(annotated_image) + + # 尝试使用默认字体 + try: + font = ImageFont.truetype("arial.ttf", 12) + except Exception: + try: + font = ImageFont.load_default() + except Exception: + font = None + + # 绘制坐标框 + if coords: + x1, y1, x2, y2 = coords + # 确保坐标在图像范围内 + img_w, img_h = annotated_image.size + x1 = max(0, min(x1, img_w - 1)) + y1 = max(0, min(y1, img_h - 1)) + x2 = max(0, min(x2, img_w - 1)) + y2 = max(0, min(y2, img_h - 1)) + + if x1 < x2 and y1 < y2: + # 使用元组格式 (x1, y1, x2, y2) + rect_coords: Tuple[float, float, float, float] = ( + float(x1), + float(y1), + float(x2), + float(y2), + ) + draw.rectangle(rect_coords, outline="red", width=2) + + # 添加文本信息 + if extra_info: + text_lines = [f"{k}: {v}" for k, v in extra_info.items()] + if text_lines: + text = "\n".join(text_lines) + # 在图像左上角添加文本 + try: + draw.text((5, 5), text, fill="yellow", font=font) + except Exception: + pass + + save_image_with_retry(annotated_image, file_path) + except (PermissionError, OSError) as e: + # 权限或系统错误,尝试保存原图 + try: + try: + print(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") + except Exception: + pass + save_image_with_retry(image, file_path) + except Exception: + # 如果保存原图也失败,抛出异常让外层处理 + raise + except Exception as e: + # 其他标注错误,尝试保存原图 + try: + try: + print(f"[截图管理] 图像标注失败,尝试保存原图: {e}") + except Exception: + pass + save_image_with_retry(image, file_path) + except Exception: + # 如果保存原图也失败,抛出异常让外层处理 + raise + else: + save_image_with_retry(image, file_path) + + return file_path + except FileNotFoundError as e: + # 文件或目录不存在 + try: + print(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") + except Exception: + pass + return None + except PermissionError as e: + # 权限错误 + try: + print(f"[截图管理] 保存调试图像失败(权限错误): {e}") + except Exception: + pass + return None + except OSError as e: + # 系统级错误(磁盘空间不足、路径过长等) + try: + print(f"[截图管理] 保存调试图像失败(系统错误): {e}") + except Exception: + pass + return None + except Exception as e: + # 其他未知错误 + try: + error_type = type(e).__name__ + print(f"[截图管理] 保存调试图像失败({error_type}): {e}") + except Exception: + pass + return None \ No newline at end of file diff --git a/douyin/logging/action_tracker.py b/douyin/logging/action_tracker.py index 4e6d9e3..daf2927 100644 --- a/douyin/logging/action_tracker.py +++ b/douyin/logging/action_tracker.py @@ -28,3 +28,25 @@ def track_action(name: str = ""): __all__ = ["track_action"] + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/logging/debug_logger.py b/douyin/logging/debug_logger.py index 50058b6..ae30c88 100644 --- a/douyin/logging/debug_logger.py +++ b/douyin/logging/debug_logger.py @@ -80,7 +80,7 @@ class DebugLogger: if not self.enabled: return tb = traceback.format_exc() - line = format_debug_log("Exception", level="ERROR", exception=type(exc).__name__, message=str(exc), traceback=tb, context=context or {}) + line = format_debug_log("Exception", level="ERROR", exception=type(exc).__name__, traceback=tb, context=context or {}) _debug_logger.error(line) _err.log_exception(exc, context=context) diff --git a/douyin/logging/error_logger.py b/douyin/logging/error_logger.py index 355e0eb..159371c 100644 --- a/douyin/logging/error_logger.py +++ b/douyin/logging/error_logger.py @@ -30,6 +30,10 @@ class ErrorLogger: def log_exception(self, exc: BaseException, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None: if not logger: _init_logger() + if logger is None: + # 如果仍然无法初始化 logger,则退回到标准输出,避免抛出异常 + print(f"[ErrorLogger] {type(exc).__name__}: {exc}") + return tb = traceback.format_exc() ctx = ", ".join(f"{k}={v}" for k, v in (context or {}).items()) if context else "" msg = f"Exception: {type(exc).__name__}: {exc}" @@ -41,6 +45,9 @@ class ErrorLogger: def log_error(self, msg: str, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None: if not logger: _init_logger() + if logger is None: + print(f"[ErrorLogger] {msg}") + return full = msg if context: full += " | " + ", ".join(f"{k}={v}" for k, v in context.items()) @@ -54,4 +61,23 @@ class ErrorLogger: __all__ = ["ErrorLogger"] + + + + + + + + + + + + + + + + + + + diff --git a/douyin/other/douyin_popups.py b/douyin/other/douyin_popups.py index 5dec90d..ff530a5 100644 --- a/douyin/other/douyin_popups.py +++ b/douyin/other/douyin_popups.py @@ -6,6 +6,9 @@ from PIL import Image from douyin.detection import douyin_pixel +# OCR 预处理接口(直接导入) +from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore + def check_coupon_popup(analyser) -> bool: """优惠券弹窗检测(模板匹配 + OCR兜底确认)。 @@ -76,7 +79,8 @@ def check_coupon_popup(analyser) -> bool: # OCR模式0 ocr_mode0_start = time.time() try: - coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") + pname0 = preprocess_for_ocr(analyser, "参与按钮") + coupon_text = str(analyser.operation.analyse_pic_word(pname0, 0) or "") ocr_mode0_elapsed = time.time() - ocr_mode0_start if coupon_text and "开心收下" in coupon_text: @@ -111,7 +115,8 @@ def check_coupon_popup(analyser) -> bool: if enable_ocr_mode1 and not ocr_confirmed: ocr_mode1_start = time.time() try: - coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "") + pname1 = preprocess_for_ocr(analyser, "参与按钮") + coupon_text = str(analyser.operation.analyse_pic_word(pname1, 1) or "") ocr_mode1_elapsed = time.time() - ocr_mode1_start if coupon_text and "开心收下" in coupon_text: @@ -228,7 +233,8 @@ def check_shopping_redpacket_popup(analyser) -> bool: # OCR 模式0 ocr_mode0_start = time.time() try: - t = str(analyser.operation.analyse_pic_word("診斷購物紅包", 0) or "") + name_r = preprocess_for_ocr(analyser, "診斷購物紅包") + t = str(analyser.operation.analyse_pic_word(name_r, 0) or "") hay = t.strip() if t else "" ocr_mode0_elapsed = time.time() - ocr_mode0_start except Exception as e: @@ -255,8 +261,9 @@ def check_shopping_redpacket_popup(analyser) -> bool: # 嘗試按鈕區域快速 OCR(兜底) try: analyser.cut_pic(400, 1200, 680, 1400, "", "診斷購物紅包按鈕") + name_btn = preprocess_for_ocr(analyser, "診斷購物紅包按鈕") btn_text = str( - analyser.operation.analyse_pic_word("診斷購物紅包按鈕", 0) or "" + analyser.operation.analyse_pic_word(name_btn, 0) or "" ).strip() if "搶" in btn_text: total_elapsed = time.time() - check_start @@ -292,7 +299,8 @@ def check_shopping_redpacket_popup(analyser) -> bool: # 模式1 ocr_mode1_start = time.time() try: - t1 = str(analyser.operation.analyse_pic_word("診斷購物紅包", 1) or "") + name_r1 = preprocess_for_ocr(analyser, "診斷購物紅包") + t1 = str(analyser.operation.analyse_pic_word(name_r1, 1) or "") hay1 = t1.strip() if t1 else "" ocr_mode1_elapsed = time.time() - ocr_mode1_start if hay1: @@ -320,7 +328,8 @@ def check_shopping_redpacket_popup(analyser) -> bool: # 模式2 ocr_mode2_start = time.time() try: - t2 = str(analyser.operation.analyse_pic_word("診斷購物紅包", 2) or "") + name_r2 = preprocess_for_ocr(analyser, "診斷購物紅包") + t2 = str(analyser.operation.analyse_pic_word(name_r2, 2) or "") hay2 = t2.strip() if t2 else "" ocr_mode2_elapsed = time.time() - ocr_mode2_start if hay2: @@ -374,39 +383,25 @@ def check_shopping_redpacket_popup(analyser) -> bool: def handle_lottery_result_popup(analyser) -> None: - """处理抽奖结果弹窗:点击"我知道了"或"领取并使用"按钮。 + """处理抽奖结果弹窗:通过OCR识别并点击"我知道了"或"领取并使用"按钮。 - 根据阶段诊断,已经确认是 FUDai_RESULT 阶段,这里只需要点击按钮关闭弹窗。 - 按钮位置通常在屏幕中下部,坐标约 (540, 1400) 基于1080x2400。 + 根据阶段诊断,已经确认是 FUDai_RESULT 阶段,这里使用OCR识别按钮文本后点击。 """ try: analyser._log_kv("开奖结果", "开始处理抽奖结果弹窗") - # 点击"我知道了"或"领取并使用"按钮(坐标基于1080x2400:540, 1400) - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - btn_x = int(540 * rx // 1080) - btn_y = int(1400 * ry // 2400) + # 使用OCR识别开奖结果按钮 + from douyin.utils import douyin_helpers + result_type = douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(analyser) - analyser.operation.click(analyser.device_id, btn_x, btn_y) - analyser._log_kv("开奖结果", "已点击结果按钮", x=btn_x, y=btn_y) - analyser.operation.delay(1.0) - - # 如果还有弹窗,尝试再次点击或按返回键 - try: - analyser.operation.get_screenshot(analyser.device_id) - from douyin.stage import douyin_stage - result = douyin_stage.diagnose_stage_from_current_screen(analyser) - if result is None: - stage = "UNKNOWN" - else: - stage, _ = result - if stage == "FUDai_RESULT": - # 仍在结果页,尝试按返回键 - analyser.operation.click_back(analyser.device_id) - analyser.operation.delay(0.5) - except Exception: - pass + if result_type: + # 根据OCR识别结果处理 + douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(analyser, result_type) + else: + # OCR未识别到,尝试按返回键 + analyser._log_kv("开奖结果", "OCR未识别到按钮,使用返回键关闭") + analyser.operation.click_back(analyser.device_id) + analyser.operation.delay(0.5) analyser._log_kv("开奖结果", "处理完成") except Exception as e: diff --git a/douyin/other/douyin_robot.py b/douyin/other/douyin_robot.py index 2f7d5e8..2daffe1 100644 --- a/douyin/other/douyin_robot.py +++ b/douyin/other/douyin_robot.py @@ -5,6 +5,8 @@ from typing import Any from PIL import Image +# OCR 预处理接口(直接导入) +from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore def check_have_robot_analyse(analyser) -> int | bool: """检查是否存在人机校验。 @@ -16,17 +18,19 @@ def check_have_robot_analyse(analyser) -> int | bool: - False: 未检测到人机验证 """ analyser.cut_pic(130, 790, 680, 870, "", "直播验证") - result = analyser.operation.analyse_pic_word("直播验证", 1) + name_live = preprocess_for_ocr(analyser, "直播验证") + result = analyser.operation.analyse_pic_word(name_live, 0) if "验证" in result: - print("存在滑动图片人机校验,需要等待完成验证.") + print("存在滑动图片人机校验,需要等待完成验证。") return 1 elif "形状相同" in result: - print("存在点击图片人机校验,需要等待完成验证.") + print("存在点击图片人机校验,需要等待完成验证。") return 2 analyser.cut_pic(340, 1415, 700, 1518, "", "直播验证") - result = analyser.operation.analyse_pic_word("直播验证") + name_live2 = preprocess_for_ocr(analyser, "直播验证") + result = analyser.operation.analyse_pic_word(name_live2) if "开始检测" in result: - print("存在人脸识别人机校验,需要等待完成验证.") + print("存在人脸识别人机校验,需要等待完成验证。") return 3 return False @@ -142,4 +146,3 @@ def check_robot_pic_distance(analyser) -> int: return 0 - diff --git a/douyin/reservation/core/__init__.py b/douyin/reservation/core/__init__.py index 1133ba0..385fdb6 100644 --- a/douyin/reservation/core/__init__.py +++ b/douyin/reservation/core/__init__.py @@ -47,3 +47,25 @@ __all__ = [ + + + + + + + + + + + + + + + + + + + + + + diff --git a/douyin/reservation/douyin_reservation_handler.py b/douyin/reservation/douyin_reservation_handler.py index aae1e7e..32f57c5 100644 --- a/douyin/reservation/douyin_reservation_handler.py +++ b/douyin/reservation/douyin_reservation_handler.py @@ -166,6 +166,14 @@ class ReservationHandler: 参数: analyser: 分析器对象 """ + # 检查配置项,只有在启用时才记录映射表 + try: + mapping_enabled = bool(getattr(analyser, "record_room_title_mapping_enabled", True)) + if not mapping_enabled: + return + except Exception: + pass + try: room_pos = int(getattr(analyser, "room_pos", 0) or 0) @@ -350,20 +358,20 @@ class ReservationHandler: ) except Exception: pass - delay_s = float( - getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6 - ) # 回退时设置标志,跳过记录标题(因为之前已经记录过了) try: analyser._skip_record_title_during_seek = True except Exception: pass - for _ in range(back_times): + # 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成) + for i in range(back_times): douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(analyser) - try: - analyser.operation.delay(delay_s) - except Exception: - time.sleep(delay_s) + # 只在最后一次滑动后添加短暂延迟,确保页面稳定 + if i == back_times - 1 and back_times > 0: + try: + analyser.operation.delay(0.1) # 最后一次滑动后短暂等待 + except Exception: + time.sleep(0.1) # 清除标志 try: analyser._skip_record_title_during_seek = False @@ -385,20 +393,20 @@ class ReservationHandler: ) except Exception: pass - delay_s = float( - getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6 - ) # 回退时设置标志,跳过记录标题(因为之前已经记录过了) try: analyser._skip_record_title_during_seek = True except Exception: pass - for _ in range(forward_times): + # 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成) + for i in range(forward_times): douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(analyser) - try: - analyser.operation.delay(delay_s) - except Exception: - time.sleep(delay_s) + # 只在最后一次滑动后添加短暂延迟,确保页面稳定 + if i == forward_times - 1 and forward_times > 0: + try: + analyser.operation.delay(0.1) # 最后一次滑动后短暂等待 + except Exception: + time.sleep(0.1) # 清除标志 try: analyser._skip_record_title_during_seek = False @@ -411,7 +419,13 @@ class ReservationHandler: @staticmethod # type: ignore[misc] def handle_reservation_direct_attend(analyser: Any) -> None: - """预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。 + """预约回退后直接参与:直接查找福袋并点击,使用按钮检测进行决策,跳过OCR识别。 + + 新流程: + 1. 直接查找福袋图标并点击 + 2. 点击后调用阶段检测中的按钮检测进行决策 + 3. 完成决策后,再点击福袋图标验证参与状态 + 4. 参与成功后进入开奖倒计时 参数: analyser: 分析器对象 @@ -420,7 +434,7 @@ class ReservationHandler: try: analyser._log_kv( # type: ignore[attr-defined] "预约", - "[预约] 预约回退后直接参与:使用预约记录中的详情,跳过OCR识别", + "[预约] 预约回退后直接参与:直接查找福袋,使用按钮检测进行决策,跳过OCR识别", ) except Exception: pass @@ -441,14 +455,10 @@ class ReservationHandler: first_reservation = analyser.reservations[0] try: # 从预约记录中获取信息 - content = str(first_reservation.get("content", "") or "") + future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0) prize_value_yuan = float( first_reservation.get("prize_value_yuan", 0.0) or 0.0 ) - future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0) - time_text = str(first_reservation.get("time_text", "") or "") - participants = int(first_reservation.get("participants", 0) or 0) - copies = int(first_reservation.get("copies", 0) or 0) # 检查福袋是否已过期 now_ts = time.time() @@ -481,7 +491,6 @@ class ReservationHandler: pass # 清除相关标志 - analyser._reservation_back_direct_attend = False analyser._force_attend_after_reservation_back = False analyser.queue_full_waiting_at_earliest = False @@ -497,45 +506,196 @@ class ReservationHandler: return - # 构造倒计时元组 - countdown_start = now_ts - countdown_end = future_ts if future_ts > 0 else (now_ts + 60.0) - - # 构造 detail tuple(格式与 read_fudai_detail_once 返回的格式一致) - detail = ( - content, # 0: 内容 - time_text, # 1: 倒计时文本 - participants, # 2: 参与人数 - copies, # 3: 份数 - prize_value_yuan, # 4: 价值 - (countdown_start, countdown_end), # 5: 倒计时元组 - ) + # 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除) + analyser._current_fudai_future_ts = future_ts + # 步骤1:直接查找福袋图标并点击 try: analyser._log_kv( # type: ignore[attr-defined] "预约", - "[预约] 预约回退后直接参与:从预约记录构造详情", - content=content[:50] if content else "", - prize_value_yuan=prize_value_yuan, - future_ts=int(future_ts) if future_ts > 0 else 0, - time_text=time_text, - participants=participants, - copies=copies, + "[预约] 步骤1:直接查找福袋图标并点击", ) except Exception: pass - # 保存详情数据,标记为已读取(用于后续可能的第二次打开) - analyser._last_fudai_detail_tuple = detail - analyser._fudai_detail_first_read = True + from douyin.core import douyin_flow_control - # 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除) - analyser._current_fudai_future_ts = future_ts + room_pos_ref = [int(getattr(analyser, "room_pos", 0) or 0)] + opened = douyin_flow_control.find_and_open_fudai_detail( + analyser, room_pos_ref + ) - # 直接调用参与决策,跳过详情识别 - join_result = douyin_fudai_core.basic_join_decision(analyser, detail) + if not opened: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 未找到福袋图标,回退到正常流程", + ) + except Exception: + pass + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + return - # 如果参与成功,设置开奖等待状态并从预约队列中移除 + # 等待页面加载 + try: + analyser.operation.delay(0.5) # 等待详情页加载(减少延迟) + except Exception: + time.sleep(0.5) + + # 步骤2:调用阶段检测中的按钮检测进行决策 + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 步骤2:调用按钮检测进行决策", + ) + except Exception: + pass + + # 获取截图 + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass + + # 检测参与按钮 + from PIL import Image + import path_config + + try: + screenshot_path = path_config.get_screenshot_path() + pic_rgb = Image.open(screenshot_path) # type: ignore[attr-defined] + except Exception: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 无法读取截图,回退到正常流程", + ) + except Exception: + pass + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + return + + from douyin.detection import douyin_pixel + + button_result = douyin_pixel.detect_attend_button_red_area( + pic_rgb, return_info=True, analyser=analyser + ) + if isinstance(button_result, tuple): + has_button, button_info = button_result + else: + has_button = button_result + button_info = {} + + if not has_button: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 未检测到参与按钮,回退到正常流程", + button_info=button_info, + ) + except Exception: + pass + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + return + + # 步骤3:点击参与按钮 + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 步骤3:点击参与按钮", + button_info=button_info, + ) + except Exception: + pass + + # 点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + + attend_x = int(543 * rx / 1080) + attend_y = int(2070 * ry / 2400) + analyser.operation.click(analyser.device_id, attend_x, attend_y) + + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 已点击参与按钮", + click_x=attend_x, + click_y=attend_y, + ) + except Exception: + pass + + # 等待点击后的响应 + try: + analyser.operation.delay(0.8) # 等待参与响应(减少延迟) + except Exception: + time.sleep(0.8) + + # 步骤4:点击福袋图标验证参与状态 + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 步骤4:点击福袋图标验证参与状态", + ) + except Exception: + pass + + # 再次查找并点击福袋图标 + room_pos_ref2 = [int(getattr(analyser, "room_pos", 0) or 0)] + opened2 = douyin_flow_control.find_and_open_fudai_detail( + analyser, room_pos_ref2 + ) + + if not opened2: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 验证时未找到福袋图标,可能已参与成功", + ) + except Exception: + pass + else: + # 等待详情页加载 + try: + analyser.operation.delay(0.5) # 减少延迟 + except Exception: + time.sleep(0.5) + + # 再次检测按钮状态,验证是否参与成功 + try: + analyser.operation.get_screenshot(analyser.device_id) + screenshot_path2 = path_config.get_screenshot_path() + pic_rgb2 = Image.open(screenshot_path2) # type: ignore[attr-defined] + button_result2 = douyin_pixel.detect_attend_button_red_area( + pic_rgb2, return_info=True, analyser=analyser + ) + if isinstance(button_result2, tuple): + has_button2, button_info2 = button_result2 + else: + has_button2 = button_result2 + button_info2 = {} + + if has_button2: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 验证时仍检测到参与按钮,可能参与失败", + button_info=button_info2, + ) + except Exception: + pass + # 如果还有按钮,回退到正常流程 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + return + except Exception: + pass + + # 步骤5:参与成功,设置开奖等待状态并从预约队列中移除 + join_result = True # 假设参与成功 if join_result and future_ts > 0: try: # 设置开奖等待状态 @@ -597,8 +757,6 @@ class ReservationHandler: if len(remaining_reservations) < len(analyser.reservations): analyser.reservations = remaining_reservations - # 清除预约回退直接参与标志 - analyser._reservation_back_direct_attend = False analyser.reservation_after_action_pending = False except Exception as e: analyser._log_kv( # type: ignore[attr-defined] @@ -629,4 +787,3 @@ class ReservationHandler: pass # 如果出错,回退到正常流程 analyser._handle_in_fudai_detail() # type: ignore[attr-defined] - diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index 964a5eb..315284e 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -744,13 +744,11 @@ def handle_queue_full_wait_at_earliest( except Exception: time.sleep(1.5) - # 队列满后回退到最早直播间,直接设置参与标志,不管时间窗口是否到达 - # 立即参与,不等待开奖窗口 + # 队列满后回退到最早直播间,继续执行后续流程 try: - analyser._reservation_back_direct_attend = True analyser._log_kv( "预约", - "[预约] 队列满回退后,直接设置参与标志(立即参与,不等待开奖窗口)", + "[预约] 队列满回退后,继续执行后续流程", earliest_future_ts=int(ft), now_ts=int(now_ts), remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, @@ -1064,8 +1062,7 @@ def process_reservation_attend_window( is_queue_full_immediate_attend_check = False try: queue_full_waiting_check = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) - reservation_direct_attend_check = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False) - if queue_full_waiting_check and reservation_direct_attend_check: + if queue_full_waiting_check: is_queue_full_immediate_attend_check = True except Exception: pass @@ -1110,8 +1107,7 @@ def process_reservation_attend_window( is_queue_full_immediate_attend_pos = False try: queue_full_waiting_pos = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) - reservation_direct_attend_pos = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False) - if queue_full_waiting_pos and reservation_direct_attend_pos: + if queue_full_waiting_pos: is_queue_full_immediate_attend_pos = True except Exception: pass @@ -1193,17 +1189,15 @@ def process_reservation_attend_window( # 检查是否是队列满后立即参与的情况(使用标志判断,而不是锁定期) is_queue_full_immediate_attend = False try: - # 检查队列满等待标志和直接参与标志 + # 检查队列满等待标志 queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) - reservation_direct_attend = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False) - if queue_full_waiting and reservation_direct_attend: + if queue_full_waiting: is_queue_full_immediate_attend = True try: analyser._log_kv( "预约", "[预约] 检测到队列满后立即参与模式(通过标志判断),跳过时间窗口检查,直接参与", queue_full_waiting=queue_full_waiting, - reservation_direct_attend=reservation_direct_attend, target_future_ts=int(ft), ) except Exception: @@ -2012,4 +2006,4 @@ def record_high_value_reservation( ) except Exception: pass - return False + return False \ No newline at end of file diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 9cf8be3..59d64ed 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -3,7 +3,7 @@ from __future__ import annotations from douyin.detection import douyin_pixel -def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C901 +def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: C901 """完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。 日志輸出已從 print 改為 _log_kv,方便結構化查看。 @@ -17,7 +17,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 # 是否输出详细阶段诊断日志: # - False:只保留最终结果等精简日志 # - True:输出完整步骤级诊断日志(便于排查问题) - verbose: bool = bool(getattr(self, "stage_diag_verbose", False)) + verbose: bool = bool(getattr(analyser, "stage_diag_verbose", False)) def _log(msg: str, **fields): # type: ignore[misc] """阶段诊断详细日志入口:始终记录到行为日志,仅在 verbose=True 时输出到 stdout。""" @@ -26,7 +26,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 # _log_kv 会同时写入 actions.log 和输出到 stdout # 如果 verbose=False,我们需要控制 stdout 输出,但行为日志应该始终记录 # 由于 _log_kv 的设计,我们暂时让它始终调用,确保行为日志有完整记录 - self._log_kv("阶段诊断", msg, **fields) # type: ignore[attr-defined] + analyser._log_kv("阶段诊断", msg, **fields) # type: ignore[attr-defined] except Exception: # 兜底:避免任何日志异常影响主流程 pass @@ -34,7 +34,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 def _log_summary(msg: str, **fields): """阶段诊断精简日志入口:始终输出,用于记录最终结果等关键信息。""" try: - self._log_kv("阶段诊断", msg, **fields) + analyser._log_kv("阶段诊断", msg, **fields) except Exception: # 兜底:避免任何日志异常影响主流程 pass @@ -48,94 +48,190 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 msg = f"\n{char * 3} {title} {char * 3}\n" else: msg = f"\n{char * 10}\n" - self._log_kv("阶段诊断", msg) + analyser._log_kv("阶段诊断", msg) except Exception: pass diag_start = time.time() - max_diag_time = getattr(self, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒) - max_step_time = getattr(self, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒) - enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False)) # OCR模式1开关(二值化) + max_diag_time = getattr(analyser, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒) + max_step_time = getattr(analyser, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒) + enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) # OCR模式1开关(二值化) + + from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore # 仅在详细模式下输出开始分隔符与起始信息 _log_separator("开始阶段诊断") _log("开始阶段诊断", 最大诊断时间秒=max_diag_time, 单步最大耗时秒=max_step_time) - # ========== 步骤0:首先检测是否在直播间(最优先)========== + # ========== 步骤0:首先执行并行检测(包括直播间图标检测)========== step_start = time.time() - _log("步骤0[检测直播间]-开始", 说明="优先像素检测,然后模板匹配,最后OCR回退") + _log("步骤0[并行检测]-开始", 说明="并行检测:直播间图标(像素检测-多边形区域白色像素)、优惠券、红包、抽奖结果、参与按钮、粉丝团、福袋详情") in_live_room = False live_room_score = 0.0 detection_method = "" - # 第一步:优先使用像素检测 # 获取像素检测阈值(用于判断置信度是否达到要求) - pixel_threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8) + pixel_threshold = float(getattr(analyser, "live_room_match_threshold", 0.8) or 0.8) if pixel_threshold < 0.0: pixel_threshold = 0.0 if pixel_threshold > 1.0: pixel_threshold = 1.0 + # ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)========== + # 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行 + # 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测 + pixel_state = {} + pixel_details = {} + pixel_detection_start = time.time() try: - pixel_start = time.time() - import os - # 使用统一的截图路径配置 - try: - import path_config - pic_path = path_config.get_screenshot_path() - except Exception: - # 回退到旧路径(向后兼容) - import path_config - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - pic_rgb = douyin_pixel._safe_open_screenshot_rgb(pic_path) - if pic_rgb is not None: - detected, confidence = douyin_pixel.detect_live_room_icons_by_pixel(pic_rgb) - pixel_elapsed = (time.time() - pixel_start) * 1000 - # 使用 live_room_match_threshold 判断像素检测的置信度是否达到阈值 - if detected and confidence >= pixel_threshold: - in_live_room = True - live_room_score = float(confidence or 0.0) - detection_method = "像素检测" - _log( - "步骤0[检测直播间]-命中(像素检测)", - 置信度=round(confidence, 3), - 阈值=pixel_threshold, - 耗时毫秒=pixel_elapsed, - ) + result = analyser._read_pixel_stage_state(return_details=True) + if isinstance(result, tuple): + pixel_state, pixel_details = result + else: + pixel_state = result + pixel_details = {} + + pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 + + # 从并行检测结果中获取直播间图标检测结果 + # 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间 + live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False)) + + # 获取检测分数(白色像素比例) + pixel_confidence = 0.0 + if "has_live_room_pixel" in pixel_details: + pixel_confidence = float(pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0) + + # 如果像素检测通过(白色比例 >= 阈值),判定为在直播间 + if live_room_pixel_detected: + in_live_room = True + detection_method = "像素检测(多边形区域白色像素)" + live_room_score = pixel_confidence # 白色像素比例即为置信度 + _log( + "步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)", + 白色像素比例=round(pixel_confidence, 3), + 阈值=pixel_threshold, + ) + else: + # 像素检测未通过 + in_live_room = False + detection_method = "像素检测未命中" + _log( + "步骤0[检测直播间]-像素检测未命中", + 白色像素比例=round(pixel_confidence, 3), + 阈值=pixel_threshold, + ) + + if in_live_room: + total_elapsed = (time.time() - step_start) * 1000 + _log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed) + + # 记录每个检测步骤的详细信息 + for key, detail in pixel_details.items(): + step_name_map = { + "has_coupon_bg": "优惠券背景", + "has_redpacket_bg": "购物红包背景", + "has_lucky_draw_result": "抽奖结果弹窗", + "has_attend_button_red": "参与按钮红色区域", + "has_fansclub_join_red": "粉丝团加入红色区域", + "has_fudai_detail": "福袋详情页", + "has_live_room_pixel": "直播间图标(像素检测-多边形区域白色像素)", + } + step_name = step_name_map.get(key, key) + detected = detail.get("detected", False) + method = detail.get("method", "unknown") + + log_fields = { + "步骤": step_name, + "检测结果": "命中" if detected else "未命中", + "检测方法": method, + } + + # 添加分数信息 + if "template_score" in detail and detail["template_score"] is not None: + log_fields["分数"] = round(detail["template_score"], 4) + log_fields["模板匹配分数"] = round(detail["template_score"], 4) + # 对于像素检测,添加置信度信息 + if "confidence" in detail and detail["confidence"] is not None: + if "分数" not in log_fields: + log_fields["分数"] = round(detail["confidence"], 4) + log_fields["置信度"] = round(detail["confidence"], 4) + # 如果是三部分识别,显示平均分和区域结果 + if "avg_score" in detail and detail["avg_score"] is not None: + log_fields["平均分"] = round(detail["avg_score"], 4) + if "detected_parts" in detail and detail["detected_parts"]: + log_fields["匹配部分"] = ",".join(detail["detected_parts"]) + if "best_region" in detail and detail["best_region"]: + log_fields["最佳区域"] = detail["best_region"] + if "region_results" in detail and detail["region_results"]: + region_scores = detail["region_results"] + if isinstance(region_scores, dict): + log_fields["区域分数"] = f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}" + # 对于像素检测,red_ratio也作为分数显示 + if "red_ratio" in detail and detail["red_ratio"] is not None: + log_fields["红色比例"] = round(detail["red_ratio"], 4) + # 如果还没有分数,将red_ratio作为分数显示 + if "分数" not in log_fields: + log_fields["分数"] = round(detail["red_ratio"], 4) + # 显示阈值(无论是否为None都显示,方便调试) + if "effective_threshold" in detail: + threshold_val = detail["effective_threshold"] + if threshold_val is not None: + log_fields["阈值"] = round(threshold_val, 4) else: - _log( - "步骤0[检测直播间]-像素检测未命中", - 置信度=round(confidence, 3), - 阈值=pixel_threshold, - 耗时毫秒=pixel_elapsed, + log_fields["阈值"] = "未设置" + # 对于福袋详情页,额外显示配置的阈值(用于调试) + if key == "has_fudai_detail": + # 显示任务数量信息(无论是否为None都显示,便于调试) + if "task_count" in detail: + task_count_val = detail["task_count"] + log_fields["任务数量"] = task_count_val + # 如果任务数量存在但检测结果为False,记录警告 + if task_count_val is not None and task_count_val > 0 and not detected: + try: + _log( # type: ignore[misc] + "警告:检测到任务数量但 has_fudai_detail 为 False", + 任务数量=task_count_val, + detected=detected, + ) + except Exception: + pass + else: + log_fields["任务数量"] = "未获取" + try: + configured_threshold = float( + getattr(analyser, "fudai_detail_template_threshold", None) or + getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) + log_fields["配置阈值"] = round(configured_threshold, 4) + except Exception: + pass + if "reason" in detail: + log_fields["原因"] = detail["reason"] + if "error" in detail: + log_fields["错误"] = detail["error"] + + _log(f"并行检测-{step_name}", **log_fields) + + _log( + "像素状态(并行检测完成)", + 耗时毫秒=pixel_detection_elapsed, + 直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)), + 优惠券背景=bool(pixel_state.get("has_coupon_bg", False)), + 购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)), + 抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)), + 参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)), + 粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)), + 福袋详情页=bool(pixel_state.get("has_fudai_detail", False)), + ) except Exception as e: - pixel_elapsed = (time.time() - step_start) * 1000 - _log("步骤0[检测直播间]-像素检测异常", 耗时毫秒=pixel_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) + import traceback + pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 + _log("并行检测异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) + pixel_state = {} + pixel_details = {} - # 第二步:如果像素检测失败,使用模板匹配 - if not in_live_room: - try: - template_start = time.time() - detected, score = self._check_in_live_room_by_icon() - template_elapsed = (time.time() - template_start) * 1000 - if detected: - in_live_room = True - live_room_score = float(score or 0.0) - detection_method = "模板匹配" - _log("步骤0[检测直播间]-命中(模板匹配)", 分数=live_room_score, 耗时毫秒=template_elapsed) - else: - _log("步骤0[检测直播间]-模板匹配未命中", 分数=live_room_score, 耗时毫秒=template_elapsed) - except Exception as e: - template_elapsed = (time.time() - step_start) * 1000 - _log("步骤0[检测直播间]-模板匹配异常", 耗时毫秒=template_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) - - if in_live_room: - total_elapsed = (time.time() - step_start) * 1000 - _log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed) - - # 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表) + # ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)========== if not in_live_room: _log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)") @@ -151,13 +247,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 _log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)") if time.time() - step_start < max_step_time: cut_start = time.time() - self.cut_pic(400, 140, 900, 200, "", "推荐页标签栏") + analyser.cut_pic(400, 140, 900, 200, "", "推荐页标签栏") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_start < max_step_time: ocr_start = time.time() - t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 0) or "") + name0 = preprocess_for_ocr(analyser, "推荐页标签栏") + t_recommend = str(analyser.operation.analyse_pic_word(name0, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤3[OCR推荐页标签栏]-OCR模式0", @@ -170,7 +267,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend) ): ocr_start_1 = time.time() - t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 1) or "") + name1 = preprocess_for_ocr(analyser, "推荐页标签栏") + t_recommend = str(analyser.operation.analyse_pic_word(name1, 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 _log( "步骤3[OCR推荐页标签栏]-OCR模式1", @@ -206,13 +304,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 try: if time.time() - step_start < max_step_time: cut_start = time.time() - self.cut_pic(658, 147, 765, 194, "", "关注列表标签") + analyser.cut_pic(658, 147, 765, 194, "", "关注列表标签") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_start < max_step_time: ocr_start = time.time() - t_follow = str(self.operation.analyse_pic_word("关注列表标签", 0) or "") + namef0 = preprocess_for_ocr(analyser, "关注列表标签") + t_follow = str(analyser.operation.analyse_pic_word(namef0, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤3[OCR关注列表]-OCR模式0", @@ -223,7 +322,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("关注" not in t_follow): ocr_start_1 = time.time() - t_follow = str(self.operation.analyse_pic_word("关注列表标签", 1) or "") + namef1 = preprocess_for_ocr(analyser, "关注列表标签") + t_follow = str(analyser.operation.analyse_pic_word(namef1, 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 _log( "步骤3[OCR关注列表]-OCR模式1", @@ -246,9 +346,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 识别文本=follow_text, ) try: - self._last_follow_list_title_text = str(t_follow or "").strip() + analyser._last_follow_list_title_text = str(t_follow or "").strip() except Exception: - self._last_follow_list_title_text = "" + analyser._last_follow_list_title_text = "" _log_summary( "阶段诊断完成", 阶段="FOLLOW_LIST", @@ -265,31 +365,33 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 try: if time.time() - step_start < max_step_time: cut_start = time.time() - self.cut_pic(650, 145, 800, 195, "", "直播列表标签") + analyser.cut_pic(650, 145, 800, 195, "", "直播列表标签") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_start < max_step_time: ocr_start = time.time() - t_list = str(self.operation.analyse_pic_word("直播列表标签", 0) or "") - ocr_elapsed = (time.time() - ocr_start) * 1000 - _log( - "步骤3[OCR直播列表]-OCR模式0", - 耗时毫秒=ocr_elapsed, - 文本长度=len(t_list), - 文本预览=t_list[:50] if t_list else "", - ) + namel0 = preprocess_for_ocr(analyser, "直播列表标签") + t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "") + ocr_elapsed = (time.time() - ocr_start) * 1000 + _log( + "步骤3[OCR直播列表]-OCR模式0", + 耗时毫秒=ocr_elapsed, + 文本长度=len(t_list), + 文本预览=t_list[:50] if t_list else "", + ) - if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list): - ocr_start_1 = time.time() - t_list = str(self.operation.analyse_pic_word("直播列表标签", 1) or "") - ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 - _log( - "步骤3[OCR直播列表]-OCR模式1", - 耗时毫秒=ocr_elapsed_1, - 文本长度=len(t_list), - 文本预览=t_list[:50] if t_list else "", - ) + if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list): + ocr_start_1 = time.time() + namel1 = preprocess_for_ocr(analyser, "直播列表标签") + t_list = str(analyser.operation.analyse_pic_word(namel1, 1) or "") + ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 + _log( + "步骤3[OCR直播列表]-OCR模式1", + 耗时毫秒=ocr_elapsed_1, + 文本长度=len(t_list), + 文本预览=t_list[:50] if t_list else "", + ) except Exception as e: import traceback _log("步骤3[OCR直播列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc()) @@ -315,9 +417,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 # 记录诊断时看到的"关注页标题" try: - self._last_follow_list_title_text = str(t_follow or "").strip() + analyser._last_follow_list_title_text = str(t_follow or "").strip() except Exception: - self._last_follow_list_title_text = "" + analyser._last_follow_list_title_text = "" elapsed_total = (time.time() - step_start) * 1000 if elapsed_total > max_step_time * 1000: @@ -350,122 +452,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 _log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)") return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间" - # ========== 在直播间:继续执行像素检测 ========== - _log_separator("在直播间,继续执行像素检测") - _log("在直播间,继续执行像素检测") - - # ========== 第一步:基于同一张截图并行采集所有像素特征 ========== - # 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行 - pixel_state = {} - pixel_details = {} - pixel_detection_start = time.time() - try: - result = self._read_pixel_stage_state(return_details=True) - if isinstance(result, tuple): - pixel_state, pixel_details = result - else: - pixel_state = result - pixel_details = {} - - pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 - - # 记录每个检测步骤的详细信息 - for key, detail in pixel_details.items(): - step_name_map = { - "has_coupon_bg": "优惠券背景", - "has_redpacket_bg": "购物红包背景", - "has_lucky_draw_result": "抽奖结果弹窗", - "has_attend_button_red": "参与按钮红色区域", - "has_fansclub_join_red": "粉丝团加入红色区域", - "has_fudai_detail": "福袋详情页", - } - step_name = step_name_map.get(key, key) - detected = detail.get("detected", False) - method = detail.get("method", "unknown") - - log_fields = { - "步骤": step_name, - "检测结果": "命中" if detected else "未命中", - "检测方法": method, - } - - # 添加分数信息 - if "template_score" in detail and detail["template_score"] is not None: - log_fields["分数"] = round(detail["template_score"], 4) - log_fields["模板匹配分数"] = round(detail["template_score"], 4) - # 如果是三部分识别,显示平均分和区域结果 - if "avg_score" in detail and detail["avg_score"] is not None: - log_fields["平均分"] = round(detail["avg_score"], 4) - if "detected_parts" in detail and detail["detected_parts"]: - log_fields["匹配部分"] = ",".join(detail["detected_parts"]) - if "best_region" in detail and detail["best_region"]: - log_fields["最佳区域"] = detail["best_region"] - if "region_results" in detail and detail["region_results"]: - region_scores = detail["region_results"] - if isinstance(region_scores, dict): - log_fields["区域分数"] = f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}" - # 对于像素检测,red_ratio也作为分数显示 - if "red_ratio" in detail and detail["red_ratio"] is not None: - log_fields["红色比例"] = round(detail["red_ratio"], 4) - # 如果还没有分数,将red_ratio作为分数显示 - if "分数" not in log_fields: - log_fields["分数"] = round(detail["red_ratio"], 4) - # 显示阈值(无论是否为None都显示,方便调试) - if "effective_threshold" in detail: - threshold_val = detail["effective_threshold"] - if threshold_val is not None: - log_fields["阈值"] = round(threshold_val, 4) - else: - log_fields["阈值"] = "未设置" - # 对于福袋详情页,额外显示配置的阈值(用于调试) - if key == "has_fudai_detail": - # 显示任务数量信息(无论是否为None都显示,便于调试) - if "task_count" in detail: - task_count_val = detail["task_count"] - log_fields["任务数量"] = task_count_val - # 如果任务数量存在但检测结果为False,记录警告 - if task_count_val is not None and task_count_val > 0 and not detected: - try: - _log( # type: ignore[misc] - "警告:检测到任务数量但 has_fudai_detail 为 False", - 任务数量=task_count_val, - detected=detected, - ) - except Exception: - pass - else: - log_fields["任务数量"] = "未获取" - try: - configured_threshold = float( - getattr(self, "fudai_detail_template_threshold", None) or - getattr(self, "fudai_template_match_threshold", 0.7) or 0.7 - ) - log_fields["配置阈值"] = round(configured_threshold, 4) - except Exception: - pass - if "reason" in detail: - log_fields["原因"] = detail["reason"] - if "error" in detail: - log_fields["错误"] = detail["error"] - - _log(f"并行检测-{step_name}", **log_fields) - - _log( - "像素状态(并行检测完成)", - 耗时毫秒=pixel_detection_elapsed, - 优惠券背景=bool(pixel_state.get("has_coupon_bg", False)), - 购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)), - 抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)), - 参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)), - 粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)), - 福袋详情页=bool(pixel_state.get("has_fudai_detail", False)), - ) - except Exception as e: - import traceback - pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 - _log("像素状态读取异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) - pixel_state = {} - pixel_details = {} + # ========== 在直播间:继续执行像素检测结果处理 ========== + _log_separator("在直播间,继续执行像素检测结果处理") + _log("在直播间,继续执行像素检测结果处理") # ========== 优先使用像素检测结果判断阶段(按优先级顺序)========== # 根据像素检测结果,按优先级返回阶段 @@ -483,13 +472,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 # 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字 if time.time() - step_result_start < max_step_time: cut_start = time.time() - self.cut_pic(300, 600, 800, 800, "", "抽奖结果") + analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_result_start < max_step_time: ocr_start = time.time() - result_text = str(self.operation.analyse_pic_word("抽奖结果", 0) or "") + name_res0 = preprocess_for_ocr(analyser, "抽奖结果") + result_text = str(analyser.operation.analyse_pic_word(name_res0, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤1[检测抽奖结果弹窗]-OCR模式0", @@ -500,7 +490,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 if enable_ocr_mode1 and (time.time() - step_result_start < max_step_time) and (not result_text or ("没有抽中" not in result_text and "抽中福袋" not in result_text)): ocr_start_1 = time.time() - result_text = str(self.operation.analyse_pic_word("抽奖结果", 1) or "") + name_res1 = preprocess_for_ocr(analyser, "抽奖结果") + result_text = str(analyser.operation.analyse_pic_word(name_res1, 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 _log( "步骤1[检测抽奖结果弹窗]-OCR模式1", @@ -513,13 +504,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 if result_text and ("没有抽中" in result_text or "抽中福袋" in result_text): if time.time() - step_result_start < max_step_time: cut_confirm_start = time.time() - self.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") + analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") cut_confirm_elapsed = (time.time() - cut_confirm_start) * 1000 _log("步骤1[检测抽奖结果弹窗]-确认按钮截图完成", 耗时毫秒=cut_confirm_elapsed) if time.time() - step_result_start < max_step_time: ocr_confirm_start = time.time() - confirm_text = str(self.operation.analyse_pic_word("无奖励确认", 0) or "") + name_confirm0 = preprocess_for_ocr(analyser, "无奖励确认") + confirm_text = str(analyser.operation.analyse_pic_word(name_confirm0, 0) or "") ocr_confirm_elapsed = (time.time() - ocr_confirm_start) * 1000 _log( "步骤1[检测抽奖结果弹窗]-确认按钮OCR模式0", @@ -566,13 +558,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 try: if time.time() - step_redpacket_start < max_step_time: cut_start = time.time() - self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包") + analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_redpacket_start < max_step_time: ocr_start = time.time() - redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "") + name_rp = preprocess_for_ocr(analyser, "診斷購物紅包") + redpacket_text = str(analyser.operation.analyse_pic_word(name_rp, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤1.5[检测购物红包弹窗]-OCR模式0", @@ -630,7 +623,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 # 确保 detail_task_count 不是 None 时才保存 if detail_task_count is not None: try: - self._fudai_detail_task_count_from_stage = detail_task_count + analyser._fudai_detail_task_count_from_stage = detail_task_count try: _log( # type: ignore[misc] "保存任务数量到 analyser 对象", @@ -678,10 +671,10 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 # 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400) # 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间 # 暂时禁用:将默认值改为 False - enable_invite_redpacket_ocr = bool(getattr(self, "enable_invite_redpacket_ocr", False)) - template_match_score_threshold = float(getattr(self, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4) + enable_invite_redpacket_ocr = bool(getattr(analyser, "enable_invite_redpacket_ocr", False)) + template_match_score_threshold = float(getattr(analyser, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4) # 获取模板匹配分数(如果存在),用于判断是否跳过OCR - template_match_score = float(getattr(self, "_last_template_match_score", 0.0) or 0.0) + template_match_score = float(getattr(analyser, "_last_template_match_score", 0.0) or 0.0) should_skip_redpacket_ocr = (not detail_detected and template_match_score > 0 and template_match_score < template_match_score_threshold) if should_skip_redpacket_ocr: @@ -696,14 +689,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 step_ocr_redpacket_start = time.time() remaining_time_before = max_diag_time - (time.time() - diag_start) # 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待 - ocr_max_step_time = float(getattr(self, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0) + ocr_max_step_time = float(getattr(analyser, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0) if remaining_time_before > ocr_max_step_time: try: _log("步骤1.5[OCR检测邀你抢红包]-开始", 剩余时间秒=remaining_time_before, 说明="在指定区域检测邀你抢红包文字") if time.time() - step_ocr_redpacket_start < ocr_max_step_time: cut_start = time.time() - y_pianyi = int(getattr(self, "y_pianyi", 0) or 0) + y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) # 保存完整截图并标注OCR区域 try: from douyin.handlers import douyin_screenshot_manager @@ -718,8 +711,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 pic_rgb = pic.convert("RGB") width, height = pic_rgb.size - rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400) + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545 x1 = int(x1_base * width / rx) @@ -753,13 +746,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 except Exception: pass - self.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi) + analyser.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi) cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_ocr_redpacket_start < ocr_max_step_time: ocr_start = time.time() - ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 0) or "") + name_red0 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域") + ocr_text = str(analyser.operation.analyse_pic_word(name_red0, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤1.5[OCR检测邀你抢红包]-OCR模式0", @@ -769,10 +763,11 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 ) # 如果模式0未识别到,尝试模式1 - enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False)) + enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) if enable_ocr_mode1 and (not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气"))): if time.time() - step_ocr_redpacket_start < ocr_max_step_time: - ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 1) or "") + name_red1 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域") + ocr_text = str(analyser.operation.analyse_pic_word(name_red1, 1) or "") _log( "步骤1.5[OCR检测邀你抢红包]-OCR模式1", 文本长度=len(ocr_text), @@ -824,7 +819,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 try: if time.time() - step_ocr_verify_start < max_step_time: cut_start = time.time() - self.cut_pic(200, 1940, 880, 2140, "", "参与按钮") + analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed) @@ -834,8 +829,10 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 if enable_ocr_mode1: from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=2) as executor: - future_mode0 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 0) - future_mode1 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 1) + name_part0 = preprocess_for_ocr(analyser, "参与按钮") + future_mode0 = executor.submit(analyser.operation.analyse_pic_word, name_part0, 0) + name_part1 = preprocess_for_ocr(analyser, "参与按钮") + future_mode1 = executor.submit(analyser.operation.analyse_pic_word, name_part1, 1) text_mode0 = str(future_mode0.result() or "") text_mode1 = str(future_mode1.result() or "") # 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1 @@ -855,7 +852,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 文本预览=coupon_text[:50] if coupon_text else "", ) else: - coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "") + pname = preprocess_for_ocr(analyser, "参与按钮") + coupon_text = str(analyser.operation.analyse_pic_word(pname, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤3[OCR确认弹窗]-优惠券OCR模式0", @@ -888,13 +886,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 try: if time.time() - step_ocr_verify_start < max_step_time: cut_start = time.time() - self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包") + analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed) if time.time() - step_ocr_verify_start < max_step_time: ocr_start = time.time() - redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "") + name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包") + redpacket_text = str(analyser.operation.analyse_pic_word(name_rp2, 0) or "") ocr_elapsed = (time.time() - ocr_start) * 1000 _log( "步骤3[OCR确认弹窗]-购物红包OCR模式0", @@ -951,5 +950,4 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 原因="像素检测未命中,默认直播间", 总耗时毫秒=total_elapsed, ) - _log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)") - return "IN_LIVE_ROOM", "像素检测未命中,默认直播间" \ No newline at end of file + _log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)") \ No newline at end of file diff --git a/douyin/stage/douyin_stage_handler.py b/douyin/stage/douyin_stage_handler.py index 93e1f93..63e1bd5 100644 --- a/douyin/stage/douyin_stage_handler.py +++ b/douyin/stage/douyin_stage_handler.py @@ -141,10 +141,14 @@ class StageHandler: return False, 0.0 try: + # 同时读取灰度图和彩色图,灰度图用于模板匹配,彩色图用于颜色特征过滤 img = cv2.imread( # type: ignore[attr-defined] screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] ) - if img is None: + img_color = cv2.imread( # type: ignore[attr-defined] + screenshot_path, cv2.IMREAD_COLOR # type: ignore[attr-defined] + ) + if img is None or img_color is None: raise RuntimeError("cv2.imread 返回 None") except Exception as e: try: @@ -163,14 +167,51 @@ class StageHandler: threshold = max(0.0, min(1.0, threshold)) template_threshold = max(0.0, min(1.0, template_threshold)) - # 第一步:裁剪右上角图标区域 + # 第一步:裁剪右上角图标区域(使用固定坐标,基于1080x2400基准分辨率) + # 直播间图标区域:(972, 147) 到 (1047, 216) - 与像素检测区域一致 ih, iw = img.shape[:2] - roi_x1 = max(0, int(iw * 0.60)) - roi_y1 = 0 - roi_x2 = iw - roi_y2 = min(ih, int(ih * 0.40)) + + # 基准分辨率 + base_width = 1080 + base_height = 2400 + + # 固定坐标(基于1080x2400) + base_x1 = 972 + base_y1 = 147 + base_x2 = 1047 + base_y2 = 216 + + # 缩放坐标到实际分辨率 + scale_x = iw / base_width + scale_y = ih / base_height + + roi_x1 = max(0, int(base_x1 * scale_x)) + roi_y1 = max(0, int(base_y1 * scale_y)) + roi_x2 = min(iw, int(base_x2 * scale_x)) + roi_y2 = min(ih, int(base_y2 * scale_y)) + + # 确保区域有效 + if roi_x1 >= roi_x2 or roi_y1 >= roi_y2: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon ROI区域无效", + roi_x1=roi_x1, roi_y1=roi_y1, roi_x2=roi_x2, roi_y2=roi_y2, + img_width=iw, img_height=ih + ) + except Exception: + pass + return False, 0.0 + roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] + # 同步裁剪彩色 ROI,用于后续颜色特征检测(白色比例等) + roi_color = None + try: + if img_color is not None: + roi_color = img_color[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] + except Exception: + roi_color = None + if roi.size == 0: try: analyser._log_kv( # type: ignore[attr-defined] @@ -214,6 +255,22 @@ class StageHandler: best_name = "" detected = False + # 预计算颜色特征:白色像素比例(仅对 x 图标有效,用于过滤推荐页等误判) + # 直播间关闭 x 一般是“白色 x + 略暗背景”,因此需要一定的白色比例 + x_white_ratio = None + if roi_color is not None: + try: + roi_gray_for_white = cv2.cvtColor(roi_color, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined] + # 阈值 210:偏亮即视为白色像素 + _, white_bin = cv2.threshold( # type: ignore[attr-defined] + roi_gray_for_white, 210, 255, cv2.THRESH_BINARY # type: ignore[attr-defined] + ) + white_pixels = float((white_bin == 255).sum()) + total_pixels = float(white_bin.size or 1.0) + x_white_ratio = max(0.0, min(1.0, white_pixels / total_pixels)) + except Exception: + x_white_ratio = None + for template_path, roi_path, icon_name in template_roi_pairs: try: # 调试日志:检查文件存在性 @@ -281,35 +338,301 @@ class StageHandler: if tpl is None or roi_img is None: continue - th, tw = tpl.shape[:2] - rh, rw = roi_img.shape[:2] + # 图像预处理:根据图标类型选择不同的预处理方法 + # x图标:使用二值化+边缘检测(提高匹配准确性) + # xin图标:使用直方图均衡化(保持原有方法) + if icon_name == "x": + try: + # x图标特点:白色x在深灰色背景上,对比度明显 + # 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180) + # 先尝试多个阈值,选择最佳 + best_binary_score = 0.0 + best_binary_thresh = 160 + roi_binary_fixed = None + tpl_binary_fixed = None + + for thresh_val in [140, 160, 180, 200]: + try: + _, roi_bin = cv2.threshold(roi_img, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] + _, tpl_bin = cv2.threshold(tpl, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] + # 快速测试分数 + res_test = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) # type: ignore[attr-defined] + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res_test) # type: ignore[attr-defined] + if max_val > best_binary_score: + best_binary_score = max_val + best_binary_thresh = thresh_val + roi_binary_fixed = roi_bin + tpl_binary_fixed = tpl_bin + except: + continue + + # 方法2:自适应二值化(调整参数,blockSize使用较小值以提高精度) + roi_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] + roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] + ) + tpl_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] + tpl, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] + ) + + # 方法3:Otsu二值化(全局阈值) + _, roi_binary_otsu = cv2.threshold(roi_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] + _, tpl_binary_otsu = cv2.threshold(tpl, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] + + # 方法4:边缘检测(Canny,针对白色x和深灰背景,调整参数) + roi_edges = cv2.Canny(roi_img, 50, 150) # type: ignore[attr-defined] + tpl_edges = cv2.Canny(tpl, 50, 150) # type: ignore[attr-defined] + + # 方法5:边缘检测(更激进的参数,检测更多边缘) + roi_edges_aggressive = cv2.Canny(roi_img, 30, 80) # type: ignore[attr-defined] + tpl_edges_aggressive = cv2.Canny(tpl, 30, 80) # type: ignore[attr-defined] + + # 方法6:形态学处理(去除噪声,增强边缘) + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # type: ignore[attr-defined] + roi_edges_morph = cv2.morphologyEx(roi_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] + tpl_edges_morph = cv2.morphologyEx(tpl_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] + + # 使用固定阈值二值化图像作为主要匹配图像(针对白色x和深灰背景优化) + if roi_binary_fixed is not None and tpl_binary_fixed is not None: + roi_img_enhanced = roi_binary_fixed + tpl_enhanced = tpl_binary_fixed + else: + # 回退到自适应二值化 + roi_img_enhanced = roi_binary_adaptive + tpl_enhanced = tpl_binary_adaptive + + # 保存所有预处理图像用于多方法匹配 + roi_binary_adaptive_backup = roi_binary_adaptive + tpl_binary_adaptive_backup = tpl_binary_adaptive + roi_binary_otsu_backup = roi_binary_otsu + tpl_binary_otsu_backup = tpl_binary_otsu + roi_edges_backup = roi_edges + tpl_edges_backup = tpl_edges + roi_edges_aggressive_backup = roi_edges_aggressive + tpl_edges_aggressive_backup = tpl_edges_aggressive + roi_edges_morph_backup = roi_edges_morph + tpl_edges_morph_backup = tpl_edges_morph + + # 方法7:强对比度增强(针对实际测试中表现较好的配置) + roi_contrast = cv2.convertScaleAbs(roi_img_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] + tpl_contrast = cv2.convertScaleAbs(tpl_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] + roi_contrast_backup = roi_contrast + tpl_contrast_backup = tpl_contrast + roi_edges_morph_backup = roi_edges_morph + tpl_edges_morph_backup = tpl_edges_morph + + use_edges = True + except Exception: + roi_img_enhanced = roi_img + tpl_enhanced = tpl + use_edges = False + else: + try: + roi_img_enhanced = cv2.equalizeHist(roi_img) # type: ignore[attr-defined] + tpl_enhanced = cv2.equalizeHist(tpl) # type: ignore[attr-defined] + use_edges = False + except Exception: + roi_img_enhanced = roi_img + tpl_enhanced = tpl + use_edges = False + + th, tw = tpl_enhanced.shape[:2] + rh, rw = roi_img_enhanced.shape[:2] # 模板必须小于或等于ROI if th > rh or tw > rw: scale = min(rh / max(th, 1), rw / max(tw, 1)) if scale <= 0: continue - tpl = cv2.resize( # type: ignore[attr-defined] - tpl, (max(1, int(tw * scale)), max(1, int(th * scale))) + tpl_enhanced = cv2.resize( + tpl_enhanced, (max(1, int(tw * scale)), max(1, int(th * scale))) ) - th, tw = tpl.shape[:2] + th, tw = tpl_enhanced.shape[:2] - # 在ROI中匹配模板 - res = cv2.matchTemplate( # type: ignore[attr-defined] - roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] - ) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc( # type: ignore[attr-defined] - res - ) + if icon_name == "x" and use_edges: + try: + tpl_binary_adaptive_backup = cv2.resize(tpl_binary_adaptive_backup, (max(1, int(tw)), max(1, int(th)))) + tpl_binary_otsu_backup = cv2.resize(tpl_binary_otsu_backup, (max(1, int(tw)), max(1, int(th)))) + tpl_edges_backup = cv2.resize(tpl_edges_backup, (max(1, int(tw)), max(1, int(th)))) + tpl_edges_aggressive_backup = cv2.resize(tpl_edges_aggressive_backup, (max(1, int(tw)), max(1, int(th)))) + tpl_edges_morph_backup = cv2.resize(tpl_edges_morph_backup, (max(1, int(tw)), max(1, int(th)))) + except Exception: + pass - if max_val > best_score: + # 多方法模板匹配,取最高分(提高稳定性) + scores = [] + + if icon_name == "x" and use_edges: + try: + res1_fixed = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1_fixed) + scores.append(("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0))) + except Exception: + pass + + try: + res2_adaptive = cv2.matchTemplate(roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive) + scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0))) + except Exception: + pass + + try: + res3_otsu = cv2.matchTemplate(roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED) + _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu) + scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0))) + except Exception: + pass + + try: + res4_edges = cv2.matchTemplate(roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED) + _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges) + scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0))) + except Exception: + pass + + try: + res5_edges_agg = cv2.matchTemplate(roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED) + _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg) + scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0))) + except Exception: + pass + + try: + res6_morph = cv2.matchTemplate(roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED) + _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph) + scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0))) + except Exception: + pass + + try: + res7_contrast = cv2.matchTemplate(roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED) + _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast) + scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0))) + except Exception: + pass + + try: + res8_original = cv2.matchTemplate(roi_img, tpl, cv2.TM_CCOEFF_NORMED) + _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original) + scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) + except Exception: + pass + else: + try: + res1 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) + scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) + except Exception: + pass + + try: + res2 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) + scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) + except Exception: + pass + + try: + res3 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED) + min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) + score3 = 1.0 - float(min_val3 or 0.0) + scores.append(("TM_SQDIFF_NORMED", score3)) + except Exception: + pass + + # 选择最高分(如果多个方法都可用,使用加权平均) + if scores: + if icon_name == "x" and use_edges: + max_val = 0.0 + best_method = "" + ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] + ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None + ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] + ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None + if ccoeff_max and ccoeff_max[1] >= 0.50: + best_method, max_val = ccoeff_max + elif ccorr_max and ccorr_max[1] >= 0.75: + best_method, max_val = ccorr_max + elif ccoeff_max: + best_method, max_val = ccoeff_max + elif ccorr_max: + best_method, max_val = ccorr_max + else: + best_method, max_val = max(scores, key=lambda x: x[1]) + + if len(scores) >= 2: + sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) + top_score = sorted_scores[0][1] + second_score = sorted_scores[1][1] + if top_score - second_score > 0.15: + max_val = top_score + best_method = sorted_scores[0][0] + else: + ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] + if len(ccoeff_scores) >= 2: + max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3 + best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" + elif len(ccoeff_scores) >= 1: + max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3 + best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" + else: + binary_scores = [s for s in sorted_scores if "二值化" in s[0]] + if len(binary_scores) >= 2: + max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 + best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" + else: + max_val = top_score * 0.7 + second_score * 0.3 + best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" + elif len(scores) == 1: + best_method, max_val = scores[0] + else: + max_val = 0.0 + best_method = "" + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + max_val = score + best_method = method + break + elif score > max_val: + max_val = score + best_method = method + if best_method == "" and scores: + best_method, max_val = max(scores, key=lambda x: x[1]) + if len(scores) > 1: + weighted_sum = 0.0 + total_weight = 0.0 + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + weight = 0.5 + else: + weight = 0.25 + weighted_sum += score * weight + total_weight += weight + if total_weight > 0: + max_val = weighted_sum / total_weight + else: + res = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED) + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) + max_val = float(max_val or 0.0) + best_method = "TM_CCOEFF_NORMED" + + passed_color_filter = True + if icon_name == "x" and x_white_ratio is not None: + if x_white_ratio < 0.05 or x_white_ratio > 0.25: + passed_color_filter = False + elif 0.10 <= x_white_ratio <= 0.15: + if "TM_CCORR_NORMED" in best_method: + if max_val < 0.82: + passed_color_filter = False + else: + if max_val < 0.50: + passed_color_filter = False + + if max_val > best_score and passed_color_filter: best_score = float(max_val or 0.0) - best_name = ( - f"assets/{icon_name}.png -> " - f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png" - ) + best_name = f"assets/{icon_name}.png -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png (方法:{best_method})" - if max_val >= template_threshold: + if max_val >= template_threshold and passed_color_filter: detected = True except Exception: continue @@ -327,8 +650,11 @@ class StageHandler: "阶段诊断", "_check_in_live_room_by_icon 结果", detected=int(bool(detected)), - score=round(best_score, 3), + score=round(best_score, 4), template=best_name or "-", + threshold=round(template_threshold, 4), + 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, + 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", ) except Exception: pass @@ -343,8 +669,6 @@ class StageHandler: analyser: 分析器对象 """ # 这个方法非常长,直接调用原方法,保持兼容性 - # 注意:由于方法过于复杂(900+行),暂时保持原实现 - # 后续可以进一步拆分 analyser._handle_in_fudai_detail() # type: ignore[attr-defined] @staticmethod # type: ignore[misc] @@ -355,11 +679,8 @@ class StageHandler: analyser: 分析器对象 """ start_time = time.time() - # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) try: - already_verified = bool( - getattr(analyser, "_fudai_detail_verified", False) or False - ) + already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False) if already_verified: try: analyser._log_kv( # type: ignore[attr-defined] @@ -368,7 +689,6 @@ class StageHandler: ) except Exception: pass - # 直接调用详情处理逻辑,不查找福袋 analyser._handle_in_fudai_detail() # type: ignore[attr-defined] elapsed = time.time() - start_time analyser._log_kv( # type: ignore[attr-defined] @@ -383,12 +703,8 @@ class StageHandler: # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 try: now_ts = time.time() - focus_until = float( - getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 - ) - queue_full_waiting = bool( - getattr(analyser, "queue_full_waiting_at_earliest", False) or False - ) + focus_until = float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0) + queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) if focus_until > 0 and now_ts < focus_until and queue_full_waiting: if analyser.reservations and len(analyser.reservations) > 0: @@ -396,19 +712,10 @@ class StageHandler: try: ft = float(earliest.get("future_ts") or 0.0) if ft > 0: - join_ahead = float( - getattr( - analyser, "high_value_fudai_join_ahead_seconds", 120 - ) - or 120 - ) - poll_before = float( - getattr(analyser, "poll_before_open_seconds", 10.0) - or 10.0 - ) + join_ahead = float(getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120) + poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) time_window_start_ts = ft - join_ahead time_window_end_ts = ft + max(0.0, poll_before) - if now_ts < time_window_start_ts: try: analyser._log_kv( # type: ignore[attr-defined] @@ -417,9 +724,7 @@ class StageHandler: focus_until=int(focus_until), now_ts=int(now_ts), time_window_start=int(time_window_start_ts), - remain_seconds=int( - time_window_start_ts - now_ts - ), + remain_seconds=int(time_window_start_ts - now_ts), ) except Exception: pass @@ -438,12 +743,10 @@ class StageHandler: room_pos_ref: List[int] = [0] opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) if not opened: - # 无福袋,交给 flow_control 的"无福袋处理"逻辑 try: needswitch_cfg = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch_cfg = True - wait_times_ref = [0] swipe_times_ref = [0] reservation_focus_until_ts_ref = [0.0] @@ -477,7 +780,6 @@ class StageHandler: ) return - # 成功打开详情:调用同一套详情处理逻辑 analyser._handle_in_fudai_detail() # type: ignore[attr-defined] elapsed = time.time() - start_time analyser._log_kv( # type: ignore[attr-defined] @@ -485,4 +787,3 @@ class StageHandler: "_handle_live_room_has_or_not_fudai完成(成功打开详情)", elapsed_seconds=round(elapsed, 2), ) - diff --git a/douyin/stage/douyin_stage_handler.py.backup b/douyin/stage/douyin_stage_handler.py.backup new file mode 100644 index 0000000..9483699 --- /dev/null +++ b/douyin/stage/douyin_stage_handler.py.backup @@ -0,0 +1,1332 @@ +from __future__ import annotations + +""" +阶段处理模块 +============ + +职责:处理不同阶段的业务逻辑 +- 处理福袋详情页 +- 处理直播间福袋检测 +- 直播间图标检测 +""" + +import time +from typing import Any, Tuple, List, Optional + +from douyin.stage import douyin_stage +from douyin.fudai import douyin_fudai_detail +from douyin.fudai import douyin_fudai_core +from douyin.core import douyin_flow_control +from douyin.reservation import douyin_reservation_logic +from douyin.handlers import douyin_swipe_handler + + +class StageHandler: + """阶段处理器:统一管理阶段处理""" + + @staticmethod # type: ignore[misc] + def diagnose_stage_from_current_screen(analyser: Any) -> Tuple[str, str]: + """封装到子模块的阶段诊断入口。 + + 参数: + analyser: 分析器对象 + + 返回: + Tuple[str, str]: (阶段, 识别结果) + """ + result = douyin_stage.diagnose_stage_from_current_screen(analyser) + if result is None: + return ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间") + return result + + @staticmethod # type: ignore[misc] + def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]: + """通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。 + + 参数: + analyser: 分析器对象 + + 返回: + Tuple[bool, float]: (detected, score) 其中 score 为匹配得分(0.0~1.0) + """ + # 为了兼容没有 cv2/numpy 的环境,这里做降级处理 + try: + import cv2 # type: ignore[import-untyped, attr-defined] + import numpy as np # type: ignore + import os + + # 抑制OpenCV的文件读取警告 + os.environ["OPENCV_LOG_LEVEL"] = "ERROR" + try: + cv2.setLogLevel(0) # type: ignore[attr-defined] # 0 = SILENT + except (AttributeError, Exception): + try: + if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"): + cv2.utils.logging.setLogLevel( # type: ignore[attr-defined] + cv2.utils.logging.LOG_LEVEL_SILENT # type: ignore[attr-defined] + ) + except Exception: + pass + try: + import logging + + logging.getLogger("cv2").setLevel(logging.ERROR) + except Exception: + pass + except Exception: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", + "_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别", + ) + except Exception: + pass + return False, 0.0 + + base_dir = os.path.dirname(__file__) + + # 使用统一的模板路径配置 + try: + import path_config + assets_dir = path_config.get_assets_dir() + except Exception: + # 回退到旧路径(向后兼容) + assets_dir = os.path.join(base_dir, "assets") + + # 使用统一的截图路径配置 + try: + import path_config + screenshot_path = path_config.get_screenshot_path() + except Exception: + # 回退到旧路径(向后兼容) + pic_dir = os.path.join(base_dir, "pic") + screenshot_path = os.path.join(pic_dir, "screenshot.png") + + # 确保有最新截图 + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception as e: + # 记录截图获取失败,但不立即返回,继续检查文件是否存在 + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", + "_check_in_live_room_by_icon 获取截图失败", + error=str(e), + ) + except Exception: + pass + + # 如果预期路径不存在,尝试从其他可能的位置查找截图 + if not os.path.exists(screenshot_path): + # 尝试从项目根目录的 pic 目录查找 + try: + import path_config + alt_path = path_config.get_screenshot_path() + if os.path.exists(alt_path) and alt_path != screenshot_path: + # 如果找到备用路径,使用它 + screenshot_path = alt_path + except Exception: + pass + + # 如果仍然不存在,记录错误 + if not os.path.exists(screenshot_path): + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", + "_check_in_live_room_by_icon 截图不存在", + path=screenshot_path, + ) + except Exception: + pass + return False, 0.0 + + try: + # 同时读取灰度图和彩色图,灰度图用于模板匹配,彩色图用于颜色特征过滤 + img = cv2.imread( # type: ignore[attr-defined] + screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] + ) + img_color = cv2.imread( # type: ignore[attr-defined] + screenshot_path, cv2.IMREAD_COLOR # type: ignore[attr-defined] + ) + if img is None or img_color is None: + raise RuntimeError("cv2.imread 返回 None") + except Exception as e: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e) + ) + except Exception: + pass + return False, 0.0 + + # 获取可配置的匹配阈值 + threshold = float( + getattr(analyser, "live_room_match_threshold", 0.8) or 0.8 + ) + template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90% + threshold = max(0.0, min(1.0, threshold)) + template_threshold = max(0.0, min(1.0, template_threshold)) + + # 第一步:裁剪右上角图标区域(使用固定坐标,基于1080x2400基准分辨率) + # 直播间图标区域:(972, 147) 到 (1047, 216) - 与像素检测区域一致 + ih, iw = img.shape[:2] + + # 基准分辨率 + base_width = 1080 + base_height = 2400 + + # 固定坐标(基于1080x2400) + base_x1 = 972 + base_y1 = 147 + base_x2 = 1047 + base_y2 = 216 + + # 缩放坐标到实际分辨率 + scale_x = iw / base_width + scale_y = ih / base_height + + roi_x1 = max(0, int(base_x1 * scale_x)) + roi_y1 = max(0, int(base_y1 * scale_y)) + roi_x2 = min(iw, int(base_x2 * scale_x)) + roi_y2 = min(ih, int(base_y2 * scale_y)) + + # 确保区域有效 + if roi_x1 >= roi_x2 or roi_y1 >= roi_y2: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon ROI区域无效", + roi_x1=roi_x1, roi_y1=roi_y1, roi_x2=roi_x2, roi_y2=roi_y2, + img_width=iw, img_height=ih + ) + except Exception: + pass + return False, 0.0 + + roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] + + # 同步裁剪彩色 ROI,用于后续颜色特征检测(白色比例等) + roi_color = None + try: + if img_color is not None: + roi_color = img_color[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] + except Exception: + roi_color = None + + if roi.size == 0: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon ROI区域为空" + ) + except Exception: + pass + return False, 0.0 + + # 保存裁剪的ROI区域 + # 使用统一的 pic 目录配置 + try: + import path_config + pic_dir = path_config.get_pic_dir() + except Exception: + # 回退到旧路径(向后兼容) + pic_dir = os.path.join(base_dir, "pic") + ocr_dir = os.path.join(pic_dir, "ocr") + os.makedirs(ocr_dir, exist_ok=True) + x_roi_path = os.path.join(ocr_dir, "xx.png") + xin_roi_path = os.path.join(ocr_dir, "xxin.png") + + try: + cv2.imwrite(x_roi_path, roi) # type: ignore[attr-defined] + cv2.imwrite(xin_roi_path, roi) # type: ignore[attr-defined] + except Exception as e: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon 保存ROI失败", error=str(e) + ) + except Exception: + pass + + # 第二步:使用模板匹配 + template_roi_pairs = [ + (os.path.join(assets_dir, "x.png"), x_roi_path, "x"), + (os.path.join(assets_dir, "xin.png"), xin_roi_path, "xin"), + ] + + best_score = 0.0 + best_name = "" + detected = False + + # 预计算颜色特征:白色像素比例(仅对 x 图标有效,用于过滤推荐页等误判) + # 直播间关闭 x 一般是“白色 x + 略暗背景”,因此需要一定的白色比例 + x_white_ratio = None + if roi_color is not None: + try: + roi_gray_for_white = cv2.cvtColor(roi_color, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined] + # 阈值 210:偏亮即视为白色像素 + _, white_bin = cv2.threshold( # type: ignore[attr-defined] + roi_gray_for_white, 210, 255, cv2.THRESH_BINARY # type: ignore[attr-defined] + ) + white_pixels = float((white_bin == 255).sum()) + total_pixels = float(white_bin.size or 1.0) + x_white_ratio = max(0.0, min(1.0, white_pixels / total_pixels)) + except Exception: + x_white_ratio = None + + for template_path, roi_path, icon_name in template_roi_pairs: + try: + # 调试日志:检查文件存在性 + template_exists = os.path.exists(template_path) and os.path.isfile(template_path) + roi_exists = os.path.exists(roi_path) and os.path.isfile(roi_path) + + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", f"_check_in_live_room_by_icon 检查文件", + icon_name=icon_name, + template_exists=template_exists, + template_path=template_path, + roi_exists=roi_exists, + roi_path=roi_path, + ) + except Exception: + pass + + if not template_exists: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", f"_check_in_live_room_by_icon 模板文件不存在", + icon_name=icon_name, + template_path=template_path, + ) + except Exception: + pass + continue + + try: + if os.path.getsize(template_path) == 0: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", f"_check_in_live_room_by_icon 模板文件为空", + icon_name=icon_name, + template_path=template_path, + ) + except Exception: + pass + continue + except (OSError, IOError): + continue + + if not roi_exists: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", f"_check_in_live_room_by_icon ROI文件不存在", + icon_name=icon_name, + roi_path=roi_path, + ) + except Exception: + pass + continue + + try: + tpl = cv2.imread( # type: ignore[attr-defined] + template_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] + ) + roi_img = cv2.imread( # type: ignore[attr-defined] + roi_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined] + ) + except Exception: + continue + + if tpl is None or roi_img is None: + continue + + # 图像预处理:根据图标类型选择不同的预处理方法 + # x图标:使用二值化+边缘检测(提高匹配准确性) + # xin图标:使用直方图均衡化(保持原有方法) + if icon_name == "x": + try: + # x图标特点:白色x在深灰色背景上,对比度明显 + # 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180) + # 先尝试多个阈值,选择最佳 + best_binary_score = 0.0 + best_binary_thresh = 160 + roi_binary_fixed = None + tpl_binary_fixed = None + + for thresh_val in [140, 160, 180, 200]: + try: + _, roi_bin = cv2.threshold(roi_img, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] + _, tpl_bin = cv2.threshold(tpl, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] + # 快速测试分数 + res_test = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) # type: ignore[attr-defined] + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res_test) # type: ignore[attr-defined] + if max_val > best_binary_score: + best_binary_score = max_val + best_binary_thresh = thresh_val + roi_binary_fixed = roi_bin + tpl_binary_fixed = tpl_bin + except: + continue + + # 方法2:自适应二值化(调整参数,blockSize使用较小值以提高精度) + roi_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] + roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] + ) + tpl_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] + tpl, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] + ) + + # 方法3:Otsu二值化(全局阈值) + _, roi_binary_otsu = cv2.threshold(roi_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] + _, tpl_binary_otsu = cv2.threshold(tpl, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] + + # 方法4:边缘检测(Canny,针对白色x和深灰背景,调整参数) + # 降低低阈值以检测更多边缘,提高高阈值以减少噪声 + roi_edges = cv2.Canny(roi_img, 50, 150) # type: ignore[attr-defined] # 提高阈值,减少噪声 + tpl_edges = cv2.Canny(tpl, 50, 150) # type: ignore[attr-defined] + + # 方法5:边缘检测(更激进的参数,检测更多边缘) + roi_edges_aggressive = cv2.Canny(roi_img, 30, 80) # type: ignore[attr-defined] # 更低的阈值,检测更多边缘 + tpl_edges_aggressive = cv2.Canny(tpl, 30, 80) # type: ignore[attr-defined] + + # 方法6:形态学处理(去除噪声,增强边缘) + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # type: ignore[attr-defined] + roi_edges_morph = cv2.morphologyEx(roi_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] + tpl_edges_morph = cv2.morphologyEx(tpl_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] + + # 使用固定阈值二值化图像作为主要匹配图像(针对白色x和深灰背景优化) + if roi_binary_fixed is not None and tpl_binary_fixed is not None: + roi_img_enhanced = roi_binary_fixed + tpl_enhanced = tpl_binary_fixed + else: + # 回退到自适应二值化 + roi_img_enhanced = roi_binary_adaptive + tpl_enhanced = tpl_binary_adaptive + + # 保存所有预处理图像用于多方法匹配 + roi_binary_adaptive_backup = roi_binary_adaptive + tpl_binary_adaptive_backup = tpl_binary_adaptive + roi_binary_otsu_backup = roi_binary_otsu + tpl_binary_otsu_backup = tpl_binary_otsu + roi_edges_backup = roi_edges + tpl_edges_backup = tpl_edges + roi_edges_aggressive_backup = roi_edges_aggressive + tpl_edges_aggressive_backup = tpl_edges_aggressive + roi_edges_morph_backup = roi_edges_morph + tpl_edges_morph_backup = tpl_edges_morph + + # 方法7:强对比度增强(针对实际测试中表现较好的配置) + # alpha=2.0, beta=30:整体拉高对比度和亮度,突出白色 x + roi_contrast = cv2.convertScaleAbs(roi_img_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] + tpl_contrast = cv2.convertScaleAbs(tpl_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] + roi_contrast_backup = roi_contrast + tpl_contrast_backup = tpl_contrast + roi_edges_morph_backup = roi_edges_morph + tpl_edges_morph_backup = tpl_edges_morph + + use_edges = True # 标记使用边缘检测 + except Exception: + # 如果预处理失败,使用原图 + roi_img_enhanced = roi_img + tpl_enhanced = tpl + use_edges = False + else: + # xin图标:使用直方图均衡化(保持原有方法) + try: + # 直方图均衡化(增强对比度,提高匹配稳定性) + roi_img_enhanced = cv2.equalizeHist(roi_img) # type: ignore[attr-defined] + tpl_enhanced = cv2.equalizeHist(tpl) # type: ignore[attr-defined] + use_edges = False + except Exception: + # 如果预处理失败,使用原图 + roi_img_enhanced = roi_img + tpl_enhanced = tpl + use_edges = False + + th, tw = tpl_enhanced.shape[:2] + rh, rw = roi_img_enhanced.shape[:2] + + # 模板必须小于或等于ROI + if th > rh or tw > rw: + scale = min(rh / max(th, 1), rw / max(tw, 1)) + if scale <= 0: + continue + tpl_enhanced = cv2.resize( # type: ignore[attr-defined] + tpl_enhanced, (max(1, int(tw * scale)), max(1, int(th * scale))) + ) + th, tw = tpl_enhanced.shape[:2] + + # 如果使用边缘检测,也需要缩放所有预处理模板 + if icon_name == "x" and use_edges: + try: + tpl_binary_adaptive_backup = cv2.resize( # type: ignore[attr-defined] + tpl_binary_adaptive_backup, (max(1, int(tw)), max(1, int(th))) + ) + tpl_binary_otsu_backup = cv2.resize( # type: ignore[attr-defined] + tpl_binary_otsu_backup, (max(1, int(tw)), max(1, int(th))) + ) + tpl_edges_backup = cv2.resize( # type: ignore[attr-defined] + tpl_edges_backup, (max(1, int(tw)), max(1, int(th))) + ) + tpl_edges_aggressive_backup = cv2.resize( # type: ignore[attr-defined] + tpl_edges_aggressive_backup, (max(1, int(tw)), max(1, int(th))) + ) + tpl_edges_morph_backup = cv2.resize( # type: ignore[attr-defined] + tpl_edges_morph_backup, (max(1, int(tw)), max(1, int(th))) + ) + except Exception: + pass + + # 多方法模板匹配,取最高分(提高稳定性) + scores = [] + + # 对于x图标,使用多种预处理方法进行匹配 + if icon_name == "x" and use_edges: + # x图标:方法1 - 固定阈值二值化匹配(针对白色x和深灰背景优化) + try: + res1_fixed = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1_fixed) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0))) + except Exception: + pass + + # x图标:方法2 - 自适应二值化匹配 + try: + res2_adaptive = cv2.matchTemplate( # type: ignore[attr-defined] + roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0))) + except Exception: + pass + + # x图标:方法3 - Otsu二值化匹配 + try: + res3_otsu = cv2.matchTemplate( # type: ignore[attr-defined] + roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0))) + except Exception: + pass + + # x图标:方法4 - 边缘检测匹配(标准参数) + try: + res4_edges = cv2.matchTemplate( # type: ignore[attr-defined] + roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0))) + except Exception: + pass + + # x图标:方法5 - 边缘检测匹配(激进参数) + try: + res5_edges_agg = cv2.matchTemplate( # type: ignore[attr-defined] + roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0))) + except Exception: + pass + + # x图标:方法6 - 形态学处理后的边缘检测匹配 + try: + res6_morph = cv2.matchTemplate( # type: ignore[attr-defined] + roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0))) + except Exception: + pass + + # x图标:方法7 - 强对比度 + TM_CCORR_NORMED(实验中表现较好) + try: + res7_contrast = cv2.matchTemplate( # type: ignore[attr-defined] + roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] + ) + _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast) # type: ignore[attr-defined] + scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0))) + except Exception: + pass + + # x图标:方法8 - 原始图像匹配(作为对比和备用) + try: + res8_original = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) + except Exception: + pass + else: + # xin图标或其他:使用原有方法 + # 方法1: TM_CCOEFF_NORMED(归一化相关系数,对光照变化不敏感) + try: + res1 = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) + except Exception: + pass + + # 方法2: TM_CCORR_NORMED(归一化相关,对亮度变化不敏感) + try: + res2 = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) # type: ignore[attr-defined] + scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) + except Exception: + pass + + # 方法3: TM_SQDIFF_NORMED(归一化平方差,值越小越好,需要转换) + try: + res3 = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED # type: ignore[attr-defined] + ) + min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) # type: ignore[attr-defined] + # 转换为相似度分数(1 - 归一化平方差) + score3 = 1.0 - float(min_val3 or 0.0) + scores.append(("TM_SQDIFF_NORMED", score3)) + except Exception: + pass + + # 选择最高分(如果多个方法都可用,使用加权平均) + if scores: + if icon_name == "x" and use_edges: + # x图标:优先使用最高分的方法,然后计算加权平均 + max_val = 0.0 + best_method = "" + + # 混合策略:优先使用 TM_CCOEFF_NORMED 系列,但如果分数太低,考虑使用 TM_CCORR_NORMED 系列 + # 1. 先找 TM_CCOEFF_NORMED 系列的最高分 + ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] + ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None + + # 2. 找 TM_CCORR_NORMED 系列的最高分 + ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] + ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None + + # 3. 决策:如果 CCOEFF 分数 >= 0.50,优先使用它(更稳定) + # 否则,如果 CCORR 分数 >= 0.75,使用它(需要根据白色比例调整颜色过滤阈值) + # 否则,使用 CCOEFF(即使分数低,也比误判好) + if ccoeff_max and ccoeff_max[1] >= 0.50: + best_method, max_val = ccoeff_max + elif ccorr_max and ccorr_max[1] >= 0.75: + # CCORR 分数较高,可以使用 + best_method, max_val = ccorr_max + elif ccoeff_max: + best_method, max_val = ccoeff_max + elif ccorr_max: + best_method, max_val = ccorr_max + else: + # 回退到最高分 + best_method, max_val = max(scores, key=lambda x: x[1]) + + # 如果多个方法都可用,计算加权平均(提高稳定性) + # 优先使用二值化方法的加权平均 + if len(scores) >= 2: + sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) + top_score = sorted_scores[0][1] + second_score = sorted_scores[1][1] + + # 如果最高分明显高于次高分(差距>0.15),使用最高分 + # 否则使用加权平均(最高分权重0.7,次高分权重0.3) + if top_score - second_score > 0.15: + max_val = top_score + best_method = sorted_scores[0][0] + else: + # 优先选择 TM_CCOEFF_NORMED 系列方法进行加权(避免 CCORR 系列误判) + ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] + if len(ccoeff_scores) >= 2: + max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3 + best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" + elif len(ccoeff_scores) >= 1: + # 如果只有一个 CCOEFF 方法,用它和次高分加权 + max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3 + best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" + else: + # 回退到二值化方法加权 + binary_scores = [s for s in sorted_scores if "二值化" in s[0]] + if len(binary_scores) >= 2: + max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 + best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" + else: + max_val = top_score * 0.7 + second_score * 0.3 + best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" + elif len(scores) == 1: + # 只有一个方法可用,直接使用 + best_method, max_val = scores[0] + else: + # xin图标或其他:使用原有逻辑 + # 优先使用 TM_CCOEFF_NORMED(最稳定) + max_val = 0.0 + best_method = "" + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + max_val = score + best_method = method + break + elif score > max_val: + max_val = score + best_method = method + + # 如果 TM_CCOEFF_NORMED 可用,使用它;否则使用最高分 + if best_method == "" and scores: + best_method, max_val = max(scores, key=lambda x: x[1]) + + # 如果多个方法都可用,计算加权平均(提高稳定性) + if len(scores) > 1: + # TM_CCOEFF_NORMED 权重最高(0.5),其他方法各0.25 + weighted_sum = 0.0 + total_weight = 0.0 + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + weight = 0.5 + else: + weight = 0.25 + weighted_sum += score * weight + total_weight += weight + if total_weight > 0: + max_val = weighted_sum / total_weight + else: + # 回退到原始方法 + res = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined] + max_val = float(max_val or 0.0) + best_method = "TM_CCOEFF_NORMED" + + # 对 x 图标额外应用颜色特征过滤:白色比例过低/过高都认为不是关闭按钮 + passed_color_filter = True + if icon_name == "x" and x_white_ratio is not None: + # 根据实际测试:直播间 x 图标的白色比例通常在 0.05~0.20 之间 + # 推荐页这类画面通常白色比例在 0.10~0.15 之间,但结合模板匹配分数可以区分 + # 如果白色比例过低(<0.05)或过高(>0.25),直接过滤 + # 如果白色比例在 0.10~0.15 之间,需要根据使用的匹配方法调整阈值 + if x_white_ratio < 0.05 or x_white_ratio > 0.25: + passed_color_filter = False + elif 0.10 <= x_white_ratio <= 0.15: + # 这个范围内的白色比例可能是推荐页,需要更高的模板匹配分数 + # 根据测试:推荐页分数约 0.8143,直播间分数约 0.76~0.86 + # 如果使用 TM_CCORR_NORMED 系列,需要 >= 0.82(推荐页 < 0.82,直播间 >= 0.82) + # 如果使用 TM_CCOEFF_NORMED 系列,需要 >= 0.50 + if "TM_CCORR_NORMED" in best_method: + if max_val < 0.82: + passed_color_filter = False + else: + if max_val < 0.50: + passed_color_filter = False + + if max_val > best_score and passed_color_filter: + best_score = float(max_val or 0.0) + best_name = ( + f"assets/{icon_name}.png -> " + f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png" + f" (方法:{best_method})" + ) + + if max_val >= template_threshold and passed_color_filter: + detected = True + except Exception: + continue + + if not detected and best_score == 0.0: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件" + ) + except Exception: + pass + + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", + "_check_in_live_room_by_icon 结果", + detected=int(bool(detected)), + score=round(best_score, 4), # 提高精度到4位小数 + template=best_name or "-", + threshold=round(template_threshold, 4), + 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, + 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", + ) + except Exception: + pass + + return bool(detected), float(best_score or 0.0) + + @staticmethod # type: ignore[misc] + def handle_in_fudai_detail(analyser: Any) -> None: + """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。 + + 参数: + analyser: 分析器对象 + """ + # 这个方法非常长,直接调用原方法,保持兼容性 + # 注意:由于方法过于复杂(900+行),暂时保持原实现 + # 后续可以进一步拆分 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + + @staticmethod # type: ignore[misc] + def handle_live_room_has_or_not_fudai(analyser: Any) -> None: + """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"。 + + 参数: + analyser: 分析器对象 + """ + start_time = time.time() + # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) + try: + already_verified = bool( + getattr(analyser, "_fudai_detail_verified", False) or False + ) + if already_verified: + try: + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋", + ) + except Exception: + pass + # 直接调用详情处理逻辑,不查找福袋 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(已验证详情页)", + elapsed_seconds=round(elapsed, 2), + ) + return + except Exception: + pass + + # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 + try: + now_ts = time.time() + focus_until = float( + getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 + ) + queue_full_waiting = bool( + getattr(analyser, "queue_full_waiting_at_earliest", False) or False + ) + + if focus_until > 0 and now_ts < focus_until and queue_full_waiting: + if analyser.reservations and len(analyser.reservations) > 0: + earliest = analyser.reservations[0] + try: + ft = float(earliest.get("future_ts") or 0.0) + if ft > 0: + join_ahead = float( + getattr( + analyser, "high_value_fudai_join_ahead_seconds", 120 + ) + or 120 + ) + poll_before = float( + getattr(analyser, "poll_before_open_seconds", 10.0) + or 10.0 + ) + time_window_start_ts = ft - join_ahead + time_window_end_ts = ft + max(0.0, poll_before) + + if now_ts < time_window_start_ts: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", + focus_until=int(focus_until), + now_ts=int(now_ts), + time_window_start=int(time_window_start_ts), + remain_seconds=int( + time_window_start_ts - now_ts + ), + ) + except Exception: + pass + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", + elapsed_seconds=round(elapsed, 2), + ) + return + except Exception: + pass + except Exception: + pass + + room_pos_ref: List[int] = [0] + opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) + if not opened: + # 无福袋,交给 flow_control 的"无福袋处理"逻辑 + try: + needswitch_cfg = bool(getattr(analyser, "needswitch", True)) + except Exception: + needswitch_cfg = True + + wait_times_ref = [0] + swipe_times_ref = [0] + reservation_focus_until_ts_ref = [0.0] + reset_to_list_after_reservations_ref = [False] + douyin_flow_control.handle_no_fudai_situation( + analyser, + x=0, + swipe_times=0, + wait_times_ref=wait_times_ref, + needswitch=needswitch_cfg, + reservation_focus_until_ts=0.0, + reservations=[], + room_pos=room_pos_ref[0], + post_switch_delay_s=1.5, + swipe_up_switch_callback=analyser.swipe_up_to_next_live, # type: ignore[attr-defined] + swipe_down_back_callback=lambda: None, + sort_reservations_callback=lambda: None, + clear_reservations_callback=lambda: None, + write_state_callback=lambda: None, + back_to_list_callback=lambda: None, + into_list_callback=lambda: None, + reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, + reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, + swipe_times_ref=swipe_times_ref, + ) + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(无福袋)", + elapsed_seconds=round(elapsed, 2), + ) + return + + # 成功打开详情:调用同一套详情处理逻辑 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(成功打开详情)", + elapsed_seconds=round(elapsed, 2), + ) + + except Exception: + pass + + # x图标:方法2 - 自适应二值化匹配 + try: + res2_adaptive = cv2.matchTemplate( # type: ignore[attr-defined] + roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0))) + except Exception: + pass + + # x图标:方法3 - Otsu二值化匹配 + try: + res3_otsu = cv2.matchTemplate( # type: ignore[attr-defined] + roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0))) + except Exception: + pass + + # x图标:方法4 - 边缘检测匹配(标准参数) + try: + res4_edges = cv2.matchTemplate( # type: ignore[attr-defined] + roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0))) + except Exception: + pass + + # x图标:方法5 - 边缘检测匹配(激进参数) + try: + res5_edges_agg = cv2.matchTemplate( # type: ignore[attr-defined] + roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0))) + except Exception: + pass + + # x图标:方法6 - 形态学处理后的边缘检测匹配 + try: + res6_morph = cv2.matchTemplate( # type: ignore[attr-defined] + roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0))) + except Exception: + pass + + # x图标:方法7 - 强对比度 + TM_CCORR_NORMED(实验中表现较好) + try: + res7_contrast = cv2.matchTemplate( # type: ignore[attr-defined] + roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] + ) + _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast) # type: ignore[attr-defined] + scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0))) + except Exception: + pass + + # x图标:方法8 - 原始图像匹配(作为对比和备用) + try: + res8_original = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) + except Exception: + pass + else: + # xin图标或其他:使用原有方法 + # 方法1: TM_CCOEFF_NORMED(归一化相关系数,对光照变化不敏感) + try: + res1 = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) # type: ignore[attr-defined] + scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) + except Exception: + pass + + # 方法2: TM_CCORR_NORMED(归一化相关,对亮度变化不敏感) + try: + res2 = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED # type: ignore[attr-defined] + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) # type: ignore[attr-defined] + scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) + except Exception: + pass + + # 方法3: TM_SQDIFF_NORMED(归一化平方差,值越小越好,需要转换) + try: + res3 = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED # type: ignore[attr-defined] + ) + min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) # type: ignore[attr-defined] + # 转换为相似度分数(1 - 归一化平方差) + score3 = 1.0 - float(min_val3 or 0.0) + scores.append(("TM_SQDIFF_NORMED", score3)) + except Exception: + pass + + # 选择最高分(如果多个方法都可用,使用加权平均) + if scores: + if icon_name == "x" and use_edges: + # x图标:优先使用最高分的方法,然后计算加权平均 + max_val = 0.0 + best_method = "" + + # 混合策略:优先使用 TM_CCOEFF_NORMED 系列,但如果分数太低,考虑使用 TM_CCORR_NORMED 系列 + # 1. 先找 TM_CCOEFF_NORMED 系列的最高分 + ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] + ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None + + # 2. 找 TM_CCORR_NORMED 系列的最高分 + ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] + ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None + + # 3. 决策:如果 CCOEFF 分数 >= 0.50,优先使用它(更稳定) + # 否则,如果 CCORR 分数 >= 0.75,使用它(需要根据白色比例调整颜色过滤阈值) + # 否则,使用 CCOEFF(即使分数低,也比误判好) + if ccoeff_max and ccoeff_max[1] >= 0.50: + best_method, max_val = ccoeff_max + elif ccorr_max and ccorr_max[1] >= 0.75: + # CCORR 分数较高,可以使用 + best_method, max_val = ccorr_max + elif ccoeff_max: + best_method, max_val = ccoeff_max + elif ccorr_max: + best_method, max_val = ccorr_max + else: + # 回退到最高分 + best_method, max_val = max(scores, key=lambda x: x[1]) + + # 如果多个方法都可用,计算加权平均(提高稳定性) + # 优先使用二值化方法的加权平均 + if len(scores) >= 2: + sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) + top_score = sorted_scores[0][1] + second_score = sorted_scores[1][1] + + # 如果最高分明显高于次高分(差距>0.15),使用最高分 + # 否则使用加权平均(最高分权重0.7,次高分权重0.3) + if top_score - second_score > 0.15: + max_val = top_score + best_method = sorted_scores[0][0] + else: + # 优先选择 TM_CCOEFF_NORMED 系列方法进行加权(避免 CCORR 系列误判) + ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] + if len(ccoeff_scores) >= 2: + max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3 + best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" + elif len(ccoeff_scores) >= 1: + # 如果只有一个 CCOEFF 方法,用它和次高分加权 + max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3 + best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" + else: + # 回退到二值化方法加权 + binary_scores = [s for s in sorted_scores if "二值化" in s[0]] + if len(binary_scores) >= 2: + max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 + best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" + else: + max_val = top_score * 0.7 + second_score * 0.3 + best_method = f"{sorted_scores[0][0]}+{sorted_scores[1][0]}_加权" + elif len(scores) == 1: + # 只有一个方法可用,直接使用 + best_method, max_val = scores[0] + else: + # xin图标或其他:使用原有逻辑 + # 优先使用 TM_CCOEFF_NORMED(最稳定) + max_val = 0.0 + best_method = "" + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + max_val = score + best_method = method + break + elif score > max_val: + max_val = score + best_method = method + + # 如果 TM_CCOEFF_NORMED 可用,使用它;否则使用最高分 + if best_method == "" and scores: + best_method, max_val = max(scores, key=lambda x: x[1]) + + # 如果多个方法都可用,计算加权平均(提高稳定性) + if len(scores) > 1: + # TM_CCOEFF_NORMED 权重最高(0.5),其他方法各0.25 + weighted_sum = 0.0 + total_weight = 0.0 + for method, score in scores: + if method == "TM_CCOEFF_NORMED": + weight = 0.5 + else: + weight = 0.25 + weighted_sum += score * weight + total_weight += weight + if total_weight > 0: + max_val = weighted_sum / total_weight + else: + # 回退到原始方法 + res = cv2.matchTemplate( # type: ignore[attr-defined] + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined] + ) + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined] + max_val = float(max_val or 0.0) + best_method = "TM_CCOEFF_NORMED" + + # 对 x 图标额外应用颜色特征过滤:白色比例过低/过高都认为不是关闭按钮 + passed_color_filter = True + if icon_name == "x" and x_white_ratio is not None: + # 根据实际测试:直播间 x 图标的白色比例通常在 0.05~0.20 之间 + # 推荐页这类画面通常白色比例在 0.10~0.15 之间,但结合模板匹配分数可以区分 + # 如果白色比例过低(<0.05)或过高(>0.25),直接过滤 + # 如果白色比例在 0.10~0.15 之间,需要根据使用的匹配方法调整阈值 + if x_white_ratio < 0.05 or x_white_ratio > 0.25: + passed_color_filter = False + elif 0.10 <= x_white_ratio <= 0.15: + # 这个范围内的白色比例可能是推荐页,需要更高的模板匹配分数 + # 根据测试:推荐页分数约 0.8143,直播间分数约 0.76~0.86 + # 如果使用 TM_CCORR_NORMED 系列,需要 >= 0.82(推荐页 < 0.82,直播间 >= 0.82) + # 如果使用 TM_CCOEFF_NORMED 系列,需要 >= 0.50 + if "TM_CCORR_NORMED" in best_method: + if max_val < 0.82: + passed_color_filter = False + else: + if max_val < 0.50: + passed_color_filter = False + + if max_val > best_score and passed_color_filter: + best_score = float(max_val or 0.0) + best_name = ( + f"assets/{icon_name}.png -> " + f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png" + f" (方法:{best_method})" + ) + + if max_val >= template_threshold and passed_color_filter: + detected = True + except Exception: + continue + + if not detected and best_score == 0.0: + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件" + ) + except Exception: + pass + + try: + analyser._log_kv( # type: ignore[attr-defined] + "阶段诊断", + "_check_in_live_room_by_icon 结果", + detected=int(bool(detected)), + score=round(best_score, 4), # 提高精度到4位小数 + template=best_name or "-", + threshold=round(template_threshold, 4), + 白色比例=x_white_ratio if x_white_ratio is not None else -1.0, + 说明="已优化:使用直方图均衡化+多方法匹配+固定ROI区域+颜色过滤", + ) + except Exception: + pass + + return bool(detected), float(best_score or 0.0) + + @staticmethod # type: ignore[misc] + def handle_in_fudai_detail(analyser: Any) -> None: + """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。 + + 参数: + analyser: 分析器对象 + """ + # 这个方法非常长,直接调用原方法,保持兼容性 + # 注意:由于方法过于复杂(900+行),暂时保持原实现 + # 后续可以进一步拆分 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + + @staticmethod # type: ignore[misc] + def handle_live_room_has_or_not_fudai(analyser: Any) -> None: + """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"。 + + 参数: + analyser: 分析器对象 + """ + start_time = time.time() + # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) + try: + already_verified = bool( + getattr(analyser, "_fudai_detail_verified", False) or False + ) + if already_verified: + try: + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋", + ) + except Exception: + pass + # 直接调用详情处理逻辑,不查找福袋 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(已验证详情页)", + elapsed_seconds=round(elapsed, 2), + ) + return + except Exception: + pass + + # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 + try: + now_ts = time.time() + focus_until = float( + getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 + ) + queue_full_waiting = bool( + getattr(analyser, "queue_full_waiting_at_earliest", False) or False + ) + + if focus_until > 0 and now_ts < focus_until and queue_full_waiting: + if analyser.reservations and len(analyser.reservations) > 0: + earliest = analyser.reservations[0] + try: + ft = float(earliest.get("future_ts") or 0.0) + if ft > 0: + join_ahead = float( + getattr( + analyser, "high_value_fudai_join_ahead_seconds", 120 + ) + or 120 + ) + poll_before = float( + getattr(analyser, "poll_before_open_seconds", 10.0) + or 10.0 + ) + time_window_start_ts = ft - join_ahead + time_window_end_ts = ft + max(0.0, poll_before) + + if now_ts < time_window_start_ts: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", + focus_until=int(focus_until), + now_ts=int(now_ts), + time_window_start=int(time_window_start_ts), + remain_seconds=int( + time_window_start_ts - now_ts + ), + ) + except Exception: + pass + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", + elapsed_seconds=round(elapsed, 2), + ) + return + except Exception: + pass + except Exception: + pass + + room_pos_ref: List[int] = [0] + opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref) + if not opened: + # 无福袋,交给 flow_control 的"无福袋处理"逻辑 + try: + needswitch_cfg = bool(getattr(analyser, "needswitch", True)) + except Exception: + needswitch_cfg = True + + wait_times_ref = [0] + swipe_times_ref = [0] + reservation_focus_until_ts_ref = [0.0] + reset_to_list_after_reservations_ref = [False] + douyin_flow_control.handle_no_fudai_situation( + analyser, + x=0, + swipe_times=0, + wait_times_ref=wait_times_ref, + needswitch=needswitch_cfg, + reservation_focus_until_ts=0.0, + reservations=[], + room_pos=room_pos_ref[0], + post_switch_delay_s=1.5, + swipe_up_switch_callback=analyser.swipe_up_to_next_live, # type: ignore[attr-defined] + swipe_down_back_callback=lambda: None, + sort_reservations_callback=lambda: None, + clear_reservations_callback=lambda: None, + write_state_callback=lambda: None, + back_to_list_callback=lambda: None, + into_list_callback=lambda: None, + reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, + reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, + swipe_times_ref=swipe_times_ref, + ) + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(无福袋)", + elapsed_seconds=round(elapsed, 2), + ) + return + + # 成功打开详情:调用同一套详情处理逻辑 + analyser._handle_in_fudai_detail() # type: ignore[attr-defined] + elapsed = time.time() - start_time + analyser._log_kv( # type: ignore[attr-defined] + "流程", + "_handle_live_room_has_or_not_fudai完成(成功打开详情)", + elapsed_seconds=round(elapsed, 2), + ) \ No newline at end of file diff --git a/douyin/utils/douyin_config.py b/douyin/utils/douyin_config.py index 7a059f1..9f6ff24 100644 --- a/douyin/utils/douyin_config.py +++ b/douyin/utils/douyin_config.py @@ -170,6 +170,11 @@ class ConfigManager: config["reservation_back_verify_enabled"] ) + if "record_room_title_mapping_enabled" in config: + analyser.record_room_title_mapping_enabled = bool( + config["record_room_title_mapping_enabled"] + ) + if "reservation_back_swipe_delay" in config: analyser.reservation_back_swipe_delay = float( config["reservation_back_swipe_delay"] or 0.6 diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index 5cfe1b5..3697941 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -15,6 +15,7 @@ from __future__ import annotations import os import time import shutil +import json from typing import Any, Optional, Tuple, Dict, Union from datetime import datetime @@ -25,7 +26,7 @@ from douyin.handlers import douyin_screenshot_handler class HelperFunctions: """工具函数集合:通用工具方法""" - @staticmethod # type: ignore[misc] + @staticmethod def click(analyser: Any, x: int, y: int) -> None: """兼容原版 fudai_analyse.click:转发到底层 operation.click。 @@ -39,7 +40,7 @@ class HelperFunctions: analyser.operation.click(analyser.device_id, int(x), int(y)) elapsed = time.time() - start_time if elapsed > 0.1: # 只记录耗时较长的点击操作 - analyser._log_kv( # type: ignore[attr-defined] + analyser._log_kv( "操作", "点击操作", x=int(x), @@ -113,14 +114,16 @@ class HelperFunctions: None - 未识别到相关文本 """ try: - # OCR区域:(175, 1267) 到 (890, 1377) + # OCR区域:(175, 1200) 到 (890, 1377) - 向上扩展了识别区域 # 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures) douyin_screenshot_handler.ScreenshotHandler.cut_pic( - analyser, 175, 1267, 890, 1377, "", "开奖结果按钮", 0 + analyser, 175, 1200, 890, 1377, "", "开奖结果按钮", 0 ) # OCR识别 - ocr_text = str(analyser.operation.analyse_pic_word("开奖结果按钮", 0) or "") + from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore + name_res = preprocess_for_ocr(analyser, "开奖结果按钮") + ocr_text = str(analyser.operation.analyse_pic_word(name_res, 0) or "") analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined] @@ -132,6 +135,18 @@ class HelperFunctions: or "领取奖品" in ocr_text or "立即领取" in ocr_text ): + # 检查是否为误识别(检查相似字记录) + if HelperFunctions._is_false_positive_prize_text(ocr_text): + analyser._log_kv( # type: ignore[attr-defined] + "开奖结果", "识别到相似字,判定为误识别", text=ocr_text + ) + return None + # 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查 + if ocr_text.strip() != "立即领取奖品": + HelperFunctions._save_false_positive(ocr_text) + analyser._log_kv( # type: ignore[attr-defined] + "开奖结果", "记录相似字文本", text=ocr_text + ) return "立即领取奖品" else: # 尝试模式1识别 @@ -145,6 +160,18 @@ class HelperFunctions: or "领取奖品" in ocr_text_1 or "立即领取" in ocr_text_1 ): + # 检查是否为误识别(检查相似字记录) + if HelperFunctions._is_false_positive_prize_text(ocr_text_1): + analyser._log_kv( # type: ignore[attr-defined] + "开奖结果", "识别到相似字,判定为误识别", text=ocr_text_1 + ) + return None + # 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查 + if ocr_text_1.strip() != "立即领取奖品": + HelperFunctions._save_false_positive(ocr_text_1) + analyser._log_kv( # type: ignore[attr-defined] + "开奖结果", "记录相似字文本", text=ocr_text_1 + ) return "立即领取奖品" return None @@ -152,6 +179,60 @@ class HelperFunctions: analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined] return None + @staticmethod # type: ignore[misc] + def _get_false_positive_file_path() -> str: + """获取误识别记录文件路径""" + try: + import path_config + pic_dir = path_config.get_pic_dir() + except Exception: + base_dir = os.path.dirname(__file__) + pic_dir = os.path.join(base_dir, "pic") + false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") + return false_positive_file + + @staticmethod # type: ignore[misc] + def _load_false_positives() -> set[str]: + """加载误识别文本记录""" + false_positive_file = HelperFunctions._get_false_positive_file_path() + if not os.path.exists(false_positive_file): + return set() + try: + with open(false_positive_file, "r", encoding="utf-8") as f: + data = json.load(f) + return set(data.get("false_positives", [])) + except Exception: + return set() + + @staticmethod # type: ignore[misc] + def _save_false_positive(text: str) -> None: + """保存误识别文本到记录文件""" + false_positive_file = HelperFunctions._get_false_positive_file_path() + os.makedirs(os.path.dirname(false_positive_file), exist_ok=True) + + false_positives = HelperFunctions._load_false_positives() + false_positives.add(text.strip()) + + try: + with open(false_positive_file, "w", encoding="utf-8") as f: + json.dump({"false_positives": list(false_positives)}, f, ensure_ascii=False, indent=2) + except Exception: + pass + + @staticmethod # type: ignore[misc] + def _is_false_positive_prize_text(text: str) -> bool: + """检查文本是否为误识别的"立即领取奖品"相似字""" + false_positives = HelperFunctions._load_false_positives() + text_clean = text.strip() + # 检查是否在误识别列表中 + if text_clean in false_positives: + return True + # 检查是否包含误识别文本 + for fp_text in false_positives: + if fp_text in text_clean or text_clean in fp_text: + return True + return False + @staticmethod # type: ignore[misc] def handle_lottery_result_by_ocr(analyser: Any, result_type: str) -> None: """根据OCR识别结果处理开奖结果。 @@ -166,9 +247,9 @@ class HelperFunctions: # 识别到"我知道了",点击按钮,切换下一个直播间 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, (1267+1377)/2=1322 + # 按钮位置在OCR区域中心附近 (175+890)/2=532, (1200+1377)/2=1288.5≈1289 btn_x = int(532 * rx // 1080) - btn_y = int(1322 * ry // 2400) + btn_y = int(1289 * ry // 2400) analyser.operation.click(analyser.device_id, btn_x, btn_y) analyser._log_kv( # type: ignore[attr-defined] @@ -311,4 +392,4 @@ class HelperFunctions: tag, f"{msg} - 异常: {type(e).__name__}" ) except Exception: - pass + pass \ No newline at end of file diff --git a/douyin/utils/ocr_preprocess.py b/douyin/utils/ocr_preprocess.py new file mode 100644 index 0000000..bc1d575 --- /dev/null +++ b/douyin/utils/ocr_preprocess.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +""" +OCR 预处理工具 +提供统一的图像预处理流水线:灰度、放大、自动对比、锐化等,以提高 OCR 识别稳定性。 +接口尽量简单:preprocess_for_ocr(analyser, cut_pic_name) -> 返回用于 OCR 的图片名称(不含扩展名)。 +""" + +from typing import Any +import os + +def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str: + """对已由 ScreenshotHandler.cut_pic 生成的裁剪图做预处理,返回可传入 analyse_pic_* 的图片名。 + + 参数: + analyser: fudai_analyse 实例 + cut_pic_name: cut_pic 时使用的名称(不含扩展名) + 返回: + 返回预处理后图片的名称(不含扩展名),调用者应把它传给 analyse_pic_word/analyse_pic_digits + """ + try: + from PIL import Image, ImageOps, ImageFilter + from path_config import get_cut_pic_path + except Exception: + # 如果 PIL 或 path_config 不可用,回退到原名 + return cut_pic_name + + src = get_cut_pic_path(cut_pic_name) + pre_name = f"{cut_pic_name}_preprocessed" + dst = get_cut_pic_path(pre_name) + + try: + if not os.path.exists(src): + return cut_pic_name + img = Image.open(src) + img.load() + # 转灰度 + img = img.convert("L") + # 放大两倍(Lanczos) + img = img.resize((img.width * 2, img.height * 2), Image.LANCZOS) + # 自动对比并锐化 + img = ImageOps.autocontrast(img) + img = img.filter(ImageFilter.SHARPEN) + # 保存为目标路径(覆盖或新文件) + img.save(dst) + return pre_name + except Exception: + # 任何异常回退到原名,保证不抛出 + try: + return cut_pic_name + except Exception: + return cut_pic_name + + + + + + + + + + + + + + + + + + diff --git a/douyin_guaji.code-workspace b/douyin_guaji.code-workspace index b12e661..511e50c 100644 --- a/douyin_guaji.code-workspace +++ b/douyin_guaji.code-workspace @@ -50,3 +50,25 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/test_output.txt b/example_filter_usage.py similarity index 100% rename from test_output.txt rename to example_filter_usage.py diff --git a/fudai_detail_modules/fudai_detail_coupon_detection.py b/fudai_detail_modules/fudai_detail_coupon_detection.py index b08370a..ff6ce3e 100644 --- a/fudai_detail_modules/fudai_detail_coupon_detection.py +++ b/fudai_detail_modules/fudai_detail_coupon_detection.py @@ -1,15 +1,9 @@ -from __future__ import annotations - """ 优惠券弹窗检测模块 -================== - -检测当前弹窗是否为优惠券弹窗,而非真正的福袋详情页。 """ from typing import Any import os - from PIL import Image @@ -37,274 +31,240 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: pass return False - # 使用统一的截图路径配置 try: - import path_config - path = path_config.get_screenshot_path() - except Exception: - # 回退到旧路径(向后兼容) - import path_config - path = path_config.get_screenshot_path() - try: - pic = Image.open(path) - pic.load() # Force load to catch truncated files early - except (OSError, IOError, SyntaxError): - # Handle truncated image files - return False - except Exception: - return False + # 使用统一的截图路径配置 + try: + import path_config + path = path_config.get_screenshot_path() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + path = path_config.get_screenshot_path() - pic = pic.convert("RGBA") - pix = pic.load() - w, h = pic.size + try: + pic = Image.open(path) + pic.load() # Force load to catch truncated files early + except (OSError, IOError, SyntaxError): + # Handle truncated image files + return False + except Exception: + return False - # 扫描区域:153,351 到 266,451(基于1080x2400基准坐标) - # 根据实际分辨率缩放坐标 - scale_x = w / 1080.0 - scale_y = h / 2400.0 - x1 = int(153 * scale_x) - y1 = int(351 * scale_y) - x2 = int(266 * scale_x) - y2 = int(451 * scale_y) - - # 边界检查 - x1 = max(0, min(x1, w)) - y1 = max(0, min(y1, h)) - x2 = max(0, min(x2, w)) - y2 = max(0, min(y2, h)) - - if x1 >= x2 or y1 >= y2: - return False + pic = pic.convert("RGBA") + pix = pic.load() + w, h = pic.size - fudai_like = 0 - coupon_like = 0 - step_x = max(1, (x2 - x1) // 40) - step_y = max(1, (y2 - y1) // 40) + # 扫描区域:153,351 到 266,451(基于1080x2400基准坐标) + # 根据实际分辨率缩放坐标 + scale_x = w / 1080.0 + scale_y = h / 2400.0 + x1 = int(153 * scale_x) + y1 = int(351 * scale_y) + x2 = int(266 * scale_x) + y2 = int(451 * scale_y) - for yy in range(y1, y2, step_y): - for xx in range(x1, x2, step_x): - try: - p = pix[xx, yy] - except Exception as e: - # 像素访问失败,跳过该像素(可能是坐标越界) - continue - if not (isinstance(p, tuple) and len(p) >= 3): - continue - r, g, b = int(p[0]), int(p[1]), int(p[2]) - # 福袋:粉/紫/粉蓝 - if r >= 200 and b >= 210 and 80 <= g <= 230: - fudai_like += 1 - # 券:偏橙色 - if r >= 200 and 120 <= g <= 230 and b <= 180: - coupon_like += 1 + # 边界检查 + x1 = max(0, min(x1, w)) + y1 = max(0, min(y1, h)) + x2 = max(0, min(x2, w)) + y2 = max(0, min(y2, h)) + + if x1 >= x2 or y1 >= y2: + return False + + fudai_like = 0 + coupon_like = 0 + step_x = max(1, (x2 - x1) // 40) + step_y = max(1, (y2 - y1) // 40) + + for yy in range(y1, y2, step_y): + for xx in range(x1, x2, step_x): + try: + p = pix[xx, yy] + except Exception as e: + # 像素访问失败,跳过该像素(可能是坐标越界) + continue + if not (isinstance(p, tuple) and len(p) >= 3): + continue + r, g, b = int(p[0]), int(p[1]), int(p[2]) + # 福袋:粉/紫/粉蓝 + if r >= 200 and b >= 210 and 80 <= g <= 230: + fudai_like += 1 + # 券:偏橙色 + if r >= 200 and 120 <= g <= 230 and b <= 180: + coupon_like += 1 - try: - analyser._log_kv( - "弹窗", - "弹窗颜色统计", - fudai_like=fudai_like, - coupon_like=coupon_like, - ) - except Exception as e: try: analyser._log_kv( - "错误", - "记录弹窗颜色统计日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", + "弹窗", + "弹窗颜色统计", + fudai_like=fudai_like, + coupon_like=coupon_like, ) - except Exception: - pass - - # 如果券像素明显多于粉袋像素,可能需要OCR确认 - is_coupon_like_by_color = coupon_like > fudai_like * 1.2 - - # 检测是否同时有福袋详情特征(通过像素检测) - has_fudai_detail = False - try: - from douyin.detection import douyin_pixel - resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) - pic_rgb = pic.convert("RGB") - # 获取模板匹配阈值(优先使用福袋详情页专用阈值) - template_threshold = float( - getattr(analyser, "fudai_detail_template_threshold", None) or - getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 - ) - result = douyin_pixel.detect_fudai_detail_page( - pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi, - template_threshold, return_info=True, analyser=analyser - ) - if isinstance(result, tuple): - has_fudai_detail, detect_info = result - # 记录检测信息到日志 + except Exception as e: try: - task_count = detect_info.get("task_count", 0) - detection_method = detect_info.get("method", "unknown") - method_name = "任务数量检测" if detection_method == "task_count" else "未知" analyser._log_kv( - "弹窗", - f"检测福袋详情页({method_name})", - task_count=task_count, - method=detection_method, + "错误", + "记录弹窗颜色统计日志失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录福袋详情检测日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - else: - has_fudai_detail = result - except Exception as e: + except Exception: + pass + + # 如果券像素明显多于粉袋像素,可能需要OCR确认 + is_coupon_like_by_color = coupon_like > fudai_like * 1.2 + + # 检测是否同时有福袋详情特征(通过像素检测) + has_fudai_detail = False try: - analyser._log_kv( - "错误", - "检测福袋详情页失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", + from douyin.detection import douyin_pixel + resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) + pic_rgb = pic.convert("RGB") + # 获取模板匹配阈值(优先使用福袋详情页专用阈值) + template_threshold = float( + getattr(analyser, "fudai_detail_template_threshold", None) or + getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) - except Exception: - pass - - # 如果颜色统计显示可能是优惠券,需要严格确认: - # 1. 先进行模板匹配确认(使用 detect_coupon_popup_background) - # 2. 如果模板匹配成功,再进行OCR确认"开心收下"按钮 - # 3. 只有模板匹配和OCR都确认时,才判定为优惠券弹窗 - # 这样可以避免因识别福袋位置失败而误判为优惠券弹窗 - if is_coupon_like_by_color: - try: - # 步骤1:模板匹配确认 - template_matched = False - try: - from douyin.detection import douyin_pixel - pic_rgb = pic.convert("RGB") - template_matched = douyin_pixel.detect_coupon_popup_background(pic_rgb) - except Exception as e: - try: - analyser._log_kv( - "错误", - "模板匹配确认异常", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - - if not template_matched: - # 模板匹配失败,即使颜色统计偏向优惠券,也不判定为优惠券弹窗 - # 可能是识别福袋位置失败,导致点击了错误位置 + result = douyin_pixel.detect_fudai_detail_page( + pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi, + template_threshold, return_info=True, analyser=analyser + ) + if isinstance(result, tuple): + has_fudai_detail, detect_info = result + # 记录检测信息到日志 try: analyser._log_kv( "弹窗", - "颜色统计偏向优惠券,但模板匹配未命中,不判定为优惠券弹窗", - 说明="可能是识别福袋位置失败,点击了错误位置", + "福袋详情检测结果", + has_fudai_detail=has_fudai_detail, + detect_info=detect_info if detect_info else {}, ) except Exception as e: try: analyser._log_kv( "错误", - "记录模板匹配失败日志失败", + "记录福袋详情检测日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass - return False - - # 步骤2:OCR确认"开心收下"按钮(模板匹配成功后) - if has_fudai_detail: - analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认") else: - analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认") - - # 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域) - # 保存完整截图并标注OCR区域 + has_fudai_detail = bool(result) + except Exception as e: try: - from douyin.handlers import douyin_screenshot_manager - # 使用统一的截图路径配置 - try: - import path_config - pic_path = path_config.get_screenshot_path() - except Exception: - # 回退到旧路径(向后兼容) - import path_config - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - pic_check = Image.open(pic_path) - pic_check.load() - pic_rgb_check = pic_check.convert("RGB") - - width, height = pic_rgb_check.size - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - - x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140 - x1 = int(x1_base * width / rx) - y1 = int(y1_base * height / ry) - x2 = int(x2_base * width / rx) - y2 = int(y2_base * height / ry) - - x1 = max(0, min(x1, width - 1)) - y1 = max(0, min(y1, height - 1)) - x2 = max(0, min(x2, width - 1)) - y2 = max(0, min(y2, height - 1)) - - if x1 < x2 and y1 < y2: - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb_check, - operation_type="ocr", - picname="参与按钮", - step="before_ocr", - coords=(x1, y1, x2, y2), - extra_info={ - "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", - "size": f"{x2_base-x1_base}x{y2_base-y1_base}", - "purpose": "检测开心收下", - } - ) - if debug_path: + analyser._log_kv( + "错误", + "福袋详情检测异常", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + + # 如果颜色不像优惠券,且没有福袋详情特征,直接判定为福袋详情页 + if not is_coupon_like_by_color: + if not has_fudai_detail: + analyser._log_kv("弹窗", "颜色统计不像优惠券,且未检测到福袋详情,判定为福袋详情页") + else: + analyser._log_kv("弹窗", "颜色统计不像优惠券,但检测到福袋详情,判定为福袋详情页") + return False + + # 如果颜色像优惠券,但没有福袋详情特征,可能只是误判 + if not has_fudai_detail: + analyser._log_kv("弹窗", "颜色统计像优惠券,但未检测到福袋详情,判定为福袋详情页(可能是误判)") + return False + + # 步骤2:OCR确认"开心收下"按钮(模板匹配成功后) + if has_fudai_detail: + analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认") + else: + analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认") + + # 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域) + # 保存完整截图并标注OCR区域 + try: + from douyin.handlers import douyin_screenshot_manager + # 使用统一的截图路径配置 + try: + import path_config + pic_path = path_config.get_screenshot_path() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + pic_check = Image.open(pic_path) + pic_check.load() + pic_rgb_check = pic_check.convert("RGB") + + width, height = pic_rgb_check.size + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + + x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140 + x1 = int(x1_base * width / rx) + y1 = int(y1_base * height / ry) + x2 = int(x2_base * width / rx) + y2 = int(y2_base * height / ry) + + x1 = max(0, min(x1, width - 1)) + y1 = max(0, min(y1, height - 1)) + x2 = max(0, min(x2, width - 1)) + y2 = max(0, min(y2, height - 1)) + + if x1 < x2 and y1 < y2: + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb_check, + operation_type="ocr", + picname="参与按钮", + step="before_ocr", + coords=(x1, y1, x2, y2), + extra_info={ + "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", + "size": f"{x2_base-x1_base}x{y2_base-y1_base}", + "purpose": "检测开心收下", + } + ) + if debug_path: + try: + analyser._log_kv( + "[调试图像]", + "OCR识别前保存完整截图(参与按钮-检测开心收下)", + path=debug_path, + ) + except Exception as e: try: analyser._log_kv( - "[调试图像]", - "OCR识别前保存完整截图(参与按钮-检测开心收下)", - path=debug_path, + "错误", + "记录调试图像日志失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录调试图像日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "错误", - "保存参与按钮调试截图失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "错误", + "保存参与按钮调试截图失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + + try: analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮") - + # 并行执行模式0和模式1的OCR(如果启用模式1) enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) coupon_text = "" @@ -328,7 +288,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: else: # 只使用模式0 coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") - + if coupon_text and "开心收下" in coupon_text: # 模板匹配 + OCR 都确认,判定为优惠券弹窗 analyser._log_kv("弹窗", "模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50]) @@ -362,7 +322,19 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: except Exception: pass return False - - # 否则判定为福袋详情页 - return False + # 否则判定为福袋详情页 + return False + except Exception as e: + # 整个函数异常处理 + try: + analyser._log_kv( + "错误", + "优惠券弹窗检测过程异常", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + return False \ No newline at end of file diff --git a/fudai_detail_modules/fudai_detail_room_title.py b/fudai_detail_modules/fudai_detail_room_title.py index 661a385..24be053 100644 --- a/fudai_detail_modules/fudai_detail_room_title.py +++ b/fudai_detail_modules/fudai_detail_room_title.py @@ -156,7 +156,7 @@ def read_live_room_title_core( ) -> Tuple[str, str]: """读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。 - 使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。 + 只使用指定区域 (144,144) 到 (329,185) 进行识别,避免多次截图。 """ try: analyser.operation.get_screenshot(analyser.device_id) @@ -171,79 +171,26 @@ def read_live_room_title_core( ) except Exception: pass - # 如果是切换直播间后立即调用,等待标题区域出现(避免识别到空白或旧截图) - try: - if getattr(analyser, "_just_switched_room", False): - wait_seconds = float(getattr(analyser, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0) - poll_interval = 0.5 - start_ts = time.time() - while time.time() - start_ts < wait_seconds: - try: - # 先截图并切割 mid 区域做快速检测(使用临时名字,不覆盖正式裁剪) - analyser.operation.get_screenshot(analyser.device_id) - analyser.cut_pic(80, 128, 560, 230, "", "live_room_title_mid_tmp", y_pianyi) - txt = analyser.operation.analyse_pic_word("live_room_title_mid_tmp", 0) - if txt and str(txt).strip(): - break - except Exception: - pass - # 在等待期间执行可选的后台任务(例如处理弹窗等),以提高并发性 - try: - if hasattr(analyser, "background_tick") and callable(getattr(analyser, "background_tick")): - analyser.background_tick() - except Exception: - pass - time.sleep(poll_interval) - try: - analyser._just_switched_room = False - except Exception: - pass - except Exception: - pass - cands: List[Tuple[str, str, str]] = [] - # mid ROI:优先使用更大区域,减少"只截到尾巴1个字" + # 只使用指定区域 (144,144) 到 (329,185),只尝试一次OCR(mode 0) try: - analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi) + analyser.cut_pic(144, 144, 329, 185, '', 'live_room_title_mid', y_pianyi) t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0) - cands.append((t, r, 'mid_cc0')) - if len(t or "") < min_len: - t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1) - cands.append((t1, r1, 'mid_cc1')) + title = t + raw_text = r except Exception as e: try: analyser._log_kv( "错误", - "OCR识别直播间标题(mid区域)失败", + "OCR识别直播间标题失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass - - # large ROI:进一步扩大,兼容机型/系统字体/刘海偏移 - if not cands or max(len(x[0] or "") for x in cands) < min_len: - try: - analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi) - t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0) - cands.append((t2, r2, 'large_cc0')) - if len(t2 or "") < min_len: - t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1) - cands.append((t3, r3, 'large_cc1')) - except Exception: - pass - - # small ROI:最后兜底(历史区域),使用优化后的坐标 - if not cands or max(len(x[0] or "") for x in cands) <= 1: - try: - analyser.cut_pic(147, 160, 301, 191, '', 'live_room_title_small', y_pianyi) - t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0) - cands.append((t4, r4, 'small_cc0')) - except Exception: - pass - - title, raw_text = _pick_best_room_title(cands, min_len) + title = "" + raw_text = "" # 更新 analyser 的属性 try: diff --git a/gui/components/__init__.py b/gui/components/__init__.py index 79cf197..3653f59 100644 --- a/gui/components/__init__.py +++ b/gui/components/__init__.py @@ -17,3 +17,25 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/components/config_manager.py b/gui/components/config_manager.py index 992214f..02740f0 100644 --- a/gui/components/config_manager.py +++ b/gui/components/config_manager.py @@ -57,3 +57,25 @@ def save_ui_to_config( + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/components/device_selector.py b/gui/components/device_selector.py index cc8eeeb..c7b10a1 100644 --- a/gui/components/device_selector.py +++ b/gui/components/device_selector.py @@ -67,3 +67,25 @@ def create_device_selector( + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/components/image_viewer.py b/gui/components/image_viewer.py index 5f691c8..2707455 100644 --- a/gui/components/image_viewer.py +++ b/gui/components/image_viewer.py @@ -53,3 +53,25 @@ def create_image_viewer( + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/components/log_color_config.py b/gui/components/log_color_config.py new file mode 100644 index 0000000..0a642ee --- /dev/null +++ b/gui/components/log_color_config.py @@ -0,0 +1,540 @@ +""" +日志颜色配置模块 +================ + +为不同的操作类型定义颜色标签,支持明亮和暗色主题。 +""" + +from typing import Dict, Optional + + +# 操作类型关键词映射(用于识别日志中的操作类型) +OPERATION_KEYWORDS: Dict[str, list] = { + "ocr": [ + "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", + "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" + ], + "click": [ + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "返回", "确认", "关闭", "发送", "加入" + ], + "swipe": [ + "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", + "回退", "切换直播间", "切换房间" + ], + "screenshot": [ + "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" + ], + "detection": [ + "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", + "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" + ], + "decision": [ + "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", + "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" + ], + "reservation": [ + "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", + "高价值预约", "预约回退", "预约校验" + ], + "fansclub": [ + "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" + ], + "lottery": [ + "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" + ], + "stage": [ + "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", + "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" + ], + "performance": [ + "耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率" + ], + "error": [ + "错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout" + ], + "success": [ + "成功", "SUCCESS", "完成", "完成", "已", "完成" + ], + "info": [ + "信息", "INFO", "提示", "注意", "开始", "启动", "停止" + ], + "flow": [ + "流程", "flow", "处理", "执行", "运行", "完成" + ], + "operation": [ + "操作", "operation", "动作", "行为" + ] +} + + + + + + + +from typing import Dict, Optional + + +# 操作类型关键词映射(用于识别日志中的操作类型) +OPERATION_KEYWORDS: Dict[str, list] = { + "ocr": [ + "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", + "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" + ], + "click": [ + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "返回", "确认", "关闭", "发送", "加入" + ], + "swipe": [ + "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", + "回退", "切换直播间", "切换房间" + ], + "screenshot": [ + "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" + ], + "detection": [ + "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", + "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" + ], + "decision": [ + "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", + "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" + ], + "reservation": [ + "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", + "高价值预约", "预约回退", "预约校验" + ], + "fansclub": [ + "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" + ], + "lottery": [ + "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" + ], + "stage": [ + "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", + "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" + ], + "performance": [ + "耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率" + ], + "error": [ + "错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout" + ], + "success": [ + "成功", "SUCCESS", "完成", "完成", "已", "完成" + ], + "info": [ + "信息", "INFO", "提示", "注意", "开始", "启动", "停止" + ], + "flow": [ + "流程", "flow", "处理", "执行", "运行", "完成" + ], + "operation": [ + "操作", "operation", "动作", "行为" + ] +} + + +def get_operation_type(line: str) -> Optional[str]: + """ + 根据日志行内容识别操作类型 + + 日志格式通常是: [时间] [GUI] - 操作类型 内容 + 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) + + Args: + line: 日志行内容 + + Returns: + 操作类型名称,如果无法识别则返回None + """ + line_lower = line.lower() + + # 优先级1: 识别日志内容开头的操作类型(最精确) + # 日志格式: [时间] [GUI] - 操作类型 内容 + # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 + # [GUI] - 滑动上滑切换直播间 + # [GUI] - 阶段诊断开始阶段诊断 + # [GUI] - 预约[预约]记录直播间标题 + + import re + # 提取日志内容部分(去掉时间戳和标签) + # 匹配格式: [时间] [标签] - 内容 + content_match = re.search(r'\]\s*-\s*(.+)$', line) + if content_match: + content = content_match.group(1).strip() + content_lower = content.lower() + + # 操作类型关键词映射(按优先级排序,更具体的在前) + operation_type_map = [ + # 检测相关(最具体) + ("阶段诊断", "detection"), + ("阶段检测", "detection"), + ("并行检测", "detection"), + ("像素检测", "detection"), + ("模板匹配", "detection"), + ("检测", "detection"), + # 滑动相关 + ("滑动", "swipe"), + ("上滑", "swipe"), + ("下滑", "swipe"), + ("切换直播间", "swipe"), + # 预约相关 + ("预约", "reservation"), + # OCR相关 + ("OCR", "ocr"), + ("ocr识别", "ocr"), + ("识别", "ocr"), + # 点击相关 + ("点击", "click"), + # 截图相关 + ("截图", "screenshot"), + # 流程相关 + ("流程", "flow"), + # 决策相关 + ("决策", "decision"), + ("行为识别", "decision"), + # 开奖相关 + ("开奖", "lottery"), + ("抽奖结果", "lottery"), + # 粉丝团相关 + ("粉丝团", "fansclub"), + # 操作相关(通用,放后面) + ("操作", "operation"), + # 自救相关 + ("自救", "info"), + # 错误相关 + ("错误", "error"), + ("异常", "error"), + # 成功相关 + ("成功", "success"), + # 信息相关(最通用,放最后) + ("信息", "info"), + ] + + # 检查内容开头是否匹配操作类型 + for keyword, op_type in operation_type_map: + # 检查是否在内容开头(更精确) + if content_lower.startswith(keyword.lower()): + return op_type + # 或者检查是否紧跟在 " - " 后面 + if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower: + return op_type + + # 优先级2: 使用日志标签识别(如果内容中没有匹配到) + tag_match = re.search(r'\[([^\]]+)\]', line) + if tag_match: + tag = tag_match.group(1).lower() + + # 标签到操作类型的映射(精确匹配) + tag_to_op_type = { + "阶段诊断": "detection", + "阶段检测": "detection", + "截图": "screenshot", + "ocr": "ocr", + "ocr识别": "ocr", + "点击": "click", + "滑动": "swipe", + "预约": "reservation", + "找福袋图标": "detection", + "福袋查找": "detection", + "自救": "info", + "流程": "flow", + "行为识别": "decision", + "决策": "decision", + "错误": "error", + "异常": "error", + "成功": "success", + "信息": "info", + "提示": "info", + } + + # 精确匹配标签 + if tag in tag_to_op_type: + return tag_to_op_type[tag] + + # 部分匹配标签(用于更灵活的匹配) + for tag_key, op_type in tag_to_op_type.items(): + if tag_key in tag or tag in tag_key: + return op_type + + # 优先级2: 使用关键词匹配(更具体的短语优先) + # 定义更具体的关键词短语(按优先级排序) + specific_patterns = [ + # 检测相关(更具体的短语优先) + ("阶段诊断", "detection"), + ("阶段检测", "detection"), + ("像素检测", "detection"), + ("模板匹配", "detection"), + ("并行检测", "detection"), + # OCR相关 + ("OCR识别", "ocr"), + ("OCR模式", "ocr"), + ("识别成功", "ocr"), + ("识别失败", "ocr"), + # 点击相关 + ("点击成功", "click"), + ("点击失败", "click"), + ("参与按钮", "click"), + # 滑动相关 + ("向上滑动", "swipe"), + ("向下滑动", "swipe"), + ("切换直播间", "swipe"), + # 预约相关 + ("记录预约", "reservation"), + ("预约窗口", "reservation"), + ("预约队列", "reservation"), + # 开奖相关 + ("抽奖结果", "lottery"), + ("等待开奖", "lottery"), + ("开奖时间", "lottery"), + # 粉丝团相关 + ("加入粉丝团", "fansclub"), + ("粉丝团失败", "fansclub"), + ("粉丝团成功", "fansclub"), + ] + + # 先检查更具体的短语 + for pattern, op_type in specific_patterns: + if pattern.lower() in line_lower: + return op_type + + # 优先级3: 使用通用关键词匹配(按操作类型优先级) + # 调整顺序,让更具体的操作类型优先 + priority_order = [ + "lottery", # 开奖相关(更具体) + "fansclub", # 粉丝团(更具体) + "reservation", # 预约(更具体) + "decision", # 决策(更具体) + "detection", # 检测(较具体) + "ocr", # OCR(较具体) + "click", # 点击(较具体) + "swipe", # 滑动(较具体) + "flow", # 流程(较具体) + "operation", # 操作(较具体) + "screenshot", # 截图(较通用,放后面) + "stage", # 阶段(较通用) + "performance", # 性能(较通用) + "error", # 错误(较通用) + "success", # 成功(较通用) + "info", # 信息(最通用,放最后) + ] + + # 按优先级顺序检查 + for op_type in priority_order: + if op_type in OPERATION_KEYWORDS: + for keyword in OPERATION_KEYWORDS[op_type]: + # 避免过于宽泛的关键词误匹配 + if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]: + # 这些关键词太宽泛,只在特定上下文中使用 + # 检查是否在更具体的上下文中 + if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line): + return op_type + elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower): + return op_type + elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower): + return op_type + # 其他宽泛关键词跳过,避免误匹配 + continue + + if keyword.lower() in line_lower: + return op_type + + return None + + +def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: + """ + 获取颜色配置(根据主题) + + Args: + theme: 主题名称("litera", "darkly" 等) + + Returns: + 颜色配置字典,包含每种操作类型的颜色设置 + """ + light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} + is_light = theme.lower() in light_themes + + if is_light: + # 明亮主题颜色配置(深色文字,与白色背景对比,高区分度) + return { + "ocr": { + "foreground": "#0052CC", # 鲜明蓝色 - OCR识别 + "background": "#D6E8FF", # 浅蓝色背景 + }, + "click": { + "foreground": "#D32F2F", # 鲜明红色 - 点击操作 + "background": "#FFE0E0", # 浅红色背景 + }, + "swipe": { + "foreground": "#2E7D32", # 鲜明绿色 - 滑动操作 + "background": "#E0F2E8", # 浅绿色背景 + }, + "screenshot": { + "foreground": "#7B1FA2", # 鲜明紫色 - 截图操作 + "background": "#F3E5F5", # 浅紫色背景 + }, + "detection": { + "foreground": "#F57C00", # 鲜明橙色 - 检测操作 + "background": "#FFF3E0", # 浅橙色背景 + }, + "decision": { + "foreground": "#C2185B", # 鲜明品红色 - 决策操作 + "background": "#FCE4EC", # 浅品红色背景 + }, + "reservation": { + "foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色) + "background": "#E0F2F1", # 浅青色背景 + }, + "fansclub": { + "foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色) + "background": "#F3E5F5", # 浅紫红色背景 + }, + "lottery": { + "foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色) + "background": "#FFEBEE", # 浅橙红色背景 + }, + "stage": { + "foreground": "#616161", # 深灰色 - 阶段信息 + "background": "#F5F5F5", # 浅灰色背景 + }, + "performance": { + "foreground": "#00796B", # 鲜明青绿色 - 性能信息 + "background": "#E0F2F1", # 浅青绿色背景 + }, + "error": { + "foreground": "#C62828", # 鲜明深红色 - 错误 + "background": "#FFCDD2", # 浅红色背景 + }, + "success": { + "foreground": "#2E7D32", # 鲜明深绿色 - 成功 + "background": "#C8E6C9", # 浅绿色背景 + }, + "info": { + "foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色) + "background": "#BBDEFB", # 浅天蓝色背景 + }, + "flow": { + "foreground": "#5D4037", # 深棕色 - 流程操作 + "background": "#EFEBE9", # 浅棕色背景 + }, + "operation": { + "foreground": "#455A64", # 深蓝灰色 - 操作动作 + "background": "#ECEFF1", # 浅蓝灰色背景 + }, + } + else: + # 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度) + return { + "ocr": { + "foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别 + "background": "#0D47A1", # 深蓝色背景 + }, + "click": { + "foreground": "#EF5350", # 鲜明亮红色 - 点击操作 + "background": "#B71C1C", # 深红色背景 + }, + "swipe": { + "foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作 + "background": "#1B5E20", # 深绿色背景 + }, + "screenshot": { + "foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作 + "background": "#4A148C", # 深紫色背景 + }, + "detection": { + "foreground": "#FFA726", # 鲜明亮橙色 - 检测操作 + "background": "#E65100", # 深橙色背景 + }, + "decision": { + "foreground": "#EC407A", # 鲜明亮品红色 - 决策操作 + "background": "#880E4F", # 深品红色背景 + }, + "reservation": { + "foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色) + "background": "#004D40", # 深青色背景 + }, + "fansclub": { + "foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色) + "background": "#4A148C", # 深紫红色背景 + }, + "lottery": { + "foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色) + "background": "#BF360C", # 深橙红色背景 + }, + "stage": { + "foreground": "#90A4AE", # 亮灰色 - 阶段信息 + "background": "#263238", # 深灰色背景 + }, + "performance": { + "foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息 + "background": "#004D40", # 深青绿色背景 + }, + "error": { + "foreground": "#F44336", # 鲜明亮红色 - 错误 + "background": "#B71C1C", # 深红色背景 + }, + "success": { + "foreground": "#66BB6A", # 鲜明亮绿色 - 成功 + "background": "#1B5E20", # 深绿色背景 + }, + "info": { + "foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色) + "background": "#01579B", # 深天蓝色背景 + }, + "flow": { + "foreground": "#A1887F", # 亮棕色 - 流程操作 + "background": "#3E2723", # 深棕色背景 + }, + "operation": { + "foreground": "#78909C", # 亮蓝灰色 - 操作动作 + "background": "#263238", # 深蓝灰色背景 + }, + } + + +def apply_operation_color( + text_widget, + start_pos: str, + end_pos: str, + line: str, + theme: str = "litera" +) -> None: + """ + 为日志行应用操作类型颜色 + + Args: + text_widget: tkinter Text 组件 + start_pos: 起始位置 + end_pos: 结束位置 + line: 日志行内容 + theme: 主题名称 + """ + try: + # 识别操作类型 + op_type = get_operation_type(line) + if not op_type: + return + + # 获取颜色配置 + color_config = get_color_config(theme) + if op_type not in color_config: + return + + colors = color_config[op_type] + tag_name = f"op_{op_type}" + + # 配置标签(总是重新配置,确保主题改变时颜色也会更新) + text_widget.tag_configure( + tag_name, + foreground=colors["foreground"], + background=colors["background"], + ) + + # 应用标签 + text_widget.tag_add(tag_name, start_pos, end_pos) + except Exception: + # 忽略颜色应用失败,不影响日志显示 + pass \ No newline at end of file diff --git a/gui/components/log_color_config.py.backup b/gui/components/log_color_config.py.backup new file mode 100644 index 0000000..47cf14b --- /dev/null +++ b/gui/components/log_color_config.py.backup @@ -0,0 +1,943 @@ +""" +日志颜色配置模块 +================ + +为不同的操作类型定义颜色标签,支持明亮和暗色主题。 +""" + +from typing import Dict, Optional + + +# 操作类型关键词映射(用于识别日志中的操作类型) +OPERATION_KEYWORDS: Dict[str, list] = { + "ocr": [ + "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", + "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" + ], + "click": [ + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "返回", "确认", "关闭", "发送", "加入" + ], + "swipe": [ + "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", + "回退", "切换直播间", "切换房间" + ], + "screenshot": [ + "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" + ], + "detection": [ + "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", + "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" + ], + "decision": [ + "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", + "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" + ], + "reservation": [ + "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", + "高价值预约", "预约回退", "预约校验" + ], + "fansclub": [ + "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" + ], + "lottery": [ + "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" + ], + "stage": [ + "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", + "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" + ], + "performance": [ + "耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率" + ], + "error": [ + "错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout" + ], + "success": [ + "成功", "SUCCESS", "完成", "完成", "已", "完成" + ], + "info": [ + "信息", "INFO", "提示", "注意", "开始", "启动", "停止" + ], + "flow": [ + "流程", "flow", "处理", "执行", "运行", "完成" + ], + "operation": [ + "操作", "operation", "动作", "行为" + ] +} + + +def get_operation_type(line: str) -> Optional[str]: + """ + 根据日志行内容识别操作类型 + + 日志格式通常是: [时间] [GUI] - 操作类型 内容 + 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) + + Args: + line: 日志行内容 + + Returns: + 操作类型名称,如果无法识别则返回None + """ + line_lower = line.lower() + + # 优先级1: 识别日志内容开头的操作类型(最精确) + # 日志格式: [时间] [GUI] - 操作类型 内容 + # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 + # [GUI] - 滑动上滑切换直播间 + # [GUI] - 阶段诊断开始阶段诊断 + # [GUI] - 预约[预约]记录直播间标题 + + import re + # 提取日志内容部分(去掉时间戳和标签) + # 匹配格式: [时间] [标签] - 内容 + content_match = re.search(r'\]\s*-\s*(.+)$', line) + if content_match: + content = content_match.group(1).strip() + content_lower = content.lower() + + # 操作类型关键词映射(按优先级排序,更具体的在前) + operation_type_map = [ + # 检测相关(最具体) + ("阶段诊断", "detection"), + ("阶段检测", "detection"), + ("并行检测", "detection"), + ("像素检测", "detection"), + ("模板匹配", "detection"), + ("检测", "detection"), + # 滑动相关 + ("滑动", "swipe"), + ("上滑", "swipe"), + ("下滑", "swipe"), + ("切换直播间", "swipe"), + # 预约相关 + ("预约", "reservation"), + # OCR相关 + ("OCR", "ocr"), + ("ocr识别", "ocr"), + ("识别", "ocr"), + # 点击相关 + ("点击", "click"), + # 截图相关 + ("截图", "screenshot"), + # 流程相关 + ("流程", "flow"), + # 决策相关 + ("决策", "decision"), + ("行为识别", "decision"), + # 开奖相关 + ("开奖", "lottery"), + ("抽奖结果", "lottery"), + # 粉丝团相关 + ("粉丝团", "fansclub"), + # 操作相关(通用,放后面) + ("操作", "operation"), + # 自救相关 + ("自救", "info"), + # 错误相关 + ("错误", "error"), + ("异常", "error"), + # 成功相关 + ("成功", "success"), + # 信息相关(最通用,放最后) + ("信息", "info"), + ] + + # 检查内容开头是否匹配操作类型 + for keyword, op_type in operation_type_map: + # 检查是否在内容开头(更精确) + if content_lower.startswith(keyword.lower()): + return op_type + # 或者检查是否紧跟在 " - " 后面 + if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower: + return op_type + + # 优先级2: 使用日志标签识别(如果内容中没有匹配到) + tag_match = re.search(r'\[([^\]]+)\]', line) + if tag_match: + tag = tag_match.group(1).lower() + + # 标签到操作类型的映射(精确匹配) + tag_to_op_type = { + "阶段诊断": "detection", + "阶段检测": "detection", + "截图": "screenshot", + "ocr": "ocr", + "ocr识别": "ocr", + "点击": "click", + "滑动": "swipe", + "预约": "reservation", + "找福袋图标": "detection", + "福袋查找": "detection", + "自救": "info", + "流程": "flow", + "行为识别": "decision", + "决策": "decision", + "错误": "error", + "异常": "error", + "成功": "success", + "信息": "info", + "提示": "info", + } + + # 精确匹配标签 + if tag in tag_to_op_type: + return tag_to_op_type[tag] + + # 部分匹配标签(用于更灵活的匹配) + for tag_key, op_type in tag_to_op_type.items(): + if tag_key in tag or tag in tag_key: + return op_type + + # 优先级2: 使用关键词匹配(更具体的短语优先) + # 定义更具体的关键词短语(按优先级排序) + specific_patterns = [ + # 检测相关(更具体的短语优先) + ("阶段诊断", "detection"), + ("阶段检测", "detection"), + ("像素检测", "detection"), + ("模板匹配", "detection"), + ("并行检测", "detection"), + # OCR相关 + ("OCR识别", "ocr"), + ("OCR模式", "ocr"), + ("识别成功", "ocr"), + ("识别失败", "ocr"), + # 点击相关 + ("点击成功", "click"), + ("点击失败", "click"), + ("参与按钮", "click"), + # 滑动相关 + ("向上滑动", "swipe"), + ("向下滑动", "swipe"), + ("切换直播间", "swipe"), + # 预约相关 + ("记录预约", "reservation"), + ("预约窗口", "reservation"), + ("预约队列", "reservation"), + # 开奖相关 + ("抽奖结果", "lottery"), + ("等待开奖", "lottery"), + ("开奖时间", "lottery"), + # 粉丝团相关 + ("加入粉丝团", "fansclub"), + ("粉丝团失败", "fansclub"), + ("粉丝团成功", "fansclub"), + ] + + # 先检查更具体的短语 + for pattern, op_type in specific_patterns: + if pattern.lower() in line_lower: + return op_type + + # 优先级3: 使用通用关键词匹配(按操作类型优先级) + # 调整顺序,让更具体的操作类型优先 + priority_order = [ + "lottery", # 开奖相关(更具体) + "fansclub", # 粉丝团(更具体) + "reservation", # 预约(更具体) + "decision", # 决策(更具体) + "detection", # 检测(较具体) + "ocr", # OCR(较具体) + "click", # 点击(较具体) + "swipe", # 滑动(较具体) + "flow", # 流程(较具体) + "operation", # 操作(较具体) + "screenshot", # 截图(较通用,放后面) + "stage", # 阶段(较通用) + "performance", # 性能(较通用) + "error", # 错误(较通用) + "success", # 成功(较通用) + "info", # 信息(最通用,放最后) + ] + + # 按优先级顺序检查 + for op_type in priority_order: + if op_type in OPERATION_KEYWORDS: + for keyword in OPERATION_KEYWORDS[op_type]: + # 避免过于宽泛的关键词误匹配 + if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]: + # 这些关键词太宽泛,只在特定上下文中使用 + # 检查是否在更具体的上下文中 + if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line): + return op_type + elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower): + return op_type + elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower): + return op_type + # 其他宽泛关键词跳过,避免误匹配 + continue + + if keyword.lower() in line_lower: + return op_type + + return None + + +def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: + """ + 获取颜色配置(根据主题) + + Args: + theme: 主题名称("litera", "darkly" 等) + + Returns: + 颜色配置字典,包含每种操作类型的颜色设置 + """ + light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} + is_light = theme.lower() in light_themes + + if is_light: + # 明亮主题颜色配置(深色文字,与白色背景对比,高区分度) + return { + "ocr": { + "foreground": "#0052CC", # 鲜明蓝色 - OCR识别 + "background": "#D6E8FF", # 浅蓝色背景 + }, + "click": { + "foreground": "#D32F2F", # 鲜明红色 - 点击操作 + "background": "#FFE0E0", # 浅红色背景 + }, + "swipe": { + "foreground": "#2E7D32", # 鲜明绿色 - 滑动操作 + "background": "#E0F2E8", # 浅绿色背景 + }, + "screenshot": { + "foreground": "#7B1FA2", # 鲜明紫色 - 截图操作 + "background": "#F3E5F5", # 浅紫色背景 + }, + "detection": { + "foreground": "#F57C00", # 鲜明橙色 - 检测操作 + "background": "#FFF3E0", # 浅橙色背景 + }, + "decision": { + "foreground": "#C2185B", # 鲜明品红色 - 决策操作 + "background": "#FCE4EC", # 浅品红色背景 + }, + "reservation": { + "foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色) + "background": "#E0F2F1", # 浅青色背景 + }, + "fansclub": { + "foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色) + "background": "#F3E5F5", # 浅紫红色背景 + }, + "lottery": { + "foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色) + "background": "#FFEBEE", # 浅橙红色背景 + }, + "stage": { + "foreground": "#616161", # 深灰色 - 阶段信息 + "background": "#F5F5F5", # 浅灰色背景 + }, + "performance": { + "foreground": "#00796B", # 鲜明青绿色 - 性能信息 + "background": "#E0F2F1", # 浅青绿色背景 + }, + "error": { + "foreground": "#C62828", # 鲜明深红色 - 错误 + "background": "#FFCDD2", # 浅红色背景 + }, + "success": { + "foreground": "#2E7D32", # 鲜明深绿色 - 成功 + "background": "#C8E6C9", # 浅绿色背景 + }, + "info": { + "foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色) + "background": "#BBDEFB", # 浅天蓝色背景 + }, + "flow": { + "foreground": "#5D4037", # 深棕色 - 流程操作 + "background": "#EFEBE9", # 浅棕色背景 + }, + "operation": { + "foreground": "#455A64", # 深蓝灰色 - 操作动作 + "background": "#ECEFF1", # 浅蓝灰色背景 + }, + } + else: + # 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度) + return { + "ocr": { + "foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别 + "background": "#0D47A1", # 深蓝色背景 + }, + "click": { + "foreground": "#EF5350", # 鲜明亮红色 - 点击操作 + "background": "#B71C1C", # 深红色背景 + }, + "swipe": { + "foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作 + "background": "#1B5E20", # 深绿色背景 + }, + "screenshot": { + "foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作 + "background": "#4A148C", # 深紫色背景 + }, + "detection": { + "foreground": "#FFA726", # 鲜明亮橙色 - 检测操作 + "background": "#E65100", # 深橙色背景 + }, + "decision": { + "foreground": "#EC407A", # 鲜明亮品红色 - 决策操作 + "background": "#880E4F", # 深品红色背景 + }, + "reservation": { + "foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色) + "background": "#004D40", # 深青色背景 + }, + "fansclub": { + "foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色) + "background": "#4A148C", # 深紫红色背景 + }, + "lottery": { + "foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色) + "background": "#BF360C", # 深橙红色背景 + }, + "stage": { + "foreground": "#90A4AE", # 亮灰色 - 阶段信息 + "background": "#263238", # 深灰色背景 + }, + "performance": { + "foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息 + "background": "#004D40", # 深青绿色背景 + }, + "error": { + "foreground": "#F44336", # 鲜明亮红色 - 错误 + "background": "#B71C1C", # 深红色背景 + }, + "success": { + "foreground": "#66BB6A", # 鲜明亮绿色 - 成功 + "background": "#1B5E20", # 深绿色背景 + }, + "info": { + "foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色) + "background": "#01579B", # 深天蓝色背景 + }, + "flow": { + "foreground": "#A1887F", # 亮棕色 - 流程操作 + "background": "#3E2723", # 深棕色背景 + }, + "operation": { + "foreground": "#78909C", # 亮蓝灰色 - 操作动作 + "background": "#263238", # 深蓝灰色背景 + }, + } + + +def apply_operation_color( + text_widget, + start_pos: str, + end_pos: str, + line: str, + theme: str = "litera" +) -> None: + """ + 为日志行应用操作类型颜色 + + Args: + text_widget: tkinter Text 组件 + start_pos: 起始位置 + end_pos: 结束位置 + line: 日志行内容 + theme: 主题名称 + """ + try: + # 识别操作类型 + op_type = get_operation_type(line) + if not op_type: + return + + # 获取颜色配置 + color_config = get_color_config(theme) + if op_type not in color_config: + return + + colors = color_config[op_type] + tag_name = f"op_{op_type}" + + # 配置标签(总是重新配置,确保主题改变时颜色也会更新) + text_widget.tag_configure( + tag_name, + foreground=colors["foreground"], + background=colors["background"], + ) + + # 应用标签 + text_widget.tag_add(tag_name, start_pos, end_pos) + except Exception: + # 忽略颜色应用失败,不影响日志显示 + pass + + +""" +为不同的操作类型定义颜色标签,支持明亮和暗色主题。 +""" + +from typing import Dict, Optional + + +# 操作类型关键词映射(用于识别日志中的操作类型) +OPERATION_KEYWORDS: Dict[str, list] = { + "ocr": [ + "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", + "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" + ], + "click": [ + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "返回", "确认", "关闭", "发送", "加入" + ], + "swipe": [ + "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", + "回退", "切换直播间", "切换房间" + ], + "screenshot": [ + "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" + ], + "detection": [ + "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", + "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" + ], + "decision": [ + "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", + "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" + ], + "reservation": [ + "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", + "高价值预约", "预约回退", "预约校验" + ], + "fansclub": [ + "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" + ], + "lottery": [ + "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" + ], + "stage": [ + "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", + "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" + ], + "performance": [ + "耗时", "elapsed_seconds", "性能", "时间", "秒", "毫秒", "效率" + ], + "error": [ + "错误", "ERROR", "失败", "异常", "Exception", "失败", "超时", "timeout" + ], + "success": [ + "成功", "SUCCESS", "完成", "完成", "已", "完成" + ], + "info": [ + "信息", "INFO", "提示", "注意", "开始", "启动", "停止" + ], + "flow": [ + "流程", "flow", "处理", "执行", "运行", "完成" + ], + "operation": [ + "操作", "operation", "动作", "行为" + ] +} + + +def get_operation_type(line: str) -> Optional[str]: + """ + 根据日志行内容识别操作类型 + + 日志格式通常是: [时间] [GUI] - 操作类型 内容 + 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) + + Args: + line: 日志行内容 + + Returns: + 操作类型名称,如果无法识别则返回None + """ + line_lower = line.lower() + + # 优先级1: 识别日志内容开头的操作类型(最精确) + # 日志格式: [时间] [GUI] - 操作类型 内容 + # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 + # [GUI] - 滑动上滑切换直播间 + # [GUI] - 阶段诊断开始阶段诊断 + # [GUI] - 预约[预约]记录直播间标题 + + import re + # 提取日志内容部分(去掉时间戳和标签) + # 匹配格式: [时间] [标签] - 内容 + content_match = re.search(r'\]\s*-\s*(.+)$', line) + if content_match: + content = content_match.group(1).strip() + content_lower = content.lower() + + # 操作类型关键词映射(按优先级排序,更具体的在前) + operation_type_map = [ + # 检测相关(最具体) + ("阶段诊断", "detection"), + ("阶段检测", "detection"), + ("并行检测", "detection"), + ("像素检测", "detection"), + ("模板匹配", "detection"), + ("检测", "detection"), + # 滑动相关 + ("滑动", "swipe"), + ("上滑", "swipe"), + ("下滑", "swipe"), + ("切换直播间", "swipe"), + # 预约相关 + ("预约", "reservation"), + # OCR相关 + ("OCR", "ocr"), + ("ocr识别", "ocr"), + ("识别", "ocr"), + # 点击相关 + ("点击", "click"), + # 截图相关 + ("截图", "screenshot"), + # 流程相关 + ("流程", "flow"), + # 决策相关 + ("决策", "decision"), + ("行为识别", "decision"), + # 开奖相关 + ("开奖", "lottery"), + ("抽奖结果", "lottery"), + # 粉丝团相关 + ("粉丝团", "fansclub"), + # 操作相关(通用,放后面) + ("操作", "operation"), + # 自救相关 + ("自救", "info"), + # 错误相关 + ("错误", "error"), + ("异常", "error"), + # 成功相关 + ("成功", "success"), + # 信息相关(最通用,放最后) + ("信息", "info"), + ] + + # 检查内容开头是否匹配操作类型 + for keyword, op_type in operation_type_map: + # 检查是否在内容开头(更精确) + if content_lower.startswith(keyword.lower()): + return op_type + # 或者检查是否紧跟在 " - " 后面 + if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower: + return op_type + + # 优先级2: 使用日志标签识别(如果内容中没有匹配到) + tag_match = re.search(r'\[([^\]]+)\]', line) + if tag_match: + tag = tag_match.group(1).lower() + + # 标签到操作类型的映射(精确匹配) + tag_to_op_type = { + "阶段诊断": "detection", + "阶段检测": "detection", + "截图": "screenshot", + "ocr": "ocr", + "ocr识别": "ocr", + "点击": "click", + "滑动": "swipe", + "预约": "reservation", + "找福袋图标": "detection", + "福袋查找": "detection", + "自救": "info", + "流程": "flow", + "行为识别": "decision", + "决策": "decision", + "错误": "error", + "异常": "error", + "成功": "success", + "信息": "info", + "提示": "info", + } + + # 精确匹配标签 + if tag in tag_to_op_type: + return tag_to_op_type[tag] + + # 部分匹配标签(用于更灵活的匹配) + for tag_key, op_type in tag_to_op_type.items(): + if tag_key in tag or tag in tag_key: + return op_type + + # 优先级2: 使用关键词匹配(更具体的短语优先) + # 定义更具体的关键词短语(按优先级排序) + specific_patterns = [ + # 检测相关(更具体的短语优先) + ("阶段诊断", "detection"), + ("阶段检测", "detection"), + ("像素检测", "detection"), + ("模板匹配", "detection"), + ("并行检测", "detection"), + # OCR相关 + ("OCR识别", "ocr"), + ("OCR模式", "ocr"), + ("识别成功", "ocr"), + ("识别失败", "ocr"), + # 点击相关 + ("点击成功", "click"), + ("点击失败", "click"), + ("参与按钮", "click"), + # 滑动相关 + ("向上滑动", "swipe"), + ("向下滑动", "swipe"), + ("切换直播间", "swipe"), + # 预约相关 + ("记录预约", "reservation"), + ("预约窗口", "reservation"), + ("预约队列", "reservation"), + # 开奖相关 + ("抽奖结果", "lottery"), + ("等待开奖", "lottery"), + ("开奖时间", "lottery"), + # 粉丝团相关 + ("加入粉丝团", "fansclub"), + ("粉丝团失败", "fansclub"), + ("粉丝团成功", "fansclub"), + ] + + # 先检查更具体的短语 + for pattern, op_type in specific_patterns: + if pattern.lower() in line_lower: + return op_type + + # 优先级3: 使用通用关键词匹配(按操作类型优先级) + # 调整顺序,让更具体的操作类型优先 + priority_order = [ + "lottery", # 开奖相关(更具体) + "fansclub", # 粉丝团(更具体) + "reservation", # 预约(更具体) + "decision", # 决策(更具体) + "detection", # 检测(较具体) + "ocr", # OCR(较具体) + "click", # 点击(较具体) + "swipe", # 滑动(较具体) + "flow", # 流程(较具体) + "operation", # 操作(较具体) + "screenshot", # 截图(较通用,放后面) + "stage", # 阶段(较通用) + "performance", # 性能(较通用) + "error", # 错误(较通用) + "success", # 成功(较通用) + "info", # 信息(最通用,放最后) + ] + + # 按优先级顺序检查 + for op_type in priority_order: + if op_type in OPERATION_KEYWORDS: + for keyword in OPERATION_KEYWORDS[op_type]: + # 避免过于宽泛的关键词误匹配 + if keyword.lower() in ["截图", "检测", "识别", "成功", "完成", "失败", "错误"]: + # 这些关键词太宽泛,只在特定上下文中使用 + # 检查是否在更具体的上下文中 + if keyword.lower() == "截图" and ("截图成功" in line_lower or "截图失败" in line_lower or "[截图]" in line): + return op_type + elif keyword.lower() == "检测" and ("阶段检测" in line_lower or "像素检测" in line_lower or "并行检测" in line_lower): + return op_type + elif keyword.lower() == "识别" and ("OCR识别" in line_lower or "识别成功" in line_lower or "识别失败" in line_lower): + return op_type + # 其他宽泛关键词跳过,避免误匹配 + continue + + if keyword.lower() in line_lower: + return op_type + + return None + + +def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: + """ + 获取颜色配置(根据主题) + + Args: + theme: 主题名称("litera", "darkly" 等) + + Returns: + 颜色配置字典,包含每种操作类型的颜色设置 + """ + light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} + is_light = theme.lower() in light_themes + + if is_light: + # 明亮主题颜色配置(深色文字,与白色背景对比,高区分度) + return { + "ocr": { + "foreground": "#0052CC", # 鲜明蓝色 - OCR识别 + "background": "#D6E8FF", # 浅蓝色背景 + }, + "click": { + "foreground": "#D32F2F", # 鲜明红色 - 点击操作 + "background": "#FFE0E0", # 浅红色背景 + }, + "swipe": { + "foreground": "#2E7D32", # 鲜明绿色 - 滑动操作 + "background": "#E0F2E8", # 浅绿色背景 + }, + "screenshot": { + "foreground": "#7B1FA2", # 鲜明紫色 - 截图操作 + "background": "#F3E5F5", # 浅紫色背景 + }, + "detection": { + "foreground": "#F57C00", # 鲜明橙色 - 检测操作 + "background": "#FFF3E0", # 浅橙色背景 + }, + "decision": { + "foreground": "#C2185B", # 鲜明品红色 - 决策操作 + "background": "#FCE4EC", # 浅品红色背景 + }, + "reservation": { + "foreground": "#00897B", # 鲜明青色 - 预约操作(区别于OCR蓝色) + "background": "#E0F2F1", # 浅青色背景 + }, + "fansclub": { + "foreground": "#8E24AA", # 鲜明紫红色 - 粉丝团操作(区别于截图紫色) + "background": "#F3E5F5", # 浅紫红色背景 + }, + "lottery": { + "foreground": "#E64A19", # 鲜明橙红色 - 开奖相关(区别于点击红色) + "background": "#FFEBEE", # 浅橙红色背景 + }, + "stage": { + "foreground": "#616161", # 深灰色 - 阶段信息 + "background": "#F5F5F5", # 浅灰色背景 + }, + "performance": { + "foreground": "#00796B", # 鲜明青绿色 - 性能信息 + "background": "#E0F2F1", # 浅青绿色背景 + }, + "error": { + "foreground": "#C62828", # 鲜明深红色 - 错误 + "background": "#FFCDD2", # 浅红色背景 + }, + "success": { + "foreground": "#2E7D32", # 鲜明深绿色 - 成功 + "background": "#C8E6C9", # 浅绿色背景 + }, + "info": { + "foreground": "#0277BD", # 鲜明天蓝色 - 信息(区别于OCR深蓝色) + "background": "#BBDEFB", # 浅天蓝色背景 + }, + "flow": { + "foreground": "#5D4037", # 深棕色 - 流程操作 + "background": "#EFEBE9", # 浅棕色背景 + }, + "operation": { + "foreground": "#455A64", # 深蓝灰色 - 操作动作 + "background": "#ECEFF1", # 浅蓝灰色背景 + }, + } + else: + # 暗色主题颜色配置(亮色文字,与深色背景对比,高区分度) + return { + "ocr": { + "foreground": "#42A5F5", # 鲜明亮蓝色 - OCR识别 + "background": "#0D47A1", # 深蓝色背景 + }, + "click": { + "foreground": "#EF5350", # 鲜明亮红色 - 点击操作 + "background": "#B71C1C", # 深红色背景 + }, + "swipe": { + "foreground": "#66BB6A", # 鲜明亮绿色 - 滑动操作 + "background": "#1B5E20", # 深绿色背景 + }, + "screenshot": { + "foreground": "#AB47BC", # 鲜明亮紫色 - 截图操作 + "background": "#4A148C", # 深紫色背景 + }, + "detection": { + "foreground": "#FFA726", # 鲜明亮橙色 - 检测操作 + "background": "#E65100", # 深橙色背景 + }, + "decision": { + "foreground": "#EC407A", # 鲜明亮品红色 - 决策操作 + "background": "#880E4F", # 深品红色背景 + }, + "reservation": { + "foreground": "#26A69A", # 鲜明亮青色 - 预约操作(区别于OCR蓝色) + "background": "#004D40", # 深青色背景 + }, + "fansclub": { + "foreground": "#BA68C8", # 鲜明亮紫红色 - 粉丝团操作(区别于截图紫色) + "background": "#4A148C", # 深紫红色背景 + }, + "lottery": { + "foreground": "#FF7043", # 鲜明亮橙红色 - 开奖相关(区别于点击红色) + "background": "#BF360C", # 深橙红色背景 + }, + "stage": { + "foreground": "#90A4AE", # 亮灰色 - 阶段信息 + "background": "#263238", # 深灰色背景 + }, + "performance": { + "foreground": "#26A69A", # 鲜明亮青绿色 - 性能信息 + "background": "#004D40", # 深青绿色背景 + }, + "error": { + "foreground": "#F44336", # 鲜明亮红色 - 错误 + "background": "#B71C1C", # 深红色背景 + }, + "success": { + "foreground": "#66BB6A", # 鲜明亮绿色 - 成功 + "background": "#1B5E20", # 深绿色背景 + }, + "info": { + "foreground": "#29B6F6", # 鲜明亮天蓝色 - 信息(区别于OCR深蓝色) + "background": "#01579B", # 深天蓝色背景 + }, + "flow": { + "foreground": "#A1887F", # 亮棕色 - 流程操作 + "background": "#3E2723", # 深棕色背景 + }, + "operation": { + "foreground": "#78909C", # 亮蓝灰色 - 操作动作 + "background": "#263238", # 深蓝灰色背景 + }, + } + + +def apply_operation_color( + text_widget, + start_pos: str, + end_pos: str, + line: str, + theme: str = "litera" +) -> None: + """ + 为日志行应用操作类型颜色 + + Args: + text_widget: tkinter Text 组件 + start_pos: 起始位置 + end_pos: 结束位置 + line: 日志行内容 + theme: 主题名称 + """ + try: + # 识别操作类型 + op_type = get_operation_type(line) + if not op_type: + return + + # 获取颜色配置 + color_config = get_color_config(theme) + if op_type not in color_config: + return + + colors = color_config[op_type] + tag_name = f"op_{op_type}" + + # 配置标签(总是重新配置,确保主题改变时颜色也会更新) + text_widget.tag_configure( + tag_name, + foreground=colors["foreground"], + background=colors["background"], + ) + + # 应用标签 + text_widget.tag_add(tag_name, start_pos, end_pos) + except Exception: + # 忽略颜色应用失败,不影响日志显示 + pass \ No newline at end of file diff --git a/gui/components/log_color_config_fixed.py b/gui/components/log_color_config_fixed.py new file mode 100644 index 0000000..7fd861b --- /dev/null +++ b/gui/components/log_color_config_fixed.py @@ -0,0 +1,200 @@ +""" +日志颜色配置模块 +================ + +为不同的操作类型定义颜色标签,支持明亮和暗色主题。 +""" + +from typing import Dict, Optional + + +# 操作类型关键词映射(用于识别日志中的操作类型) +OPERATION_KEYWORDS: Dict[str, list] = { + "ocr": [ + "OCR", "ocr", "识别", "读取", "analyse_pic_word", "识别成功", "识别失败", + "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" + ], + "click": [ + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "返回", "确认", "关闭", "发送", "加入" + ], + "swipe": [ + "滑动", "swipe", "向上滑动", "向下滑动", "向左滑动", "向右滑动", + "回退", "切换直播间", "切换房间" + ], + "screenshot": [ + "截图", "screenshot", "get_screenshot", "保存截图", "截图成功", "截图失败" + ], + "detection": [ + "检测", "detect", "阶段检测", "阶段诊断", "像素检测", "模板匹配", + "检测成功", "检测失败", "匹配成功", "匹配失败", "识别到", "未识别到" + ], + "decision": [ + "决策", "判断", "决定", "选择", "跳过", "参与", "不参与", "筛选", + "价值过低", "人数过少", "人数过多", "倒计时", "内容不符合" + ], + "reservation": [ + "预约", "reservation", "记录预约", "回退到预约", "预约窗口", "预约队列", + "高价值预约", "预约回退", "预约校验" + ], + "fansclub": [ + "粉丝团", "fansclub", "加入粉丝团", "粉丝团失败", "粉丝团成功" + ], + "lottery": [ + "开奖", "lottery", "中奖", "未中奖", "抽奖结果", "等待开奖", "开奖时间" + ], + "stage": [ + "阶段", "stage", "IN_LIVE_ROOM", "FUDai_DETAIL", "RECOMMEND_PAGE", + "LIVE_OR_UNKNOWN", "阶段变化", "阶段流转" + ], + "performance": [ + "性能", "耗时", "time", "duration", "elapsed", "ms", "毫秒", "秒", + "执行时间", "处理时间", "检测时间" + ], + "error": [ + "错误", "error", "exception", "失败", "fail", "timeout", "超时", + "异常", "崩溃", "中断", "连接失败" + ], + "info": [ + "信息", "info", "开始", "完成", "初始化", "启动", "停止", + "日志", "debug", "调试" + ], + "network": [ + "网络", "network", "连接", "请求", "响应", "http", "api", + "服务器", "接口", "上传", "下载" + ] +} + + +def get_operation_type(line: str) -> Optional[str]: + """ + 根据日志行内容识别操作类型 + + 日志格式通常是: [时间] [GUI] - 操作类型 内容 + 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) + + Args: + line: 日志行内容 + + Returns: + 操作类型名称,如果无法识别则返回None + """ + line_lower = line.lower() + + # 优先级1: 识别日志内容开头的操作类型(最精确) + # 日志格式: [时间] [GUI] - 操作类型 内容 + # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 + if "[gui] -" in line_lower: + parts = line_lower.split("[gui] -") + if len(parts) > 1: + content = parts[1].strip() + # 提取操作类型(第一个词) + first_word = content.split()[0] if content.split() else "" + if first_word in ["流程", "滑动", "阶段诊断", "预约", "截图", "点击", "识别", "检测"]: + return first_word + + # 优先级2: 关键词匹配(更全面的识别) + for operation_type, keywords in OPERATION_KEYWORDS.items(): + for keyword in keywords: + if keyword.lower() in line_lower: + return operation_type + + return None + + +def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: + """ + 根据主题获取颜色配置 + + Args: + theme: 主题名称,如 'litera'(明亮), 'darkly'(暗色), 'cyborg'(深色) + + Returns: + 颜色配置字典,包含各操作类型的颜色设置 + """ + # 基础颜色配置 + if theme in ["litera", "minty", "pulse", "solar", "united", "yeti"]: + # 明亮主题 + base_config = { + "ocr": {"foreground": "#2E8B57", "background": "#F0FFF0"}, # 绿色 + "click": {"foreground": "#4169E1", "background": "#F0F8FF"}, # 蓝色 + "swipe": {"foreground": "#FF6347", "background": "#FFF5EE"}, # 红色 + "screenshot": {"foreground": "#8B4513", "background": "#FFF8DC"}, # 棕色 + "detection": {"foreground": "#9932CC", "background": "#F8F8FF"}, # 紫色 + "decision": {"foreground": "#FF8C00", "background": "#FFFACD"}, # 橙色 + "reservation": {"foreground": "#20B2AA", "background": "#F0FFFF"}, # 青色 + "fansclub": {"foreground": "#DC143C", "background": "#FFE4E1"}, # 粉红 + "lottery": {"foreground": "#FFD700", "background": "#FFFFE0"}, # 金色 + "stage": {"foreground": "#8B008B", "background": "#F0F0F0"}, # 深紫 + "performance": {"foreground": "#696969", "background": "#F5F5F5"}, # 灰色 + "error": {"foreground": "#B22222", "background": "#FFE4E1"}, # 深红 + "info": {"foreground": "#000000", "background": "#FFFFFF"}, # 黑色 + "network": {"foreground": "#4682B4", "background": "#F0F8FF"} # 钢蓝 + } + else: + # 暗色主题 + base_config = { + "ocr": {"foreground": "#98FB98", "background": "#2F4F2F"}, # 亮绿 + "click": {"foreground": "#87CEEB", "background": "#191970"}, # 亮蓝 + "swipe": {"foreground": "#FFA07A", "background": "#8B0000"}, # 亮红 + "screenshot": {"foreground": "#F4A460", "background": "#8B4513"}, # 沙色 + "detection": {"foreground": "#DDA0DD", "background": "#4B0082"}, # 梅红 + "decision": {"foreground": "#FFDAB9", "background": "#FF8C00"}, # 桃色 + "reservation": {"foreground": "#AFEEEE", "background": "#008B8B"}, # 淡青 + "fansclub": {"foreground": "#FFB6C1", "background": "#8B0000"}, # 浅粉 + "lottery": {"foreground": "#FFFF00", "background": "#FFD700"}, # 亮黄 + "stage": {"foreground": "#DDA0DD", "background": "#2F2F2F"}, # 梅红 + "performance": {"foreground": "#D3D3D3", "background": "#696969"}, # 浅灰 + "error": {"foreground": "#FFA07A", "background": "#B22222"}, # 亮红 + "info": {"foreground": "#FFFFFF", "background": "#000000"}, # 白色 + "network": {"foreground": "#87CEEB", "background": "#4682B4"} # 亮蓝 + } + + return base_config + + +def apply_operation_color( + text_widget, + start_pos: str, + end_pos: str, + operation_type: Optional[str], + theme: str = "litera" +) -> None: + """ + 为日志文本中的指定范围应用操作类型颜色标签 + + Args: + text_widget: Tkinter文本控件 + start_pos: 开始位置(如 "1.0") + end_pos: 结束位置(如 "1.end") + operation_type: 操作类型(None表示不应用颜色) + theme: 主题名称 + """ + try: + if operation_type is None: + return + + # 获取颜色配置 + color_config = get_color_config(theme) + colors = color_config.get(operation_type) + + if colors is None: + return + + # 创建唯一标签名 + tag_name = f"operation_{operation_type}" + + # 配置标签(总是重新配置,确保主题改变时颜色也会更新) + text_widget.tag_configure( + tag_name, + foreground=colors["foreground"], + background=colors["background"], + ) + + # 应用标签 + text_widget.tag_add(tag_name, start_pos, end_pos) + except Exception: + # 忽略颜色应用失败,不影响日志显示 + pass + + diff --git a/gui/components/log_viewer.py b/gui/components/log_viewer.py index 6a19881..58a620f 100644 --- a/gui/components/log_viewer.py +++ b/gui/components/log_viewer.py @@ -6,7 +6,7 @@ from __future__ import annotations -from typing import Any, Callable, Optional, List, Dict +from typing import Any, Callable, Optional, List, Dict, Tuple import queue import re import threading @@ -44,7 +44,7 @@ except ImportError: class EnhancedLogViewer(ttk.Frame): """增强的日志查看器组件""" - def __init__(self, parent: Any, log_queue: "queue.Queue[str]" = None): + def __init__(self, parent: Any, log_queue: Optional[queue.Queue] = None): super().__init__(parent) # 初始化数据 @@ -372,9 +372,9 @@ def format_gui_log_line(line: str) -> str: def create_log_viewer( parent: Any, - log_queue: "queue.Queue[str]", + log_queue: Optional[queue.Queue], on_line: Callable[[str], None] -) -> tuple[ScrolledText, Callable[[], None]]: +) -> Any: """创建日志查看器组件(兼容旧接口)。 参数: diff --git a/gui/components/main_window.py b/gui/components/main_window.py index 5e3a26f..7014fb1 100644 --- a/gui/components/main_window.py +++ b/gui/components/main_window.py @@ -49,3 +49,25 @@ def create_main_window( + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/components/ocr_panel.py b/gui/components/ocr_panel.py index 3683e34..a43ee70 100644 --- a/gui/components/ocr_panel.py +++ b/gui/components/ocr_panel.py @@ -50,3 +50,25 @@ def create_ocr_panel( + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/gui_app.py b/gui/gui_app.py index 2a73a85..9e1d3a2 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -27,6 +27,22 @@ from gui.gui_core import ( ) from path_config import get_logs_dir +# 导入日志颜色配置模块 +try: + from gui.components.log_color_config import ( + get_color_config, + apply_operation_color, + get_operation_type, + ) +except ImportError: + # 如果模块不存在,使用空函数作为回退 + def get_color_config(theme: str = "litera"): + return {} + def apply_operation_color(*args, **kwargs): + pass + def get_operation_type(line: str) -> str | None: + return None + # 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告) warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning) warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning) @@ -1087,7 +1103,7 @@ def main(): row4c = ttk.Frame(fudai_find_box) row4c.pack(fill=X, padx=10, pady=(0, 10)) - ttk.Label(row4c, text="直播间检测阈值:").pack(side=LEFT) + ttk.Label(row4c, text="直播间检测阈值(白色像素比例):").pack(side=LEFT) ttk.Spinbox( row4c, from_=0.0, @@ -1096,7 +1112,7 @@ def main(): textvariable=live_room_match_threshold_var, width=6, ).pack(side=LEFT) - ttk.Label(row4c, text="(0.0~1.0,默认0.7,值越高越严格)").pack( + ttk.Label(row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)").pack( side=LEFT, padx=(6, 0) ) @@ -1623,7 +1639,7 @@ def main(): cfg2["stage_diag_max_step_time"] = float( stage_diag_max_step_time_var.get() or 2.0 ) - cfg2["enable_ocr_mode1"] = bool(enable_ocr_mode1_var.get()) + cfg2["enable_ocr_mode1"] = bool(cfg.get("enable_ocr_mode1", False)) cfg2["fudai_template_match_enabled"] = bool( fudai_template_match_enabled_var.get() ) @@ -1941,6 +1957,7 @@ def main(): high_value_tab = ttk.Frame(notebook) actions_log_tab = ttk.Frame(notebook) ocr_results_tab = ttk.Frame(notebook) + win_record_tab = ttk.Frame(notebook) notebook.add(log_tab, text="运行日志") notebook.add(preview_tab, text="截图预览") notebook.add(stats_tab, text="统计信息") @@ -1948,6 +1965,7 @@ def main(): notebook.add(high_value_tab, text="高价值房间") notebook.add(actions_log_tab, text="行为日志") notebook.add(ocr_results_tab, text="OCR结果") + notebook.add(win_record_tab, text="中奖记录") # 日志区 log_box = ttk.Frame(log_tab) @@ -2100,6 +2118,19 @@ def main(): log_text.tag_configure("log_critical", foreground="#F44336", font=("Consolas", 10, "bold")) # 加粗亮红色 log_text.tag_configure("log_performance", foreground="#81C784") # 亮绿色,性能数据 log_text.tag_configure("log_module", foreground="#BA68C8") # 亮紫色,模块标识 + + # 配置操作类型颜色标签(使用模块化配置) + try: + color_config = get_color_config(current_theme) + for op_type, colors in color_config.items(): + tag_name = f"op_{op_type}" + log_text.tag_configure( + tag_name, + foreground=colors["foreground"], + background=colors["background"], + ) + except Exception: + pass # 忽略操作类型颜色配置失败 except Exception: pass # 忽略标签配置失败 @@ -2273,7 +2304,6 @@ def main(): 0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5) ) return RunParams( - enable_ocr_mode1=bool(enable_ocr_mode1_var.get()), device_id=device_var.get().strip(), y_pianyi=int(y_var.get()), needswitch=bool(needswitch_var.get()), @@ -2287,26 +2317,15 @@ def main(): auto_join_fansclub=bool(auto_join_var.get()), fansclub_fail_action=str(fansclub_action_var.get() or "stay").lower(), # Web端新增参数 - high_value_room_revisit_enabled=bool( - high_value_room_revisit_enabled_var.get() - ), - high_value_room_revisit_only_current_run=bool( - high_value_room_revisit_only_current_run_var.get() - ), - reservation_back_verify_enabled=bool( - reservation_back_verify_enabled_var.get() - ), - reservation_back_swipe_delay=float( - reservation_back_swipe_delay_var.get() or 0 - ), - reservation_preempt_min_value=float( - reservation_preempt_min_value_var.get() or 0 - ), - fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0), + high_value_room_revisit_enabled=bool(high_value_room_revisit_enabled_var.get()), + high_value_room_revisit_only_current_run=bool(high_value_room_revisit_only_current_run_var.get()), + reservation_back_verify_enabled=bool(reservation_back_verify_enabled_var.get()), + reservation_back_swipe_delay=float(reservation_back_swipe_delay_var.get() or 1.0), + reservation_preempt_min_value=float(reservation_preempt_min_value_var.get() or 1000), + fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 5), + enable_ocr_mode1=bool(enable_ocr_mode1_var.get()), fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()), - fudai_template_match_threshold=float( - fudai_template_match_threshold_var.get() or 0.7 - ), + fudai_template_match_threshold=float(fudai_template_match_threshold_var.get() or 0.7), ) def start_run(): @@ -2354,57 +2373,7 @@ def main(): side=LEFT, padx=(0, 8) ) - ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3) - test_seconds_var = tk.IntVar( - value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60) - ) - ttk.Label(actions, text="测试养号(秒):").pack(side=LEFT) - ttk.Spinbox( - actions, from_=10, to=3600, increment=10, textvariable=test_seconds_var, width=8 - ).pack(side=LEFT, padx=(0, 8)) - - def start_test_yanghao(): - if runner.is_running(): - on_line("[运行] 已在运行中") - return - save_ui_to_config() - secs = int(test_seconds_var.get() or 90) - dev = device_var.get().strip() - on_line(f"[测试] 启动养号流程:device={dev or '(auto)'} seconds={secs}") - status_var.set("运行中") - try: - runner.start_test_yanghao_flow(dev, secs) - except Exception as e: - status_var.set("启动失败") - on_line(f"[错误] {e}") - - ttk.Button(actions, text="测试养号流程", command=start_test_yanghao).pack(side=LEFT) - - ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3) - test_comment_var = tk.StringVar(value="测试评论") - ttk.Label(actions, text="测试评论:").pack(side=LEFT) - ttk.Entry(actions, textvariable=test_comment_var, width=12).pack( - side=LEFT, padx=(0, 8) - ) - - def start_test_comment(): - if runner.is_running(): - on_line("[运行] 已在运行中") - return - save_ui_to_config() - text = test_comment_var.get().strip() - dev = device_var.get().strip() - on_line(f"[测试] 启动评论测试:device={dev or '(auto)'} text={text}") - status_var.set("运行中") - try: - runner.start_test_comment(dev, text) - except Exception as e: - status_var.set("启动失败") - on_line(f"[错误] {e}") - - ttk.Button(actions, text="测试评论", command=start_test_comment).pack(side=LEFT) - - ttk.Separator(actions, orient="vertical").pack(side=LEFT, fill=Y, padx=10, pady=3) + # (已移除:测试养号/测试评论 按钮与相关UI) def send_back_key(): dev = device_var.get().strip() @@ -2422,37 +2391,56 @@ def main(): def pump_logs(): changed = False try: + # 获取当前主题(用于颜色配置) + try: + current_theme = str(gui_theme_var.get() or "litera") + except Exception: + current_theme = "litera" + while True: line = q.get_nowait() try: # 插入日志行并应用颜色标签 start_pos = log_text.index("end-1c") - # 检查是否需要应用颜色标签 - tag = None - if "[INFO]" in line: - tag = "log_info" - elif "[WARNING]" in line: - tag = "log_warning" - elif "[ERROR]" in line: - tag = "log_error" - elif "[CRITICAL]" in line: - tag = "log_critical" - elif "elapsed_seconds=" in line or "耗时" in line: - tag = "log_performance" - elif re.search(r'\[[\w\.]+\]', line): - tag = "log_module" - # 插入文本 log_text.insert("end", line + "\n") + end_pos = log_text.index("end-1c") - # 如果有标签,应用到这一行 - if tag: - end_pos = log_text.index("end-1c") + # 优先级1: 先检查操作类型颜色(更具体) + op_type_applied = False + try: + op_type = get_operation_type(line) + if op_type: + apply_operation_color( + log_text, start_pos, end_pos, line, current_theme + ) + op_type_applied = True + except Exception: + pass # 忽略操作类型颜色应用失败 + + # 优先级2: 再检查日志级别标签(作为补充,如果操作类型未匹配) + # 只有在没有操作类型颜色时才应用级别标签 + if not op_type_applied: try: - log_text.tag_add(tag, start_pos, end_pos) + tag = None + if "[INFO]" in line: + tag = "log_info" + elif "[WARNING]" in line: + tag = "log_warning" + elif "[ERROR]" in line: + tag = "log_error" + elif "[CRITICAL]" in line: + tag = "log_critical" + elif "elapsed_seconds=" in line or "耗时" in line: + tag = "log_performance" + elif re.search(r'\[[\w\.]+\]', line): + tag = "log_module" + + if tag: + log_text.tag_add(tag, start_pos, end_pos) except Exception: - pass # 忽略标签应用失败 + pass # 忽略级别标签应用失败 # 不再自动滚动到底部,让用户自由控制滚动位置 changed = True @@ -3430,35 +3418,43 @@ def main(): except Exception: pass - # 配置行为日志颜色标签(与主日志保持一致) - try: - # 根据主题调整行为日志颜色 - light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} + # 配置行为日志颜色标签(使用统一的颜色配置模块) + def configure_actions_log_colors(): + """根据当前主题配置行为日志的颜色标签""" try: - current_theme = str(gui_theme_var.get() or "litera") + # 获取当前主题 + try: + current_theme = str(gui_theme_var.get() or "litera") + except Exception: + current_theme = "litera" + + # 获取颜色配置 + color_config = get_color_config(current_theme) + + # 根据主题设置背景和前景色 + light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} + is_light = current_theme.lower() in light_themes + if is_light: + actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C") + else: + actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF") + + # 为所有操作类型配置标签 + for op_type, colors in color_config.items(): + tag_name = f"op_{op_type}" + try: + actions_log_text.tag_configure( + tag_name, + foreground=colors["foreground"], + background=colors["background"], + ) + except Exception: + pass # 忽略标签配置失败 except Exception: - current_theme = "litera" - - if current_theme in light_themes: - # 明亮主题 - actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C") - actions_log_text.tag_configure("action_timestamp", foreground="#8B8B8B") - actions_log_text.tag_configure("action_operation", foreground="#1E88E5") # 蓝色操作 - actions_log_text.tag_configure("action_ocr", foreground="#388E3C") # 绿色OCR - actions_log_text.tag_configure("action_decision", foreground="#F57C00") # 橙色决策 - actions_log_text.tag_configure("action_state", foreground="#7B1FA2") # 紫色状态 - actions_log_text.tag_configure("action_performance", foreground="#D32F2F") # 红色性能 - else: - # 暗色主题 - actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF") - actions_log_text.tag_configure("action_timestamp", foreground="#A0A0A0") - actions_log_text.tag_configure("action_operation", foreground="#64B5F6") # 亮蓝色操作 - actions_log_text.tag_configure("action_ocr", foreground="#81C784") # 亮绿色OCR - actions_log_text.tag_configure("action_decision", foreground="#FFB74D") # 金色决策 - actions_log_text.tag_configure("action_state", foreground="#BA68C8") # 亮紫色状态 - actions_log_text.tag_configure("action_performance", foreground="#EF5350") # 亮红色性能 - except Exception: - pass # 忽略颜色配置失败 + pass # 忽略颜色配置失败 + + # 初始配置 + configure_actions_log_colors() actions_filter_var = tk.StringVar(value="") @@ -3515,6 +3511,12 @@ def main(): actions_log_text.delete("1.0", "end") if tail: + # 获取当前主题(用于颜色配置) + try: + current_theme = str(gui_theme_var.get() or "litera") + except Exception: + current_theme = "litera" + # 逐行插入并应用颜色标签 for i, line in enumerate(tail): start_pos = actions_log_text.index("end-1c") @@ -3524,29 +3526,18 @@ def main(): actions_log_text.insert("end", "\n") actions_log_text.insert("end", line) - # 根据内容类型应用颜色标签 + # 使用统一的颜色配置模块应用颜色 end_pos = actions_log_text.index("end") - tag = None - - if "操作:" in line or "执行" in line: - tag = "action_operation" - elif "OCR" in line or "识别" in line: - tag = "action_ocr" - elif "决策" in line or "判断" in line: - tag = "action_decision" - elif "状态" in line or "阶段" in line: - tag = "action_state" - elif "耗时" in line or "时间" in line or "性能" in line: - tag = "action_performance" - elif re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', line): - tag = "action_timestamp" - - # 应用标签 - if tag: - try: - actions_log_text.tag_add(tag, start_pos, end_pos) - except Exception: - pass # 忽略标签应用失败 + try: + apply_operation_color( + actions_log_text, + start_pos, + end_pos, + line, + current_theme + ) + except Exception: + pass # 忽略颜色应用失败 else: actions_log_text.insert("1.0", "暂无匹配的行为日志") @@ -3719,6 +3710,240 @@ def main(): side=LEFT, padx=(10, 0) ) + # 中奖记录显示 + win_record_top = ttk.Frame(win_record_tab) + win_record_top.pack(fill=X, padx=10, pady=(10, 0)) + + win_record_left = ttk.Frame(win_record_tab) + win_record_left.pack(side=LEFT, fill=BOTH, expand=True, padx=(10, 5), pady=10) + + win_record_right = ttk.Frame(win_record_tab) + win_record_right.pack(side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10) + + # 左侧:中奖截图列表 + win_list_label = ttk.Label(win_record_left, text="中奖截图列表:") + win_list_label.pack(anchor="w", padx=(0, 10), pady=(0, 5)) + + win_list_frame = ttk.Frame(win_record_left) + win_list_frame.pack(fill=BOTH, expand=True) + + win_list_scrollbar = ttk.Scrollbar(win_list_frame) + win_list_scrollbar.pack(side=RIGHT, fill=Y) + + win_listbox = tk.Listbox(win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9)) + win_listbox.pack(side=LEFT, fill=BOTH, expand=True) + win_list_scrollbar.config(command=win_listbox.yview) + + # 存储文件路径映射(索引 -> 文件路径) + _win_file_paths: dict[int, str] = {} + + # 右侧:截图预览 + win_preview_label = ttk.Label(win_record_right, text="截图预览:") + win_preview_label.pack(anchor="w", pady=(0, 5)) + + win_preview_frame = ttk.Frame(win_record_right) + win_preview_frame.pack(fill=BOTH, expand=True) + + win_image_label = ttk.Label(win_preview_frame) + win_image_label.pack(fill=BOTH, expand=True) + _win_img_ref: dict[str, Any] = {"photo": None} + + def scan_win_images(): + """扫描中奖截图目录""" + try: + from path_config import get_pic_dir + pic_dir = get_pic_dir() + except Exception: + import path_config + pic_dir = path_config.get_pic_dir() + + prize_dir = os.path.join(pic_dir, "lottery_prize_captures") + win_images = [] + + if os.path.exists(prize_dir): + for file in os.listdir(prize_dir): + if file.lower().endswith((".png", ".jpg", ".jpeg")): + file_path = os.path.join(prize_dir, file) + # 获取文件修改时间 + try: + mtime = os.path.getmtime(file_path) + win_images.append((file, file_path, mtime)) + except Exception: + win_images.append((file, file_path, 0)) + + # 按时间倒序排序(最新的在前) + win_images.sort(key=lambda x: x[2], reverse=True) + return win_images + + def refresh_win_record(): + """刷新中奖记录列表""" + try: + win_images = scan_win_images() + win_listbox.delete(0, tk.END) + _win_file_paths.clear() + + for idx, (file, file_path, mtime) in enumerate(win_images): + # 格式化显示:文件名 + 时间 + try: + from datetime import datetime + dt = datetime.fromtimestamp(mtime) + time_str = dt.strftime("%Y-%m-%d %H:%M:%S") + display_text = f"{file} ({time_str})" + except Exception: + display_text = file + + win_listbox.insert(tk.END, display_text) + # 存储文件路径映射 + _win_file_paths[idx] = file_path + + if win_images: + on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图") + else: + on_line("[中奖记录] 暂无中奖截图") + except Exception as e: + on_line(f"[中奖记录] 刷新失败:{e}") + + def on_win_list_select(event): + """当选择中奖截图时,显示预览""" + try: + selection = win_listbox.curselection() + if not selection: + return + + index = selection[0] + # 从映射中获取文件路径 + if index in _win_file_paths: + file_path = _win_file_paths[index] + _load_win_image(file_path) + except Exception as e: + on_line(f"[中奖记录] 预览失败:{e}") + + def _load_win_image(img_path: str): + """加载并显示中奖截图""" + if not os.path.exists(img_path): + win_image_label.configure(image="") + _win_img_ref["photo"] = None + return + + try: + img = Image.open(img_path) + img.load() + img = img.convert("RGB") + except Exception as e: + on_line(f"[中奖记录] 图片加载失败:{e}") + return + + # 获取预览区域尺寸 + try: + win_preview_frame.update_idletasks() + w = win_preview_frame.winfo_width() + h = win_preview_frame.winfo_height() + if w <= 1 or h <= 1: + w, h = 400, 600 + except Exception: + w, h = 400, 600 + + max_w = max(200, w - 20) + max_h = max(300, h - 20) + + try: + resample = Image.Resampling.LANCZOS + except AttributeError: + resample = 1 + + img.thumbnail((max_w, max_h), resample) + photo = ImageTk.PhotoImage(img) + _win_img_ref["photo"] = photo + win_image_label.configure(image=photo) + + win_listbox.bind("<>", on_win_list_select) + + ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(side=LEFT, padx=(0, 10)) + + def open_win_folder(): + """打开中奖截图目录""" + try: + from path_config import get_pic_dir + pic_dir = get_pic_dir() + except Exception: + import path_config + pic_dir = path_config.get_pic_dir() + + prize_dir = os.path.join(pic_dir, "lottery_prize_captures") + os.makedirs(prize_dir, exist_ok=True) + try: + os.startfile(prize_dir) # type: ignore[attr-defined] + except Exception as e: + on_line(f"[中奖记录] 打开目录失败:{e}") + + ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT) + + # 误识别记录管理 + false_positive_frame = ttk.LabelFrame(win_record_right, text="误识别记录管理") + false_positive_frame.pack(fill=X, pady=(10, 0)) + + false_positive_text = ScrolledText(false_positive_frame, height=6) + false_positive_text.pack(fill=X, padx=10, pady=10) + + def load_false_positives(): + """加载误识别记录""" + try: + from path_config import get_pic_dir + pic_dir = get_pic_dir() + except Exception: + import path_config + pic_dir = path_config.get_pic_dir() + + false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") + if not os.path.exists(false_positive_file): + false_positive_text.delete("1.0", "end") + false_positive_text.insert("1.0", "暂无误识别记录") + return + + try: + import json + with open(false_positive_file, "r", encoding="utf-8") as f: + data = json.load(f) + false_positives = data.get("false_positives", []) + false_positive_text.delete("1.0", "end") + if false_positives: + false_positive_text.insert("1.0", "\n".join(false_positives)) + else: + false_positive_text.insert("1.0", "暂无误识别记录") + except Exception as e: + false_positive_text.delete("1.0", "end") + false_positive_text.insert("1.0", f"加载失败:{e}") + + def save_false_positives(): + """保存误识别记录""" + try: + from path_config import get_pic_dir + pic_dir = get_pic_dir() + except Exception: + import path_config + pic_dir = path_config.get_pic_dir() + + false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") + os.makedirs(os.path.dirname(false_positive_file), exist_ok=True) + + content = false_positive_text.get("1.0", "end-1c") + lines = [line.strip() for line in content.splitlines() if line.strip()] + + try: + import json + with open(false_positive_file, "w", encoding="utf-8") as f: + json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2) + on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录") + except Exception as e: + on_line(f"[中奖记录] 保存失败:{e}") + + false_positive_btn_frame = ttk.Frame(false_positive_frame) + false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10)) + ttk.Button(false_positive_btn_frame, text="刷新", command=load_false_positives).pack(side=LEFT, padx=(0, 5)) + ttk.Button(false_positive_btn_frame, text="保存", command=save_false_positives).pack(side=LEFT) + + load_false_positives() + pump_logs() def delayed_refresh_preview() -> None: @@ -3730,6 +3955,7 @@ def main(): root.after(500, refresh_reservations) # type: ignore[arg-type] root.after(500, refresh_high_value_rooms) # type: ignore[arg-type] root.after(500, refresh_actions_log) # type: ignore[arg-type] + root.after(500, refresh_win_record) # type: ignore[arg-type] # 定期刷新行为日志(每2秒) def auto_refresh_actions_log() -> None: @@ -3771,4 +3997,4 @@ if __name__ == "__main__": print_version_banner("gui_app") except Exception: pass - main() + main() \ No newline at end of file diff --git a/gui/gui_core.py b/gui/gui_core.py index a5d04d8..833791c 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -894,172 +894,9 @@ class Runner: self._reader_thread = threading.Thread(target=_reader, daemon=True) self._reader_thread.start() - def start_test_yanghao_flow(self, device_id: str, seconds: int) -> None: - if self.is_running(): - raise RuntimeError("已经在运行") + # (已移除) 测试养号启动器 - seconds = int(seconds or 0) - if seconds <= 0: - seconds = 90 - - run_cli_path = path_config.get_run_cli_path() - if not os.path.exists(run_cli_path): - raise FileNotFoundError( - f"未找到 run_cli.py 文件。\n" - f"预期路径: {run_cli_path}\n" - f"请确保 run_cli.py 位于项目根目录。" - ) - cmd = [ - sys.executable, - run_cli_path, - "--test-yanghao-flow", - "--test-yanghao-flow-seconds", - str(seconds), - ] - if device_id: - cmd += ["--device-id", device_id] - - env = os.environ.copy() - env.setdefault("PYTHONIOENCODING", "utf-8") - - adb_exe = find_adb_executable() - if adb_exe: - adb_dir = os.path.dirname(adb_exe) - env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "") - env["ADB_EXECUTABLE"] = adb_exe - else: - self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH") - - p = subprocess.Popen( - cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - encoding="utf-8", - errors="replace", - env=env, - cwd=path_config.PROJECT_ROOT, - ) - - with self._lock: - self._proc = p - self._pid = p.pid - self._start_ts = time.time() - self._exit_code = None - self._last_log_ts = time.time() - self._counters = {} - self._fudai_last = { - "content": "", - "countdown": "", - "participants": None, - "copies": None, - "prize_value_yuan": None, - "updated_ts": None, - } - self._events = [] - self._wins = [] - - def _reader(): - assert self._proc is not None - out = self._proc.stdout - if out is None: - return - for line in out: - cleaned_line = line.rstrip("\n") - self._on_line(cleaned_line) - try: - self._update_stats_from_line(cleaned_line) - except Exception: - pass - rc = self._proc.wait() - with self._lock: - self._exit_code = rc - self._on_line(f"[进程结束] exit_code={rc}") - - self._reader_thread = threading.Thread(target=_reader, daemon=True) - self._reader_thread.start() - - def start_test_comment(self, device_id: str, text: str) -> None: - if self.is_running(): - raise RuntimeError("已经在运行") - - text = str(text or "").strip() - run_cli_path = path_config.get_run_cli_path() - if not os.path.exists(run_cli_path): - raise FileNotFoundError( - f"未找到 run_cli.py 文件。\n" - f"预期路径: {run_cli_path}\n" - f"请确保 run_cli.py 位于项目根目录。" - ) - cmd = [ - sys.executable, - run_cli_path, - "--test-comment", - ] - if text: - cmd += ["--test-comment-text", text] - if device_id: - cmd += ["--device-id", device_id] - - env = os.environ.copy() - env.setdefault("PYTHONIOENCODING", "utf-8") - - adb_exe = find_adb_executable() - if adb_exe: - adb_dir = os.path.dirname(adb_exe) - env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "") - env["ADB_EXECUTABLE"] = adb_exe - else: - self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH") - - p = subprocess.Popen( - cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - encoding="utf-8", - errors="replace", - env=env, - cwd=path_config.PROJECT_ROOT, - ) - - with self._lock: - self._proc = p - self._pid = p.pid - self._start_ts = time.time() - self._exit_code = None - self._last_log_ts = time.time() - self._counters = {} - self._fudai_last = { - "content": "", - "countdown": "", - "participants": None, - "copies": None, - "prize_value_yuan": None, - "updated_ts": None, - } - self._events = [] - self._wins = [] - - def _reader(): - assert self._proc is not None - out = self._proc.stdout - if out is None: - return - for line in out: - cleaned_line = line.rstrip("\n") - self._on_line(cleaned_line) - try: - self._update_stats_from_line(cleaned_line) - except Exception: - pass - rc = self._proc.wait() - with self._lock: - self._exit_code = rc - self._on_line(f"[进程结束] exit_code={rc}") - - self._reader_thread = threading.Thread(target=_reader, daemon=True) - self._reader_thread.start() + # (已移除) 测试评论启动器 def send_back_key(self, device_id: str) -> bool: """手动发送返回键到指定设备。 @@ -1153,7 +990,11 @@ class Runner: # 类 Unix:尝试向进程组发送 SIGKILL import signal - os.kill(pid, signal.SIGKILL) + try: + os.kill(pid, signal.SIGKILL) + except AttributeError: + # 如果SIGKILL不存在,使用SIGTERM + os.kill(pid, signal.SIGTERM) except Exception: pass diff --git a/gui/web_components/__init__.py b/gui/web_components/__init__.py index 97a14f5..106d0d4 100644 --- a/gui/web_components/__init__.py +++ b/gui/web_components/__init__.py @@ -17,3 +17,25 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/web_components/proc_runner.py b/gui/web_components/proc_runner.py index 7842dcc..e231e05 100644 --- a/gui/web_components/proc_runner.py +++ b/gui/web_components/proc_runner.py @@ -25,3 +25,25 @@ __all__ = ["ProcRunner"] + + + + + + + + + + + + + + + + + + + + + + diff --git a/gui/web_gui.py b/gui/web_gui.py index d8a4f81..5b7fe6a 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -825,12 +825,13 @@ class ProcRunner: def get_reservations(self) -> dict: """获取当前预约队列信息(来自子进程写入的 douyin/core/state/reservations.json)。""" - try: - import path_config - path = path_config.get_reservations_path() - except Exception: - # 回退到旧路径(向后兼容) - path = path_config.get_reservations_path() + if hasattr(path_config, "get_reservations_path"): + try: + path = path_config.get_reservations_path() + except Exception: + path = os.path.join(path_config.PROJECT_ROOT if hasattr(path_config, "PROJECT_ROOT") else os.getcwd(), "douyin", "state", "reservations.json") + else: + path = os.path.join(os.getcwd(), "douyin", "state", "reservations.json") try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: @@ -1577,13 +1578,14 @@ class Handler(BaseHTTPRequestHandler): n = int((qs.get("lines") or [200])[0]) except Exception: n = 200 - # 使用统一的路径配置 - try: - import path_config - path = path_config.get_actions_log_path() - except Exception: - # 回退到旧路径(向后兼容) - path = path_config.get_actions_log_path() + # 使用统一的路径配置(优先使用 path_config 中的配置,失败时回退到项目内置路径) + if hasattr(path_config, "get_actions_log_path"): + try: + path = path_config.get_actions_log_path() + except Exception: + path = os.path.join(path_config.PROJECT_ROOT if hasattr(path_config, "PROJECT_ROOT") else os.getcwd(), "logs", "actions.log") + else: + path = os.path.join(os.getcwd(), "logs", "actions.log") out_lines: list[str] = [] try: if os.path.exists(path): @@ -1779,29 +1781,7 @@ class Handler(BaseHTTPRequestHandler): return self._send_json({"ok": False, "error": str(e)}, status=500) return self._send_json({"ok": True}) - if u.path == "/api/test-yanghao": - if RUNNER.is_running(): - return self._send_json({"ok": False, "error": "running"}, status=409) - body = self._read_json() - device_id = str(body.get("device_id") or "").strip() - seconds = int(body.get("seconds") or 60) - try: - RUNNER.start_test_yanghao(device_id, seconds) - except Exception as e: - return self._send_json({"ok": False, "error": str(e)}, status=500) - return self._send_json({"ok": True}) - - if u.path == "/api/test-comment": - if RUNNER.is_running(): - return self._send_json({"ok": False, "error": "running"}, status=409) - body = self._read_json() - device_id = str(body.get("device_id") or "").strip() - text = str(body.get("text") or "").strip() - try: - RUNNER.start_test_comment(device_id, text) - except Exception as e: - return self._send_json({"ok": False, "error": str(e)}, status=500) - return self._send_json({"ok": True}) + # (已移除) /api/test-yanghao 与 /api/test-comment 接口已删除 if u.path == "/api/stop": RUNNER.stop() @@ -1854,7 +1834,6 @@ def main() -> int: raise print(f"Web GUI: http://{host}:{port}") print("- 可在页面里设置养号时长/间隔并保存到 config.json") - print("- 可一键运行‘测试养号流程’,日志会在页面里滚动显示") try: httpd.serve_forever() except KeyboardInterrupt: diff --git a/operations/ocr_operations.py b/operations/ocr_operations.py index a61dea9..02e07f5 100644 --- a/operations/ocr_operations.py +++ b/operations/ocr_operations.py @@ -38,7 +38,7 @@ class OCRProcessor: # 首先尝试EasyOCR try: # 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题 - import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + import easyocr # type: ignore[import-untyped, import] # pyright: ignore[reportMissingImports, reportMissingModuleSource] # 只加载中文和英文,加快初始化速度 # 自动检测GPU可用性,如果可用则启用GPU加速 @@ -67,19 +67,8 @@ class OCRProcessor: ), contextlib.redirect_stderr(devnull): from paddleocr import PaddleOCR - # PaddleOCR的GPU支持需要paddlepaddle-gpu版本 + # 使用 PaddleOCR(强制 CPU 模式,不进行 GPU 检测) use_gpu = False - try: - import paddle - - if ( - paddle.device.is_compiled_with_cuda() - and paddle.device.get_device() - ): - use_gpu = False - except Exception: - pass - self.ocr = PaddleOCR( lang="ch", ocr_version="PP-OCRv4", @@ -90,8 +79,7 @@ class OCRProcessor: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - gpu_status = "GPU加速" if use_gpu else "CPU模式" - print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})") + print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") print( f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr" ) @@ -146,19 +134,8 @@ class OCRProcessor: ): from paddleocr import PaddleOCR - # PaddleOCR的GPU支持需要paddlepaddle-gpu版本 + # 使用 PaddleOCR(强制 CPU 模式) use_gpu = False - try: - import paddle - - if ( - paddle.device.is_compiled_with_cuda() - and paddle.device.get_device() - ): - use_gpu = False - except Exception: - pass - self.ocr = PaddleOCR( lang="ch", ocr_version="PP-OCRv4", @@ -169,8 +146,7 @@ class OCRProcessor: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - gpu_status = "GPU加速" if use_gpu else "CPU模式" - print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR({gpu_status})") + print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)") except Exception as e: print(f"[OCR] OCR引擎初始化失败: {e}") self.ocr = None @@ -228,4 +204,4 @@ __all__ = [ "extract_ocr_content", "_ensure_ocr", ] - + \ No newline at end of file diff --git a/run_cli.py b/run_cli.py index 9025c57..97836bd 100644 --- a/run_cli.py +++ b/run_cli.py @@ -108,24 +108,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: default=0, help="运行时长(分钟),0或负数表示无限运行,默认0(无限运行)", ) - p.add_argument( - "--test-yanghao-flow", - action="store_true", - help="测试:只执行一次推荐页养号流程并退出", - ) - p.add_argument( - "--test-yanghao-flow-seconds", - type=int, - default=10, - help="测试:推荐页养号停留秒数", - ) - - p.add_argument( - "--test-comment", - action="store_true", - help="测试:按配置坐标执行一次评论输入+键盘确认发送并退出", - ) - p.add_argument("--test-comment-text", default="测试评论123", help="测试评论内容") + # (已移除) 测试相关的命令行参数(测试养号、测试评论) # 允许从 GUI 覆盖关键配置(不改动 config.json 也能生效) p.add_argument( diff --git a/tools/README_Region_Selector.md b/tools/README_Region_Selector.md new file mode 100644 index 0000000..305edcf --- /dev/null +++ b/tools/README_Region_Selector.md @@ -0,0 +1,128 @@ +# 区域选择器 - 白色像素统计工具 + +## 功能说明 + +这个工具用于在图片上选择区域,圈出边框,并统计该区域内的白色像素数量。主要用于识别直播间图标等需要根据白色像素比例来判断的场景。 + +## 主要功能 + +1. **图片查看和导航** + - 支持多种图片格式:PNG, JPG, JPEG, BMP, WebP + - 上一张/下一张图片切换 + - 拖放图片文件到窗口直接打开 + +2. **图片缩放和平移** + - 鼠标滚轮缩放 + - Ctrl+滚轮快速缩放 + - 右键拖拽平移图片 + - 适应窗口大小 + - 重置缩放 + +3. **区域选择** + - 左键拖拽选择矩形区域 + - 红色虚线显示选择区域 + - 实时显示选择区域坐标和尺寸 + +4. **白色像素分析** + - 统计选中区域内的白色像素数量 + - 计算白色像素比例 + - 计算置信度(基于白色比例与0.5的距离) + - 自动保存分析结果 + +5. **数据管理** + - 保存/加载区域数据到JSON文件 + - 显示所有保存的区域 + - 清除选择或清除所有区域 + +## 使用方法 + +### 启动工具 + +```bash +# 从tools目录运行 +python region_selector.py + +# 或者直接指定图片路径 +python region_selector.py path/to/image.png +``` + +### 基本操作 + +1. **打开图片** + - 点击"文件" -> "打开" 或按 Ctrl+O + - 或者直接拖放图片文件到窗口 + +2. **选择区域** + - 按住鼠标左键拖拽选择矩形区域 + - 红色虚线会显示选择的区域 + +3. **缩放和平移** + - 鼠标滚轮:缩放 + - Ctrl+滚轮:快速缩放 + - 右键拖拽:平移图片 + - 视图菜单:放大/缩小/重置/适应窗口 + +4. **分析区域** + - 选择区域后,按 Enter 键或点击"分析区域"按钮 + - 结果会显示在右侧面板和控制台 + +5. **管理数据** + - Ctrl+S:保存区域数据到JSON文件 + - Ctrl+L:加载区域数据 + - "显示所有":查看所有保存的区域数据 + +## 快捷键 + +| 快捷键 | 功能 | +|--------|------| +| Ctrl+O | 打开图片 | +| ← / → | 上一张/下一张图片 | +| + / - | 放大/缩小 | +| Ctrl+0 | 重置缩放 | +| Ctrl+F | 适应窗口 | +| Delete | 清除选择 | +| Enter | 分析区域 | +| Ctrl+S | 保存区域数据 | +| Ctrl+A | 显示所有区域 | + +## 输出格式 + +分析结果包括: +- 区域坐标:(x1, y1) - (x2, y2) +- 区域尺寸:宽度x高度 +- 总像素数 +- 白色像素数 +- 白色像素比例 +- 置信度 + +## 数据文件格式 + +保存的JSON文件包含每个区域的完整信息: + +```json +[ + { + "coordinates": [x1, y1, x2, y2], + "size": [width, height], + "total_pixels": 1234, + "white_pixels": 567, + "white_ratio": 0.459, + "image_path": "path/to/image.png" + } +] +``` + +## 应用场景 + +- 直播间图标识别:通过白色像素比例判断是否为直播状态 +- UI元素检测:识别界面上的特定图标或按钮 +- 图像分析:统计图像中特定区域的颜色分布 + +## 技术说明 + +- 使用PIL (Pillow) 进行图像处理 +- 使用tkinter创建GUI界面 +- 支持numpy进行高效的像素统计 +- 白色像素阈值:RGB值都≥240的像素被认为是白色 + + diff --git a/tools/pick_coords.py b/tools/pick_coords.py index 241e0c9..d9fe91d 100644 --- a/tools/pick_coords.py +++ b/tools/pick_coords.py @@ -30,14 +30,23 @@ class CoordPicker: self.w = 0 self.h = 0 self.scale = 1.0 + self.min_scale = 0.1 # 最小缩放比例 + self.max_scale = 10.0 # 最大缩放比例 self.disp_w = 0 self.disp_h = 0 self.tk_img = None self.file_list: list[Path] = [] self.file_idx: int = -1 + self.zoom_center_x = 0 # 缩放中心点 + self.zoom_center_y = 0 + self.scroll_offset_x = 0 # 滚动偏移 + self.scroll_offset_y = 0 + self.magnifier_window = None # 放大镜窗口 + self.magnifier_size = 200 # 放大镜窗口大小 + self.magnifier_zoom = 8 # 放大倍数 # 使用 TkinterDnD 支持拖放(如果可用) - if HAS_DND: + if HAS_DND and TkinterDnD is not None: self.root = TkinterDnD.Tk() else: self.root = tk.Tk() @@ -51,27 +60,59 @@ class CoordPicker: file_menu.add_separator() file_menu.add_command(label="退出", command=self.root.destroy) menubar.add_cascade(label="文件", menu=file_menu) + + view_menu = tk.Menu(menubar, tearoff=0) + view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上") + view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下") + view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0") + view_menu.add_separator() + view_menu.add_command(label="显示/隐藏放大镜", command=self.toggle_magnifier, accelerator="M") + menubar.add_cascade(label="视图", menu=view_menu) + self.root.config(menu=menubar) self.root.bind_all("", lambda e: self.open_dialog()) self.root.bind("", lambda e: self.prev_image()) self.root.bind("", lambda e: self.next_image()) self.root.bind("", lambda e: self.prev_image()) # PageUp self.root.bind("", lambda e: self.next_image()) # PageDown + self.root.bind("", lambda e: self.zoom_in()) + self.root.bind("", lambda e: self.zoom_in()) # 无Shift的+键 + self.root.bind("", lambda e: self.zoom_out()) + self.root.bind("", lambda e: self.reset_zoom()) + self.root.bind("", lambda e: self.toggle_magnifier()) + self.root.bind("", lambda e: self.toggle_magnifier()) self.canvas = tk.Canvas(self.root, width=800, height=600) - self.canvas.pack(fill=tk.BOTH, expand=False) + self.canvas.pack(fill=tk.BOTH, expand=True) self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW) self.status = tk.StringVar() if HAS_DND: - self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片;或直接拖放图片到窗口") + self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片;或直接拖放图片到窗口") else: - self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)") + self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)") self.label = tk.Label(self.root, textvariable=self.status, anchor="w") self.label.pack(fill=tk.X) + + # 像素信息显示 + self.pixel_info = tk.StringVar() + self.pixel_info.set("") + self.pixel_label = tk.Label(self.root, textvariable=self.pixel_info, anchor="w", font=("Courier", 10)) + self.pixel_label.pack(fill=tk.X) self.canvas.bind("", self.on_move) self.canvas.bind("", self.on_click) + self.canvas.bind("", self.on_right_click) # 右键显示放大镜 + self.canvas.bind("", self.on_mousewheel) # Windows/Linux + self.canvas.bind("", self.on_mousewheel) # Linux + self.canvas.bind("", self.on_mousewheel) # Linux + self.canvas.bind("", self.on_mousewheel_ctrl) # Ctrl+滚轮 + self.canvas.bind("", self.on_drag) # 拖拽平移 + self.canvas.bind("", self.on_drag_start) + self.canvas.bind("", self.on_drag_end) + self.drag_start_x = 0 + self.drag_start_y = 0 + self.is_dragging = False # 添加拖放支持 if HAS_DND: @@ -113,28 +154,8 @@ class CoordPicker: self._refresh_file_list(image_path) # 显示用缩放(不改变输出坐标) - screen_w = self.root.winfo_screenwidth() - screen_h = self.root.winfo_screenheight() - max_w = int(screen_w * 0.9) - max_h = int(screen_h * 0.85) - scale_w = max_w / max(1, self.w) - scale_h = max_h / max(1, self.h) - self.scale = min(1.0, scale_w, scale_h) - self.disp_w = int(self.w * self.scale) - self.disp_h = int(self.h * self.scale) - - disp_img = self.img - if self.scale < 1.0: - try: - resample = Image.Resampling.BICUBIC # Pillow>=9 - except Exception: - resample = Image.BICUBIC # older Pillow - disp_img = self.img.resize((self.disp_w, self.disp_h), resample) - - self.tk_img = ImageTk.PhotoImage(disp_img) - self.canvas.config(width=self.disp_w, height=self.disp_h) - self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img) - self.root.title(f"取坐标: {image_path} ({self.w}x{self.h})") + self._update_display() + self.root.title(f"取坐标: {image_path} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") def open_dialog(self) -> bool: initial_dir = None @@ -164,24 +185,273 @@ class CoordPicker: def _to_image_xy(self, event) -> tuple[int, int]: if not self.img or self.w <= 0 or self.h <= 0: return 0, 0 - x = int(clamp(event.x / self.scale, 0, self.w - 1)) - y = int(clamp(event.y / self.scale, 0, self.h - 1)) + # 把canvas坐标转换为图像坐标(考虑缩放和滚动偏移) + canvas_x = event.x + self.scroll_offset_x + canvas_y = event.y + self.scroll_offset_y + x = int(clamp(canvas_x / self.scale, 0, self.w - 1)) + y = int(clamp(canvas_y / self.scale, 0, self.h - 1)) return x, y + def _update_display(self): + """更新显示""" + if not self.img: + return + + # 获取canvas实际大小 + self.root.update_idletasks() + canvas_w = max(1, self.canvas.winfo_width()) + canvas_h = max(1, self.canvas.winfo_height()) + + # 计算显示尺寸 + self.disp_w = int(self.w * self.scale) + self.disp_h = int(self.h * self.scale) + + # 限制滚动偏移 + max_offset_x = max(0, self.disp_w - canvas_w) + max_offset_y = max(0, self.disp_h - canvas_h) + self.scroll_offset_x = max(0, min(self.scroll_offset_x, max_offset_x)) + self.scroll_offset_y = max(0, min(self.scroll_offset_y, max_offset_y)) + + # 生成显示图像 + try: + resample = Image.Resampling.BICUBIC if hasattr(Image, 'Resampling') else Image.BICUBIC + except Exception: + resample = Image.BICUBIC + + if self.scale != 1.0: + # 如果放大,只显示可见区域以提高性能 + if self.scale > 1.0 and canvas_w < self.disp_w and canvas_h < self.disp_h: + # 计算原图中要显示的区域 + src_x1 = max(0, int(self.scroll_offset_x / self.scale)) + src_y1 = max(0, int(self.scroll_offset_y / self.scale)) + src_x2 = min(self.w, src_x1 + int(canvas_w / self.scale) + 2) + src_y2 = min(self.h, src_y1 + int(canvas_h / self.scale) + 2) + + # 裁剪并放大 + crop_img = self.img.crop((src_x1, src_y1, src_x2, src_y2)) + crop_w, crop_h = crop_img.size + disp_img = crop_img.resize((int(crop_w * self.scale), int(crop_h * self.scale)), resample) + else: + # 缩小或完全显示 + disp_img = self.img.resize((self.disp_w, self.disp_h), resample) + else: + disp_img = self.img + + self.tk_img = ImageTk.PhotoImage(disp_img) + + # 更新canvas滚动区域 + self.canvas.config(scrollregion=(0, 0, self.disp_w, self.disp_h)) + + # 更新图像位置 + self.canvas.coords(self._canvas_image_id, -self.scroll_offset_x, -self.scroll_offset_y) + self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img) + + # 更新标题 + if self.image_path: + self.root.title(f"取坐标: {self.image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") + def on_move(self, event): + """移动鼠标:显示坐标和像素信息(保留你原来的坐标逻辑)""" x, y = self._to_image_xy(event) - self.status.set(f"x={x}, y={y}") + rgb_info = "" + if self.img and 0 <= x < self.w and 0 <= y < self.h: + try: + pixel = self.img.getpixel((x, y)) + if isinstance(pixel, tuple) and len(pixel) >= 3: + rgb_info = f" | RGB({pixel[0]}, {pixel[1]}, {pixel[2]})" + elif isinstance(pixel, int): + rgb_info = f" | Gray({pixel})" + except Exception: + pass + + self.status.set(f"x={x}, y={y}{rgb_info}") + self.pixel_info.set(f"像素位置: ({x}, {y}){rgb_info}") + + # 更新放大镜 + if self.magnifier_window and self.magnifier_window.winfo_exists(): + self._update_magnifier(x, y) def on_click(self, event): + """左键点击:输出到终端 + 复制到剪贴板(恢复你之前的简单行为)""" x, y = self._to_image_xy(event) text = f"{x},{y}" print(text) try: self.root.clipboard_clear() self.root.clipboard_append(text) + self.root.update_idletasks() self.status.set(f"已复制: {text}") except Exception: self.status.set(f"坐标: {text} (复制失败)") + + def on_right_click(self, event): + """右键显示/隐藏放大镜""" + self.toggle_magnifier() + + def on_drag_start(self, event): + """开始拖拽""" + self.drag_start_x = event.x + self.drag_start_y = event.y + self.is_dragging = False + + def on_drag(self, event): + """拖拽平移""" + if not self.img: + return + dx = event.x - self.drag_start_x + dy = event.y - self.drag_start_y + if abs(dx) > 5 or abs(dy) > 5: # 避免误触 + self.is_dragging = True + self.scroll_offset_x -= dx + self.scroll_offset_y -= dy + self.drag_start_x = event.x + self.drag_start_y = event.y + self._update_display() + + def on_drag_end(self, event): + """结束拖拽""" + self.is_dragging = False + + def on_mousewheel(self, event): + """鼠标滚轮缩放(无Ctrl)""" + if event.state & 0x4: # Ctrl键按下 + return # 交给on_mousewheel_ctrl处理 + + delta = 0 + if event.num == 4 or event.delta > 0: # 向上滚动 + delta = 1 + elif event.num == 5 or event.delta < 0: # 向下滚动 + delta = -1 + + if delta != 0: + x, y = self._to_image_xy(event) + self._zoom_at_point(x, y, delta * 0.1) + + def on_mousewheel_ctrl(self, event): + """Ctrl+滚轮缩放""" + delta = 0 + if event.num == 4 or event.delta > 0: # 向上滚动 + delta = 1 + elif event.num == 5 or event.delta < 0: # 向下滚动 + delta = -1 + + if delta != 0: + x, y = self._to_image_xy(event) + self._zoom_at_point(x, y, delta * 0.1) + + def _zoom_at_point(self, img_x: int, img_y: int, delta: float): + """在指定点缩放""" + if not self.img: + return + + old_scale = self.scale + new_scale = clamp(old_scale + delta, self.min_scale, self.max_scale) + + if abs(new_scale - old_scale) < 0.01: + return + + # 计算缩放中心点在图像中的位置 + # 调整滚动偏移,使缩放点保持在屏幕上的同一位置 + scale_ratio = new_scale / old_scale + self.scroll_offset_x = img_x * new_scale - (img_x * old_scale - self.scroll_offset_x) * scale_ratio + self.scroll_offset_y = img_y * new_scale - (img_y * old_scale - self.scroll_offset_y) * scale_ratio + + self.scale = new_scale + self._update_display() + + def zoom_in(self): + """放大""" + if not self.img: + return + center_x = self.w // 2 + center_y = self.h // 2 + self._zoom_at_point(center_x, center_y, 0.2) + + def zoom_out(self): + """缩小""" + if not self.img: + return + center_x = self.w // 2 + center_y = self.h // 2 + self._zoom_at_point(center_x, center_y, -0.2) + + def reset_zoom(self): + """重置缩放""" + if not self.img: + return + self.scale = 1.0 + self.scroll_offset_x = 0 + self.scroll_offset_y = 0 + self._update_display() + + def toggle_magnifier(self): + """切换放大镜显示""" + if self.magnifier_window and self.magnifier_window.winfo_exists(): + self.magnifier_window.destroy() + self.magnifier_window = None + else: + self._create_magnifier() + + def _create_magnifier(self): + """创建放大镜窗口""" + if not self.img: + return + + self.magnifier_window = tk.Toplevel(self.root) + self.magnifier_window.title("放大镜") + self.magnifier_window.geometry(f"{self.magnifier_size}x{self.magnifier_size}") + self.magnifier_window.resizable(False, False) + + self.magnifier_canvas = tk.Canvas( + self.magnifier_window, + width=self.magnifier_size, + height=self.magnifier_size, + highlightthickness=1, + highlightbackground="black" + ) + self.magnifier_canvas.pack() + + # 绑定鼠标移动 + self.root.bind("", self._on_magnifier_move) + + def _on_magnifier_move(self, event): + """鼠标移动时更新放大镜""" + if not self.magnifier_window or not self.magnifier_window.winfo_exists(): + return + + x, y = self._to_image_xy(event) + self._update_magnifier(x, y) + + def _update_magnifier(self, img_x: int, img_y: int): + """更新放大镜显示""" + if not self.magnifier_window or not self.magnifier_window.winfo_exists() or not self.img: + return + + # 计算放大区域 + half_size = self.magnifier_size // (2 * self.magnifier_zoom) + x1 = max(0, img_x - half_size) + y1 = max(0, img_y - half_size) + x2 = min(self.w, img_x + half_size) + y2 = min(self.h, img_y + half_size) + + # 裁剪并放大 + crop_img = self.img.crop((x1, y1, x2, y2)) + try: + resample = Image.Resampling.NEAREST if hasattr(Image, 'Resampling') else Image.NEAREST + except Exception: + resample = Image.NEAREST + magnified = crop_img.resize((self.magnifier_size, self.magnifier_size), resample) + + # 显示 + tk_mag_img = ImageTk.PhotoImage(magnified) + self.magnifier_canvas.delete("all") + self.magnifier_canvas.create_image(self.magnifier_size // 2, self.magnifier_size // 2, image=tk_mag_img) + self.magnifier_canvas.image = tk_mag_img # 保持引用 + + # 绘制十字线 + center = self.magnifier_size // 2 + self.magnifier_canvas.create_line(center, 0, center, self.magnifier_size, fill="red", width=1) + self.magnifier_canvas.create_line(0, center, self.magnifier_size, center, fill="red", width=1) def _load_by_index(self, idx: int) -> bool: if not self.file_list: @@ -260,4 +530,4 @@ def main(argv: list[str]) -> int: if __name__ == "__main__": - raise SystemExit(main(sys.argv)) + raise SystemExit(main(sys.argv)) \ No newline at end of file diff --git a/tools/region_selector.py b/tools/region_selector.py new file mode 100644 index 0000000..f1dcb9e --- /dev/null +++ b/tools/region_selector.py @@ -0,0 +1,764 @@ +#!/usr/bin/env python3 +""" +区域选择和白色像素统计工具 +用于选择图片区域,圈出边框,并统计区域内白色像素数量 +""" + +import sys +from pathlib import Path +from typing import Optional, Tuple, Any +import json + +from PIL import Image, ImageTk, ImageDraw + +try: + import tkinter as tk + from tkinter import filedialog, messagebox +except Exception as e: + raise SystemExit(f"tkinter 不可用:{e}\n请安装带 tkinter 的 Python。") + +# 尝试导入拖放支持库 +try: + from tkinterdnd2 import DND_FILES, TkinterDnD # type: ignore[import] + HAS_DND = True +except ImportError: + HAS_DND = False + DND_FILES: Any = None + TkinterDnD: Any = None + + +def clamp(v: float, lo: float, hi: float) -> float: + return lo if v < lo else hi if v > hi else v + + +class RegionSelector: + def __init__(self, image_path: Optional[Path]): + self.image_path: Optional[Path] = None + self.img: Optional[Image.Image] = None + self.w = 0 + self.h = 0 + self.scale = 1.0 + self.min_scale = 0.1 # 最小缩放比例 + self.max_scale = 10.0 # 最大缩放比例 + self.disp_w = 0 + self.disp_h = 0 + self.tk_img = None + self.file_list: list[Path] = [] + self.file_idx: int = -1 + self.zoom_center_x = 0 # 缩放中心点 + self.zoom_center_y = 0 + self.scroll_offset_x = 0 # 滚动偏移 + self.scroll_offset_y = 0 + + # 区域选择相关 + self.selection_rect = None # 当前选择的矩形 (x1, y1, x2, y2) + self.selection_canvas_id = None # Canvas中的矩形ID + self.is_selecting = False + self.select_start_x = 0 + self.select_start_y = 0 + self.select_end_x = 0 + self.select_end_y = 0 + + # 拖拽相关 + self.is_dragging = False + self.drag_start_x = 0 + self.drag_start_y = 0 + + # 结果存储 + self.white_pixel_regions = [] # 存储区域和白色像素统计结果 + + # 使用 TkinterDnD 支持拖放(如果可用) + if HAS_DND: + self.root = TkinterDnD.Tk() + else: + self.root = tk.Tk() + + self.root.title("区域选择器 - 白色像素统计工具") + self.root.geometry("1200x800") + + # 创建菜单 + self._create_menu() + + # 创建主界面 + self._create_ui() + + if image_path is None: + if not self.open_dialog(): + raise SystemExit(2) + else: + self.set_image(image_path, update_list=True) + + def _create_menu(self): + """创建菜单栏""" + menubar = tk.Menu(self.root) + file_menu = tk.Menu(menubar, tearoff=0) + file_menu.add_command(label="打开...", command=self.open_dialog, accelerator="Ctrl+O") + file_menu.add_command(label="上一张", command=self.prev_image, accelerator="← / PageUp") + file_menu.add_command(label="下一张", command=self.next_image, accelerator="→ / PageDown") + file_menu.add_separator() + file_menu.add_command(label="保存区域数据", command=self.save_regions, accelerator="Ctrl+S") + file_menu.add_command(label="加载区域数据", command=self.load_regions, accelerator="Ctrl+L") + file_menu.add_separator() + file_menu.add_command(label="退出", command=self.root.destroy) + menubar.add_cascade(label="文件", menu=file_menu) + + view_menu = tk.Menu(menubar, tearoff=0) + view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上") + view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下") + view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0") + view_menu.add_command(label="适应窗口", command=self.fit_to_window, accelerator="Ctrl+F") + menubar.add_cascade(label="视图", menu=view_menu) + + region_menu = tk.Menu(menubar, tearoff=0) + region_menu.add_command(label="清除选择", command=self.clear_selection, accelerator="Delete") + region_menu.add_command(label="分析区域", command=self.analyze_region, accelerator="Enter") + region_menu.add_separator() + region_menu.add_command(label="显示所有区域", command=self.show_all_regions, accelerator="Ctrl+A") + region_menu.add_command(label="清除所有区域", command=self.clear_all_regions) + menubar.add_cascade(label="区域", menu=region_menu) + + self.root.config(menu=menubar) + + # 绑定快捷键 + self.root.bind_all("", lambda e: self.open_dialog()) + self.root.bind("", lambda e: self.prev_image()) + self.root.bind("", lambda e: self.next_image()) + self.root.bind("", lambda e: self.prev_image()) # PageUp + self.root.bind("", lambda e: self.next_image()) # PageDown + self.root.bind("", lambda e: self.zoom_in()) + self.root.bind("", lambda e: self.zoom_in()) # 无Shift的+键 + self.root.bind("", lambda e: self.zoom_out()) + self.root.bind("", lambda e: self.reset_zoom()) + self.root.bind("", lambda e: self.fit_to_window()) + self.root.bind("", lambda e: self.clear_selection()) + self.root.bind("", lambda e: self.analyze_region()) + self.root.bind("", lambda e: self.save_regions()) + self.root.bind("", lambda e: self.load_regions()) + self.root.bind("", lambda e: self.show_all_regions()) + + def _create_ui(self): + """创建用户界面""" + # 主框架 + main_frame = tk.Frame(self.root) + main_frame.pack(fill=tk.BOTH, expand=True) + + # 左侧控制面板 + left_panel = tk.Frame(main_frame, width=300, bg='#f0f0f0') + left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5) + + # 右侧画布区域 + right_panel = tk.Frame(main_frame) + right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True) + + # 控制面板内容 + self._create_control_panel(left_panel) + + # 画布 + self.canvas = tk.Canvas(right_panel, bg='#404040') + self.canvas.pack(fill=tk.BOTH, expand=True) + self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW) + + # 状态栏 + self.status = tk.StringVar() + if HAS_DND: + self.status.set("拖拽选择区域;滚轮缩放;右键拖拽平移;Enter分析区域;Ctrl+O打开图片;或直接拖放图片") + else: + self.status.set("拖拽选择区域;滚轮缩放;右键拖拽平移;Enter分析区域;Ctrl+O打开图片") + + status_label = tk.Label(right_panel, textvariable=self.status, anchor="w", bg='#e0e0e0') + status_label.pack(fill=tk.X, side=tk.BOTTOM) + + # 绑定事件 + self.canvas.bind("", self.on_move) + self.canvas.bind("", self.on_left_click) + self.canvas.bind("", self.on_left_drag) + self.canvas.bind("", self.on_left_release) + self.canvas.bind("", self.on_right_click) # 右键开始拖拽 + self.canvas.bind("", self.on_right_drag) # 右键拖拽 + self.canvas.bind("", self.on_right_release) + self.canvas.bind("", self.on_mousewheel) # Windows/Linux + self.canvas.bind("", self.on_mousewheel) # Linux + self.canvas.bind("", self.on_mousewheel) # Linux + self.canvas.bind("", self.on_mousewheel_ctrl) # Ctrl+滚轮 + + # 添加拖放支持 + if HAS_DND: + self.root.drop_target_register(DND_FILES) + self.root.dnd_bind('<>', self.on_drop) + self.canvas.drop_target_register(DND_FILES) + self.canvas.dnd_bind('<>', self.on_drop) + + def _create_control_panel(self, parent): + """创建控制面板""" + # 标题 + title_label = tk.Label(parent, text="区域选择器", font=("Arial", 14, "bold"), bg='#f0f0f0') + title_label.pack(pady=10) + + # 当前选择信息 + selection_frame = tk.LabelFrame(parent, text="当前选择", bg='#f0f0f0') + selection_frame.pack(fill=tk.X, padx=5, pady=5) + + self.selection_info = tk.StringVar() + self.selection_info.set("未选择区域") + selection_label = tk.Label(selection_frame, textvariable=self.selection_info, + anchor="w", bg='#f0f0f0', justify=tk.LEFT) + selection_label.pack(fill=tk.X, padx=5, pady=5) + + # 分析结果 + result_frame = tk.LabelFrame(parent, text="分析结果", bg='#f0f0f0') + result_frame.pack(fill=tk.X, padx=5, pady=5) + + self.result_info = tk.Text(result_frame, height=8, width=35, font=("Courier", 9)) + scrollbar = tk.Scrollbar(result_frame, command=self.result_info.yview) + self.result_info.config(yscrollcommand=scrollbar.set) + self.result_info.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) + scrollbar.pack(side=tk.RIGHT, fill=tk.Y) + + # 按钮区域 + button_frame = tk.Frame(parent, bg='#f0f0f0') + button_frame.pack(fill=tk.X, padx=5, pady=5) + + tk.Button(button_frame, text="分析区域", command=self.analyze_region, + bg='#4CAF50', fg='white').pack(fill=tk.X, pady=2) + tk.Button(button_frame, text="清除选择", command=self.clear_selection, + bg='#f44336', fg='white').pack(fill=tk.X, pady=2) + tk.Button(button_frame, text="显示所有", command=self.show_all_regions, + bg='#2196F3', fg='white').pack(fill=tk.X, pady=2) + tk.Button(button_frame, text="清除所有", command=self.clear_all_regions, + bg='#FF9800', fg='white').pack(fill=tk.X, pady=2) + + def _refresh_file_list(self, current: Path) -> None: + """刷新当前目录下的图片列表""" + exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"} + try: + files = [p for p in current.parent.iterdir() if p.suffix.lower() in exts and p.is_file()] + files.sort() + self.file_list = files + try: + self.file_idx = self.file_list.index(current) + except ValueError: + self.file_idx = -1 + except Exception: + self.file_list = [] + self.file_idx = -1 + + def set_image(self, image_path: Path, update_list: bool = False) -> None: + """设置当前图片""" + image_path = Path(image_path) + self.image_path = image_path + self.img = Image.open(image_path).convert("RGB") + self.w, self.h = self.img.size + + if update_list: + self._refresh_file_list(image_path) + + # 清除之前的选择 + self.clear_selection() + self.clear_all_regions() + + # 显示用缩放 + self._update_display() + self.root.title(f"区域选择器: {image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") + + def open_dialog(self) -> bool: + """打开文件选择对话框""" + initial_dir = None + try: + if self.image_path and self.image_path.parent.exists(): + initial_dir = str(self.image_path.parent) + except Exception: + initial_dir = None + + filename = filedialog.askopenfilename( + title="选择图片", + initialdir=initial_dir, + filetypes=[ + ("Images", "*.png;*.jpg;*.jpeg;*.bmp;*.webp"), + ("All files", "*.*"), + ], + ) + if not filename: + return False + try: + self.set_image(Path(filename), update_list=True) + return True + except Exception as e: + messagebox.showerror("错误", f"打开图片失败: {e}") + return False + + def _to_image_xy(self, event) -> tuple[int, int]: + """将canvas坐标转换为图像坐标""" + if not self.img or self.w <= 0 or self.h <= 0: + return 0, 0 + # 考虑缩放和滚动偏移 + canvas_x = event.x + self.scroll_offset_x + canvas_y = event.y + self.scroll_offset_y + x = int(clamp(canvas_x / self.scale, 0, self.w - 1)) + y = int(clamp(canvas_y / self.scale, 0, self.h - 1)) + return x, y + + def _to_canvas_xy(self, img_x: int, img_y: int) -> tuple[int, int]: + """将图像坐标转换为canvas坐标""" + canvas_x = img_x * self.scale - self.scroll_offset_x + canvas_y = img_y * self.scale - self.scroll_offset_y + return int(canvas_x), int(canvas_y) + + def _update_display(self): + """更新显示""" + if not self.img: + return + + # 获取canvas实际大小 + self.root.update_idletasks() + canvas_w = max(1, self.canvas.winfo_width()) + canvas_h = max(1, self.canvas.winfo_height()) + + # 计算显示尺寸 + self.disp_w = int(self.w * self.scale) + self.disp_h = int(self.h * self.scale) + + # 限制滚动偏移 + max_offset_x = max(0, self.disp_w - canvas_w) + max_offset_y = max(0, self.disp_h - canvas_h) + self.scroll_offset_x = max(0, min(self.scroll_offset_x, max_offset_x)) + self.scroll_offset_y = max(0, min(self.scroll_offset_y, max_offset_y)) + + # 生成显示图像 + try: + resample = Image.Resampling.BICUBIC if hasattr(Image, 'Resampling') else Image.BICUBIC + except Exception: + resample = Image.BICUBIC + + if self.scale != 1.0: + # 如果放大,只显示可见区域以提高性能 + if self.scale > 1.0 and canvas_w < self.disp_w and canvas_h < self.disp_h: + # 计算原图中要显示的区域 + src_x1 = max(0, int(self.scroll_offset_x / self.scale)) + src_y1 = max(0, int(self.scroll_offset_y / self.scale)) + src_x2 = min(self.w, src_x1 + int(canvas_w / self.scale) + 2) + src_y2 = min(self.h, src_y1 + int(canvas_h / self.scale) + 2) + + # 裁剪并放大 + crop_img = self.img.crop((src_x1, src_y1, src_x2, src_y2)) + crop_w, crop_h = crop_img.size + disp_img = crop_img.resize((int(crop_w * self.scale), int(crop_h * self.scale)), resample) + else: + # 缩小或完全显示 + disp_img = self.img.resize((self.disp_w, self.disp_h), resample) + else: + disp_img = self.img + + self.tk_img = ImageTk.PhotoImage(disp_img) + + # 更新canvas滚动区域 + self.canvas.config(scrollregion=(0, 0, self.disp_w, self.disp_h)) + + # 更新图像位置 + self.canvas.coords(self._canvas_image_id, -self.scroll_offset_x, -self.scroll_offset_y) + self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img) + + # 重新绘制选择矩形 + self._redraw_selection_rect() + + # 更新标题 + if self.image_path: + self.root.title(f"区域选择器: {self.image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") + + def _redraw_selection_rect(self): + """重新绘制选择矩形""" + # 删除旧的矩形 + if self.selection_canvas_id: + self.canvas.delete(self.selection_canvas_id) + self.selection_canvas_id = None + + # 绘制新的矩形 + if self.selection_rect: + x1, y1, x2, y2 = self.selection_rect + canvas_x1, canvas_y1 = self._to_canvas_xy(x1, y1) + canvas_x2, canvas_y2 = self._to_canvas_xy(x2, y2) + + self.selection_canvas_id = self.canvas.create_rectangle( + canvas_x1, canvas_y1, canvas_x2, canvas_y2, + outline='red', width=2, dash=(5, 5) + ) + + def on_move(self, event): + """鼠标移动事件""" + if self.is_selecting: + # 更新选择矩形 + self.select_end_x, self.select_end_y = self._to_image_xy(event) + self._update_selection_rect() + elif self.is_dragging: + # 拖拽平移 + dx = event.x - self.drag_start_x + dy = event.y - self.drag_start_y + self.scroll_offset_x -= dx + self.scroll_offset_y -= dy + self.drag_start_x = event.x + self.drag_start_y = event.y + self._update_display() + + def on_left_click(self, event): + """左键点击""" + if not self.img: + return + + img_x, img_y = self._to_image_xy(event) + self.select_start_x = img_x + self.select_start_y = img_y + self.select_end_x = img_x + self.select_end_y = img_y + self.is_selecting = True + self._update_selection_rect() + + def on_left_drag(self, event): + """左键拖拽""" + if self.is_selecting: + self.select_end_x, self.select_end_y = self._to_image_xy(event) + self._update_selection_rect() + + def on_left_release(self, event): + """左键释放""" + if self.is_selecting: + self.select_end_x, self.select_end_y = self._to_image_xy(event) + self._update_selection_rect() + self.is_selecting = False + + # 更新选择信息 + self._update_selection_info() + + def on_right_click(self, event): + """右键点击开始拖拽""" + self.drag_start_x = event.x + self.drag_start_y = event.y + self.is_dragging = True + + def on_right_drag(self, event): + """右键拖拽""" + if self.is_dragging: + dx = event.x - self.drag_start_x + dy = event.y - self.drag_start_y + self.scroll_offset_x -= dx + self.scroll_offset_y -= dy + self.drag_start_x = event.x + self.drag_start_y = event.y + self._update_display() + + def on_right_release(self, event): + """右键释放""" + self.is_dragging = False + + def _update_selection_rect(self): + """更新选择矩形""" + x1 = min(self.select_start_x, self.select_end_x) + y1 = min(self.select_start_y, self.select_end_y) + x2 = max(self.select_start_x, self.select_end_x) + y2 = max(self.select_start_y, self.select_end_y) + + self.selection_rect = (x1, y1, x2, y2) + self._redraw_selection_rect() + + def _update_selection_info(self): + """更新选择信息显示""" + if self.selection_rect: + x1, y1, x2, y2 = self.selection_rect + width = x2 - x1 + 1 + height = y2 - y1 + 1 + self.selection_info.set(f"区域: ({x1}, {y1}) - ({x2}, {y2})\n尺寸: {width}x{height}") + else: + self.selection_info.set("未选择区域") + + def analyze_region(self): + """分析当前选择的区域""" + if not self.img or not self.selection_rect: + messagebox.showwarning("警告", "请先选择一个区域") + return + + x1, y1, x2, y2 = self.selection_rect + + # 统计白色像素 + white_count = 0 + total_pixels = 0 + region_img = self.img.crop((x1, y1, x2+1, y2+1)) + + # 将图像转换为numpy数组进行分析 + import numpy as np + region_array = np.array(region_img) + + # 计算白色像素(RGB值都接近255的像素) + white_threshold = 240 # 白色阈值 + white_pixels = np.all(region_array >= white_threshold, axis=2) + white_count = np.sum(white_pixels) + total_pixels = region_array.shape[0] * region_array.shape[1] + + white_ratio = white_count / total_pixels if total_pixels > 0 else 0 + + # 生成结果文本 + result_text = f"区域分析结果:\n" + result_text += f"坐标: ({x1}, {y1}) - ({x2}, {y2})\n" + result_text += f"尺寸: {(x2-x1+1)}x{(y2-y1+1)}\n" + result_text += f"总像素: {total_pixels}\n" + result_text += f"白色像素: {white_count}\n" + result_text += f"白色比例: {white_ratio:.3f}\n" + result_text += f"置信度: {(1 - abs(white_ratio - 0.5) * 2):.3f}" + # 保存到结果列表 + region_data = { + 'coordinates': (x1, y1, x2, y2), + 'size': (x2-x1+1, y2-y1+1), + 'total_pixels': total_pixels, + 'white_pixels': white_count, + 'white_ratio': white_ratio, + 'image_path': str(self.image_path) if self.image_path else None + } + + self.white_pixel_regions.append(region_data) + + # 显示结果 + self.result_info.delete(1.0, tk.END) + self.result_info.insert(tk.END, result_text) + + # 打印到控制台 + print(f"\n=== 区域分析结果 ===") + print(result_text) + print(f"结果已保存到内存中 (共{len(self.white_pixel_regions)}个区域)") + + def clear_selection(self): + """清除当前选择""" + self.selection_rect = None + if self.selection_canvas_id: + self.canvas.delete(self.selection_canvas_id) + self.selection_canvas_id = None + self._update_selection_info() + + def clear_all_regions(self): + """清除所有保存的区域""" + self.white_pixel_regions.clear() + self.result_info.delete(1.0, tk.END) + self.result_info.insert(tk.END, "已清除所有区域数据") + + def show_all_regions(self): + """显示所有保存的区域""" + if not self.white_pixel_regions: + messagebox.showinfo("信息", "没有保存的区域数据") + return + + result_text = f"所有区域数据 (共{len(self.white_pixel_regions)}个):\n\n" + for i, region in enumerate(self.white_pixel_regions, 1): + x1, y1, x2, y2 = region['coordinates'] + result_text += f"区域 {i}:\n" + result_text += f" 坐标: ({x1}, {y1}) - ({x2}, {y2})\n" + result_text += f" 尺寸: {region['size'][0]}x{region['size'][1]}\n" + result_text += f" 白色像素: {region['white_pixels']}/{region['total_pixels']} " + result_text += f"({region['white_ratio']:.3f})\n\n" + + self.result_info.delete(1.0, tk.END) + self.result_info.insert(tk.END, result_text) + + def save_regions(self): + """保存区域数据到文件""" + if not self.white_pixel_regions: + messagebox.showwarning("警告", "没有区域数据可以保存") + return + + filename = filedialog.asksaveasfilename( + title="保存区域数据", + defaultextension=".json", + filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")] + ) + + if filename: + try: + with open(filename, 'w', encoding='utf-8') as f: + json.dump(self.white_pixel_regions, f, indent=2, ensure_ascii=False) + messagebox.showinfo("成功", f"区域数据已保存到: {filename}") + except Exception as e: + messagebox.showerror("错误", f"保存失败: {e}") + + def load_regions(self): + """从文件加载区域数据""" + filename = filedialog.askopenfilename( + title="加载区域数据", + filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")] + ) + + if filename: + try: + with open(filename, 'r', encoding='utf-8') as f: + self.white_pixel_regions = json.load(f) + messagebox.showinfo("成功", f"已加载 {len(self.white_pixel_regions)} 个区域数据") + self.show_all_regions() + except Exception as e: + messagebox.showerror("错误", f"加载失败: {e}") + + def on_mousewheel(self, event): + """鼠标滚轮缩放""" + if event.state & 0x4: # Ctrl键按下 + return # 交给on_mousewheel_ctrl处理 + + delta = 0 + if event.num == 4 or event.delta > 0: # 向上滚动 + delta = 1 + elif event.num == 5 or event.delta < 0: # 向下滚动 + delta = -1 + + if delta != 0: + img_x, img_y = self._to_image_xy(event) + self._zoom_at_point(img_x, img_y, delta * 0.1) + + def on_mousewheel_ctrl(self, event): + """Ctrl+滚轮缩放""" + delta = 0 + if event.num == 4 or event.delta > 0: # 向上滚动 + delta = 1 + elif event.num == 5 or event.delta < 0: # 向下滚动 + delta = -1 + + if delta != 0: + img_x, img_y = self._to_image_xy(event) + self._zoom_at_point(img_x, img_y, delta * 0.1) + + def _zoom_at_point(self, img_x: int, img_y: int, delta: float): + """在指定点缩放""" + if not self.img: + return + + old_scale = self.scale + new_scale = clamp(old_scale + delta, self.min_scale, self.max_scale) + + if abs(new_scale - old_scale) < 0.01: + return + + # 计算缩放中心点在图像中的位置 + # 调整滚动偏移,使缩放点保持在屏幕上的同一位置 + scale_ratio = new_scale / old_scale + self.scroll_offset_x = img_x * new_scale - (img_x * old_scale - self.scroll_offset_x) * scale_ratio + self.scroll_offset_y = img_y * new_scale - (img_y * old_scale - self.scroll_offset_y) * scale_ratio + + self.scale = new_scale + self._update_display() + + def zoom_in(self): + """放大""" + if not self.img: + return + center_x = self.w // 2 + center_y = self.h // 2 + self._zoom_at_point(center_x, center_y, 0.2) + + def zoom_out(self): + """缩小""" + if not self.img: + return + center_x = self.w // 2 + center_y = self.h // 2 + self._zoom_at_point(center_x, center_y, -0.2) + + def reset_zoom(self): + """重置缩放""" + if not self.img: + return + self.scale = 1.0 + self.scroll_offset_x = 0 + self.scroll_offset_y = 0 + self._update_display() + + def fit_to_window(self): + """适应窗口大小""" + if not self.img: + return + + self.root.update_idletasks() + canvas_w = self.canvas.winfo_width() + canvas_h = self.canvas.winfo_height() + + if canvas_w > 0 and canvas_h > 0: + scale_x = canvas_w / self.w + scale_y = canvas_h / self.h + self.scale = min(scale_x, scale_y) * 0.9 # 留一点边距 + self.scroll_offset_x = 0 + self.scroll_offset_y = 0 + self._update_display() + + def _load_by_index(self, idx: int) -> bool: + """按索引加载图片""" + if not self.file_list: + return False + idx = idx % len(self.file_list) + try: + self.set_image(self.file_list[idx], update_list=False) + self.file_idx = idx + return True + except Exception as e: + messagebox.showerror("错误", f"切换图片失败: {e}") + return False + + def next_image(self) -> None: + """下一张图片""" + if self.file_list: + if self._load_by_index(self.file_idx + 1): + self.status.set(f"下一张: {self.image_path.name if self.image_path else ''}") + + def prev_image(self) -> None: + """上一张图片""" + if self.file_list: + if self._load_by_index(self.file_idx - 1): + self.status.set(f"上一张: {self.image_path.name if self.image_path else ''}") + + def on_drop(self, event) -> None: + """处理拖放事件""" + if not HAS_DND: + return + + try: + # 获取拖放的文件路径 + files = self.root.tk.splitlist(event.data) + if not files: + return + + # 取第一个文件 + file_path = files[0] + # 移除可能的花括号(Windows 拖放可能包含) + file_path = file_path.strip('{}') + + path = Path(file_path) + if not path.exists(): + self.status.set(f"文件不存在: {path}") + return + + # 检查是否为图片文件 + exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"} + if path.suffix.lower() not in exts: + self.status.set(f"不是支持的图片格式: {path.suffix}") + return + + # 加载图片 + self.set_image(path, update_list=True) + self.status.set(f"已加载: {path.name}") + except Exception as e: + self.status.set(f"拖放失败: {e}") + + def run(self): + """运行主循环""" + self.root.mainloop() + + +def main(argv: list[str]) -> int: + """主函数""" + p: Optional[Path] = None + if len(argv) >= 2: + p = Path(argv[1]).expanduser() + if p and not p.is_absolute(): + p = (Path(__file__).resolve().parent.parent / p).resolve() + if p and not p.exists(): + print(f"找不到图片: {p}") + print("将弹出文件选择框,请手动选择图片。") + p = None + else: + print("未传入图片路径,将弹出文件选择框。") + + RegionSelector(p).run() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/tools/simple_region_selector.py b/tools/simple_region_selector.py new file mode 100644 index 0000000..6d87eb3 --- /dev/null +++ b/tools/simple_region_selector.py @@ -0,0 +1,699 @@ +#!/usr/bin/env python3 +""" +简化版区域选择器 - 专门用于抖音挂机项目 +用于选择直播间图标区域并统计白色像素 +""" + +import sys +import os +from pathlib import Path +from typing import Optional +import json + +try: + import tkinter as tk + from tkinter import filedialog, messagebox +except ImportError: + print("错误: tkinter不可用。请确保Python安装时包含了tkinter。") + print("在Windows上,请重新安装Python并勾选'tcl/tk and IDLE'选项。") + sys.exit(1) + +from PIL import Image, ImageTk, ImageDraw +import numpy as np + + +class SimpleRegionSelector: + def __init__(self, image_path=None): + self.image_path = image_path + self.img = None + self.photo = None + self.scale = 1.0 + self.offset_x = 0 + self.offset_y = 0 + + # 选择相关 + self.polygon_points = [] # 多边形顶点列表 + self.polygon_id = None # 画布上的多边形ID + + # 缩放和平移相关 + self.scale = 1.0 + self.min_scale = 0.1 + self.max_scale = 10.0 + self.offset_x = 0 + self.offset_y = 0 + self.is_dragging = False + self.drag_start_x = 0 + self.drag_start_y = 0 + + # 结果存储 + self.regions = [] + + self.setup_ui() + + if image_path: + self.load_image(image_path) + else: + self.ask_for_image() + + def setup_ui(self): + """设置用户界面""" + self.root = tk.Tk() + self.root.title("抖音区域选择器 - 白色像素统计") + self.root.geometry("1000x700") + + # 菜单栏 + menubar = tk.Menu(self.root) + file_menu = tk.Menu(menubar, tearoff=0) + file_menu.add_command(label="打开图片", command=self.ask_for_image, accelerator="Ctrl+O") + file_menu.add_command(label="保存区域", command=self.save_regions, accelerator="Ctrl+S") + file_menu.add_command(label="加载区域", command=self.load_regions, accelerator="Ctrl+L") + file_menu.add_separator() + file_menu.add_command(label="退出", command=self.root.quit) + menubar.add_cascade(label="文件", menu=file_menu) + + edit_menu = tk.Menu(menubar, tearoff=0) + edit_menu.add_command(label="清除选择", command=self.clear_selection, accelerator="Del") + edit_menu.add_command(label="分析区域", command=self.analyze_region, accelerator="Enter") + edit_menu.add_command(label="显示所有", command=self.show_all_regions) + edit_menu.add_command(label="清除所有", command=self.clear_all_regions) + menubar.add_cascade(label="编辑", menu=edit_menu) + + # 移除视图菜单,不需要放大缩小功能 + + # 视图菜单 + view_menu = tk.Menu(menubar, tearoff=0) + view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+") + view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="-") + view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0") + view_menu.add_command(label="适应窗口", command=self.fit_to_window, accelerator="Ctrl+F") + menubar.add_cascade(label="视图", menu=view_menu) + + self.root.config(menu=menubar) + + # 绑定快捷键 + self.root.bind("", lambda e: self.ask_for_image()) + self.root.bind("", lambda e: self.save_regions()) + self.root.bind("", lambda e: self.load_regions()) + self.root.bind("", lambda e: self.clear_selection()) + self.root.bind("", lambda e: self.analyze_region()) + # 视图相关快捷键 + self.root.bind("", lambda e: self.zoom_in()) + self.root.bind("", lambda e: self.zoom_in()) + self.root.bind("", lambda e: self.zoom_out()) + self.root.bind("", lambda e: self.reset_zoom()) + self.root.bind("", lambda e: self.fit_to_window()) + + # 主框架 + main_frame = tk.Frame(self.root) + main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) + + # 左侧控制面板 + left_panel = tk.Frame(main_frame, width=250, bg='#f0f0f0') + left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0,5)) + + # 右侧画布区域 + right_panel = tk.Frame(main_frame) + right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True) + + # 控制面板内容 + self.setup_control_panel(left_panel) + + # 画布 + self.canvas = tk.Canvas(right_panel, bg='#404040') + self.canvas.pack(fill=tk.BOTH, expand=True) + + # 状态栏 + self.status_var = tk.StringVar() + self.status_var.set("请打开图片,然后用滚轮缩放、右键拖拽调整视图,依次点击多个点围成x图标区域") + status_bar = tk.Label(right_panel, textvariable=self.status_var, + anchor="w", bg='#e0e0e0', relief=tk.SUNKEN) + status_bar.pack(fill=tk.X, side=tk.BOTTOM) + + # 绑定画布事件 + self.canvas.bind("", self.on_canvas_click) # 左键添加点 + self.canvas.bind("", self.on_canvas_right_click) # 右键完成多边形 + self.canvas.bind("", self.on_canvas_drag) # 右键拖拽 + self.canvas.bind("", self.on_mousewheel) # 滚轮缩放 + self.root.bind("", self.finish_polygon) # 空格键完成多边形 + self.root.bind("", self.remove_last_point) # 退格键删除最后一个点 + + def setup_control_panel(self, parent): + """设置控制面板""" + # 标题 + title = tk.Label(parent, text="区域选择器", font=("Arial", 12, "bold"), bg='#f0f0f0') + title.pack(pady=10) + + # 当前选择信息 + select_frame = tk.LabelFrame(parent, text="当前选择", bg='#f0f0f0') + select_frame.pack(fill=tk.X, padx=5, pady=5) + + self.select_info = tk.StringVar() + self.select_info.set("未选择区域") + tk.Label(select_frame, textvariable=self.select_info, anchor="w", bg='#f0f0f0', + justify=tk.LEFT, wraplength=220).pack(fill=tk.X, padx=5, pady=5) + + # 分析结果 + result_frame = tk.LabelFrame(parent, text="分析结果", bg='#f0f0f0') + result_frame.pack(fill=tk.X, padx=5, pady=5) + + self.result_text = tk.Text(result_frame, height=10, width=25, font=("Courier", 9)) + scrollbar = tk.Scrollbar(result_frame, command=self.result_text.yview) + self.result_text.config(yscrollcommand=scrollbar.set) + self.result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) + scrollbar.pack(side=tk.RIGHT, fill=tk.Y) + + # 按钮区域 + btn_frame = tk.Frame(parent, bg='#f0f0f0') + btn_frame.pack(fill=tk.X, padx=5, pady=5) + + tk.Button(btn_frame, text="分析区域", command=self.analyze_region, + bg='#4CAF50', fg='white').pack(fill=tk.X, pady=2) + tk.Button(btn_frame, text="清除选择", command=self.clear_selection, + bg='#f44336', fg='white').pack(fill=tk.X, pady=2) + tk.Button(btn_frame, text="显示所有", command=self.show_all_regions, + bg='#2196F3', fg='white').pack(fill=tk.X, pady=2) + tk.Button(btn_frame, text="清除所有", command=self.clear_all_regions, + bg='#FF9800', fg='white').pack(fill=tk.X, pady=2) + + # 添加使用说明 + help_frame = tk.LabelFrame(parent, text="多边形选择说明", bg='#f0f0f0') + help_frame.pack(fill=tk.X, padx=5, pady=5) + + help_text = """操作步骤: +1. 打开图片 +2. 滚轮缩放,右键拖拽调整视图 +3. 依次点击多个点围成x图标 +4. 右键或按Space完成选择 +5. 按Enter分析区域 + +快捷键: +Space: 完成多边形 +BackSpace: 删除最后一个点 ++/-: 放大缩小 +Ctrl+0: 重置缩放 +Ctrl+F: 适应窗口""" + tk.Label(help_frame, text=help_text, anchor="w", bg='#f0f0f0', + justify=tk.LEFT, font=("Arial", 9)).pack(fill=tk.X, padx=5, pady=5) + + def ask_for_image(self): + """选择图片文件""" + filetypes = [("图片文件", "*.png *.jpg *.jpeg *.bmp *.webp"), ("所有文件", "*.*")] + filename = filedialog.askopenfilename(title="选择图片", filetypes=filetypes) + + if filename: + self.load_image(filename) + + def load_image(self, path): + """加载图片""" + try: + self.image_path = path + self.img = Image.open(path).convert("RGB") + self.w, self.h = self.img.size + self.scale = 1.0 + self.offset_x = 0 + self.offset_y = 0 + self.clear_selection() + self.clear_all_regions() + self.update_display() + self.root.title(f"多边形区域选择器 - {Path(path).name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") + self.status_var.set("图片已加载,请依次点击多个点围成x图标区域") + except Exception as e: + messagebox.showerror("错误", f"加载图片失败: {e}") + + def update_display(self): + """更新显示""" + if not self.img: + return + + # 获取canvas尺寸 + canvas_w = self.canvas.winfo_width() + canvas_h = self.canvas.winfo_height() + + if canvas_w <= 1 or canvas_h <= 1: + return + + # 计算显示尺寸 + disp_w = int(self.w * self.scale) + disp_h = int(self.h * self.scale) + + # 缩放图片 + if self.scale != 1.0: + try: + resample = Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS + except: + resample = Image.BICUBIC + resized = self.img.resize((disp_w, disp_h), resample) + else: + resized = self.img + + self.photo = ImageTk.PhotoImage(resized) + self.canvas.config(scrollregion=(0, 0, disp_w, disp_h)) + self.canvas.delete("image") + self.canvas.create_image(-self.offset_x, -self.offset_y, anchor=tk.NW, + image=self.photo, tags="image") + + # 重新绘制多边形 + self.redraw_polygon() + + # 更新标题 + if self.image_path: + self.root.title(f"多边形区域选择器 - {Path(self.image_path).name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") + + def redraw_polygon(self): + """重新绘制多边形""" + self.canvas.delete("polygon") + + if not self.polygon_points: + return + + # 绘制多边形边线 + if len(self.polygon_points) >= 2: + canvas_points = [] + for img_x, img_y in self.polygon_points: + canvas_x = img_x * self.scale - self.offset_x + canvas_y = img_y * self.scale - self.offset_y + canvas_points.extend([canvas_x, canvas_y]) + + # 如果多边形已完成,绘制闭合多边形 + if len(self.polygon_points) >= 3: + # 连接最后一个点到第一个点 + first_x = self.polygon_points[0][0] * self.scale - self.offset_x + first_y = self.polygon_points[0][1] * self.scale - self.offset_y + canvas_points.extend([first_x, first_y]) + + # 绘制填充的多边形 + self.polygon_id = self.canvas.create_polygon( + canvas_points, + outline='red', fill='red', stipple='gray50', + width=2, tags="polygon" + ) + else: + # 绘制开放的多边形线条 + self.polygon_id = self.canvas.create_line( + canvas_points, + fill='red', width=2, tags="polygon" + ) + + # 绘制顶点 + for i, (img_x, img_y) in enumerate(self.polygon_points): + canvas_x = img_x * self.scale - self.offset_x + canvas_y = img_y * self.scale - self.offset_y + + # 绘制点(根据缩放调整大小) + radius = max(3, int(3 / self.scale)) if self.scale > 0 else 3 + self.canvas.create_oval( + canvas_x - radius, canvas_y - radius, + canvas_x + radius, canvas_y + radius, + fill='blue', outline='white', width=1, tags="polygon" + ) + + # 绘制点编号(根据缩放调整字体大小) + font_size = max(8, int(10 / self.scale)) if self.scale > 0 else 8 + self.canvas.create_text( + canvas_x, canvas_y - radius - 5, + text=str(i+1), fill='white', font=('Arial', font_size, 'bold'), + tags="polygon" + ) + + def canvas_to_image_coords(self, canvas_x, canvas_y): + """画布坐标转图片坐标""" + if self.scale == 0: + return 0, 0 + img_x = int((canvas_x + self.offset_x) / self.scale) + img_y = int((canvas_y + self.offset_y) / self.scale) + return max(0, min(img_x, self.w-1)), max(0, min(img_y, self.h-1)) + + def on_canvas_click(self, event): + """画布点击 - 添加多边形顶点""" + if not self.img: + return + + img_x, img_y = self.canvas_to_image_coords(event.x, event.y) + + # 添加新点到多边形 + self.polygon_points.append((img_x, img_y)) + self.redraw_polygon() + + point_num = len(self.polygon_points) + self.status_var.set(f"已添加第{point_num}个点: ({img_x}, {img_y}) | 右键或按空格完成多边形") + print(f"点 {point_num}: ({img_x}, {img_y})") + + def on_canvas_right_click(self, event): + """右键点击 - 完成多边形""" + self.finish_polygon() + + def finish_polygon(self, event=None): + """完成多边形选择""" + if len(self.polygon_points) < 3: + messagebox.showwarning("警告", "需要至少3个点才能构成多边形") + return + + # 关闭多边形(连接最后一个点到第一个点) + self.redraw_polygon() + self.update_selection_info() + + point_count = len(self.polygon_points) + self.status_var.set(f"多边形已完成 ({point_count}个顶点),按Enter分析区域") + print(f"多边形完成,共{point_count}个顶点") + + def remove_last_point(self, event=None): + """删除最后一个点""" + if self.polygon_points: + removed_point = self.polygon_points.pop() + self.redraw_polygon() + point_count = len(self.polygon_points) + if point_count > 0: + self.status_var.set(f"已删除最后一个点,还剩{point_count}个点") + print(f"删除点: {removed_point},还剩{point_count}个点") + else: + self.status_var.set("已清除所有点,请重新选择") + print("已清除所有点") + else: + self.status_var.set("没有点可以删除") + + def on_mousewheel(self, event): + """鼠标滚轮缩放""" + if not self.img: + return + + # Windows用event.delta,Linux用event.num + if event.delta > 0 or event.num == 4: # 放大 + self.zoom_at_point(event.x, event.y, 1.2) + elif event.delta < 0 or event.num == 5: # 缩小 + self.zoom_at_point(event.x, event.y, 0.8) + + def on_canvas_drag(self, event): + """右键拖拽图片""" + if not self.img: + return + + if not self.is_dragging: + self.is_dragging = True + self.drag_start_x = event.x + self.drag_start_y = event.y + return + + # 计算拖拽距离 + dx = event.x - self.drag_start_x + dy = event.y - self.drag_start_y + + # 更新偏移 + self.offset_x += dx + self.offset_y += dy + + # 限制拖拽范围 + self.limit_offsets() + + # 更新拖拽起始点 + self.drag_start_x = event.x + self.drag_start_y = event.y + + # 重新显示 + self.update_display() + self.status_var.set(f"拖拽中... 偏移: ({self.offset_x:.0f}, {self.offset_y:.0f})") + + def zoom_at_point(self, canvas_x, canvas_y, factor): + """在指定点缩放""" + if not self.img: + return + + old_scale = self.scale + new_scale = max(self.min_scale, min(self.max_scale, old_scale * factor)) + + if abs(new_scale - old_scale) < 0.01: + return + + # 计算缩放中心点在图像中的位置 + img_x = (canvas_x + self.offset_x) / old_scale + img_y = (canvas_y + self.offset_y) / old_scale + + # 更新缩放 + self.scale = new_scale + + # 调整偏移使缩放点保持在原位 + self.offset_x = img_x * new_scale - canvas_x + self.offset_y = img_y * new_scale - canvas_y + + # 限制偏移范围 + self.limit_offsets() + + # 重新显示 + self.update_display() + self.status_var.set(f"缩放: {self.scale:.2f}x") + + def limit_offsets(self): + """限制偏移范围,防止图片拖拽出视野""" + if not self.img: + return + + canvas_w = self.canvas.winfo_width() + canvas_h = self.canvas.winfo_height() + + if canvas_w <= 1 or canvas_h <= 1: + return + + disp_w = self.w * self.scale + disp_h = self.h * self.scale + + # 计算最大偏移 + max_offset_x = max(0, disp_w - canvas_w) + max_offset_y = max(0, disp_h - canvas_h) + + # 限制偏移 + self.offset_x = max(-canvas_w // 2, min(self.offset_x, max_offset_x + canvas_w // 2)) + self.offset_y = max(-canvas_h // 2, min(self.offset_y, max_offset_y + canvas_h // 2)) + + def zoom_in(self): + """放大""" + if self.img: + canvas_w = self.canvas.winfo_width() + canvas_h = self.canvas.winfo_height() + center_x = canvas_w // 2 + center_y = canvas_h // 2 + self.zoom_at_point(center_x, center_y, 1.5) + + def zoom_out(self): + """缩小""" + if self.img: + canvas_w = self.canvas.winfo_width() + canvas_h = self.canvas.h // 2 + center_x = canvas_w // 2 + center_y = canvas_h // 2 + self.zoom_at_point(center_x, center_y, 0.67) + + def reset_zoom(self): + """重置缩放""" + if self.img: + self.scale = 1.0 + self.offset_x = 0 + self.offset_y = 0 + self.update_display() + self.status_var.set("已重置缩放") + + def fit_to_window(self): + """适应窗口""" + if not self.img: + return + + self.canvas.update() + canvas_w = self.canvas.winfo_width() + canvas_h = self.canvas.winfo_height() + + if canvas_w > 0 and canvas_h > 0: + scale_x = canvas_w / self.w + scale_y = canvas_h / self.h + self.scale = min(scale_x, scale_y) * 0.9 + self.offset_x = 0 + self.offset_y = 0 + self.update_display() + self.status_var.set(f"适应窗口,缩放: {self.scale:.2f}x") + + def update_selection_info(self): + """更新选择信息""" + if self.polygon_points: + point_count = len(self.polygon_points) + if point_count >= 3: + self.select_info.set(f"多边形: {point_count}个顶点\n状态: 已完成") + else: + self.select_info.set(f"多边形: {point_count}个顶点\n状态: 未完成(需要至少3个点)") + else: + self.select_info.set("未选择区域") + + + def clear_selection(self): + """清除选择""" + self.polygon_points = [] + self.canvas.delete("polygon") + self.update_selection_info() + if self.img: + self.status_var.set("已清除多边形,请重新依次点击多个点围成区域") + else: + self.status_var.set("请先打开图片") + + def analyze_region(self): + """分析多边形区域""" + if not self.img or len(self.polygon_points) < 3: + messagebox.showwarning("警告", "请先选择一个完整的多边形区域(至少3个点)") + return + + # 创建多边形mask + mask = Image.new('L', (self.w, self.h), 0) + draw = ImageDraw.Draw(mask) + + # 将多边形点转换为整数坐标 + polygon_coords = [(int(x), int(y)) for x, y in self.polygon_points] + + # 绘制多边形(填充为白色) + draw.polygon(polygon_coords, fill=255) + + # 将mask转换为numpy数组 + mask_array = np.array(mask) + + # 获取原始图像的像素数据 + img_array = np.array(self.img) + + # 计算多边形内部的总像素数 + total_pixels = np.sum(mask_array > 0) + + if total_pixels == 0: + messagebox.showwarning("警告", "多边形区域为空,请重新选择") + return + + # 计算多边形内部的白色像素 + white_count = 0 + for y in range(self.h): + for x in range(self.w): + if mask_array[y, x] > 0: # 在多边形内部 + r, g, b = img_array[y, x] + if r >= 240 and g >= 240 and b >= 240: # 白色阈值 + white_count += 1 + + white_ratio = white_count / total_pixels if total_pixels > 0 else 0 + + # 计算置信度(基于与0.5的距离) + confidence = 1 - abs(white_ratio - 0.5) * 2 + + # 保存结果 + region_data = { + 'polygon_points': self.polygon_points.copy(), + 'total_pixels': total_pixels, + 'white_pixels': white_count, + 'white_ratio': white_ratio, + 'confidence': confidence, + 'image_path': str(self.image_path) if self.image_path else None + } + + self.regions.append(region_data) + + # 显示结果 + result_text = f"多边形区域分析结果:\n" + result_text += f"顶点数量: {len(self.polygon_points)}\n" + result_text += f"顶点坐标:\n" + for i, (x, y) in enumerate(self.polygon_points): + result_text += f" {i+1}: ({x:.0f}, {y:.0f})\n" + result_text += f"总像素: {total_pixels}\n" + result_text += f"白色像素: {white_count}\n" + result_text += f"白色比例: {white_ratio:.3f}\n" + result_text += f"置信度: {confidence:.3f}\n" + # 判断是否可能是直播图标 + if white_ratio < 0.3: + result_text += f"判断: 可能是直播图标 (白色像素较少)\n" + elif white_ratio > 0.7: + result_text += f"判断: 可能不是直播图标 (白色像素较多)\n" + else: + result_text += f"判断: 不确定 (白色比例适中)\n" + + self.result_text.delete(1.0, tk.END) + self.result_text.insert(tk.END, result_text) + + print(f"\n=== 多边形区域分析结果 ===") + print(f"顶点: {self.polygon_points}") + print(result_text) + print(f"结果已保存 (共{len(self.regions)}个区域)") + + def show_all_regions(self): + """显示所有区域""" + if not self.regions: + messagebox.showinfo("信息", "没有保存的区域数据") + return + + result_text = f"所有多边形区域数据 (共{len(self.regions)}个):\n\n" + for i, region in enumerate(self.regions, 1): + result_text += f"区域 {i}:\n" + result_text += f" 顶点数: {len(region['polygon_points'])}\n" + result_text += f" 顶点坐标:\n" + for j, (x, y) in enumerate(region['polygon_points']): + result_text += f" {j+1}: ({x:.0f}, {y:.0f})\n" + result_text += f" 白色像素: {region['white_pixels']}/{region['total_pixels']}\n" + result_text += f" 比例: {region['white_ratio']:.3f}, 置信度: {region['confidence']:.3f}\n\n" + + self.result_text.delete(1.0, tk.END) + self.result_text.insert(tk.END, result_text) + + def clear_all_regions(self): + """清除所有区域""" + self.regions.clear() + self.result_text.delete(1.0, tk.END) + self.result_text.insert(tk.END, "已清除所有区域数据") + + def save_regions(self): + """保存区域数据""" + if not self.regions: + messagebox.showwarning("警告", "没有区域数据可以保存") + return + + filename = filedialog.asksaveasfilename( + title="保存区域数据", + defaultextension=".json", + filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")] + ) + + if filename: + try: + with open(filename, 'w', encoding='utf-8') as f: + json.dump(self.regions, f, indent=2, ensure_ascii=False) + messagebox.showinfo("成功", f"区域数据已保存到: {filename}") + except Exception as e: + messagebox.showerror("错误", f"保存失败: {e}") + + def load_regions(self): + """加载区域数据""" + filename = filedialog.askopenfilename( + title="加载区域数据", + filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")] + ) + + if filename: + try: + with open(filename, 'r', encoding='utf-8') as f: + self.regions = json.load(f) + messagebox.showinfo("成功", f"已加载 {len(self.regions)} 个区域数据") + self.show_all_regions() + except Exception as e: + messagebox.showerror("错误", f"加载失败: {e}") + + def run(self): + """运行主循环""" + self.root.mainloop() + + +def main(): + """主函数""" + # 如果有命令行参数,使用它作为图片路径 + image_path = sys.argv[1] if len(sys.argv) > 1 else None + + if image_path and not os.path.exists(image_path): + print(f"错误: 找不到图片文件 {image_path}") + image_path = None + + try: + app = SimpleRegionSelector(image_path) + app.run() + except Exception as e: + print(f"启动失败: {e}") + import traceback + traceback.print_exc() + + +if __name__ == "__main__": + main() diff --git a/tools/test_white_regions_x.py b/tools/test_white_regions_x.py new file mode 100644 index 0000000..5ef1d95 --- /dev/null +++ b/tools/test_white_regions_x.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +在两个指定小区域内统计白色像素比例,用于辅助判断右上角是否有关闭 X 图标。 + +用法示例: + python tools/test_white_regions_x.py pic/screenshot_recommend.png pic/screenshot_live.png + +思路: +- 假设原始截图分辨率约为 1080x2400(宽x高),并使用与代码中像素检测相同的坐标系。 +- X 图标所在的大 ROI 为 (972,147)-(1047,216) +- 你在 pick_coords 中点出的两个白色点大致为: + P1 = (999,174) + P2 = (1025,201) +- 本脚本在这两个点附近取一个小方框(默认 7x7),统计白色像素比例。 +""" + +import os +import sys +from typing import Tuple, List + +import cv2 +import numpy as np + +# 修正 Windows 控制台编码问题 +if sys.platform == "win32": + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: + pass + + +def load_image(path: str) -> np.ndarray: + """加载图片(支持中文路径),返回 BGR 图像。""" + if not os.path.exists(path): + raise FileNotFoundError(path) + data = np.fromfile(path, dtype=np.uint8) + img = cv2.imdecode(data, cv2.IMREAD_COLOR) + if img is None: + raise RuntimeError(f"无法读取图片: {path}") + return img + + +def crop_region( + img: np.ndarray, x1: int, y1: int, x2: int, y2: int +) -> np.ndarray: + h, w = img.shape[:2] + x1 = max(0, min(w - 1, x1)) + x2 = max(0, min(w, x2)) + y1 = max(0, min(h - 1, y1)) + y2 = max(0, min(h, y2)) + if x2 <= x1 or y2 <= y1: + return img[0:0, 0:0] + return img[y1:y2, x1:x2] + + +def count_white_pixels(region: np.ndarray, gray_threshold: int = 245, diff_threshold: int = 10) -> Tuple[int, int, float]: + """ + 统计区域内“白色像素”数量。 + + - gray_threshold: 灰度阈值(越大越严格,默认 245) + - diff_threshold: RGB 分量差异阈值(越小越接近纯白,默认 10) + """ + if region.size == 0: + return 0, 0, 0.0 + + b, g, r = cv2.split(region) + gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY) + + # 灰度足够亮 + bright = gray >= gray_threshold + # RGB 三通道差异不大(接近无色) + diff_rg = np.abs(r.astype(np.int16) - g.astype(np.int16)) <= diff_threshold + diff_rb = np.abs(r.astype(np.int16) - b.astype(np.int16)) <= diff_threshold + diff_gb = np.abs(g.astype(np.int16) - b.astype(np.int16)) <= diff_threshold + + white_mask = bright & diff_rg & diff_rb & diff_gb + white_count = int(white_mask.sum()) + total = int(region.shape[0] * region.shape[1]) + ratio = white_count / total if total > 0 else 0.0 + return white_count, total, ratio + + +def analyse_image( + path: str, + p1: Tuple[int, int], + p2: Tuple[int, int], +) -> None: + """对单张截图进行分析并打印结果(使用两点组成的对角矩形区域)。""" + img = load_image(path) + h, w = img.shape[:2] + print("=" * 80) + print(f"图片: {path}") + print(f"尺寸: {w}x{h}") + + # 如果不是接近 1080x2400,可以按宽高比例缩放坐标 + base_w, base_h = 1080, 2400 + scale_x = w / base_w + scale_y = h / base_h + + def scaled_point(p: Tuple[int, int]) -> Tuple[int, int]: + return int(round(p[0] * scale_x)), int(round(p[1] * scale_y)) + + sp1 = scaled_point(p1) + sp2 = scaled_point(p2) + + # 使用两点组成对角矩形区域 + x1, y1 = sp1 + x2, y2 = sp2 + rx1, ry1 = min(x1, x2), min(y1, y2) + rx2, ry2 = max(x1, x2), max(y1, y2) + + region = crop_region(img, rx1, ry1, rx2, ry2) + + # 为了更接近“纯白”,在这个测试里稍微提高阈值要求 + white_count, total, ratio = count_white_pixels(region, gray_threshold=250, diff_threshold=5) + + print(f"矩形区域(基于原坐标): {p1} - {p2}") + print(f"实际像素区域: ({rx1},{ry1})-({rx2},{ry2}), 尺寸={region.shape[1]}x{region.shape[0]}") + print(f"纯白像素: {white_count}/{total}, 比例={ratio:.4f}") + + +def main(argv: List[str]) -> int: + if len(argv) < 2: + print( + "用法: python tools/test_white_regions_x.py <图片1> [图片2 ...]\n" + "建议:分别传入推荐页截图和直播间截图,对比输出的白色像素比例。" + ) + return 1 + + # 你在 pick_coords 中点出的两个点 + p1 = (999, 174) + p2 = (1025, 201) + + for path in argv[1:]: + try: + analyse_image(path, p1, p2) + except Exception as e: + print(f"分析失败: {path} -> {e}") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) + diff --git a/tools/使用说明.txt b/tools/使用说明.txt new file mode 100644 index 0000000..c737dd4 --- /dev/null +++ b/tools/使用说明.txt @@ -0,0 +1,66 @@ +抖音区域选择器使用说明 +========================== + +工具位置: +- 主程序:tools/simple_region_selector.py +- 启动脚本:tools/启动区域选择器.bat + +功能说明: +这个工具专门用于抖音挂机项目,帮助你: +1. 可视化选择直播间图标(x)的区域 +2. 统计区域内的白色像素数量 +3. 通过白色像素比例判断是否为直播状态 +4. 保存区域坐标和分析结果 + +快速开始: +1. 双击运行 "启动区域选择器.bat" +2. 在弹出的窗口中点击"文件" -> "打开图片" +3. 选择一张抖音截图(比如pic/screenshot.png) +4. 依次点击多个点围成x图标的形状 +5. 右键或按空格键完成多边形选择 +6. 按Enter键分析白色像素统计 +7. 按Ctrl+S保存区域坐标数据 + +操作说明: +- 依次点击:沿着x图标的边缘点击多个点 +- 完成选择:右键点击或按空格键闭合多边形 +- 删除点:按Backspace键删除最后一个点 +- 系统会自动绘制红色多边形和半透明填充显示选择的区域 +- 不支持拖拽图片或放大缩小,图片按原始大小显示 + +使用技巧: +- 多边形可以精确围住不规则形状的x图标 +- 至少需要3个点才能构成有效多边形 +- 白色像素比例<0.3:可能是直播图标 +- 白色像素比例>0.7:可能不是直播图标 +- 置信度接近1.0:判断更可靠 + +图片操作: +- 鼠标滚轮:放大缩小 +- 右键拖拽:移动图片 +- 适应窗口:自动调整缩放比例 +- 重置缩放:恢复原始大小 + +快捷键: +Ctrl+O 打开图片 +Enter 分析区域 +Delete 清除选择 +Space 完成多边形 +Backspace 删除最后一个点 +Ctrl+S 保存数据 +Ctrl+L 加载数据 ++/- 放大缩小 +Ctrl+0 重置缩放 +Ctrl+F 适应窗口 + +输出格式: +保存的JSON文件包含: +- 坐标范围 (x1,y1)-(x2,y2) +- 区域尺寸 +- 白色像素统计 +- 置信度分析 + +注意事项: +- 确保Python和PIL库已安装 +- 建议使用高分辨率截图 +- 区域选择要精确圈住图标 diff --git a/tools/启动区域选择器.bat b/tools/启动区域选择器.bat new file mode 100644 index 0000000..28a13eb --- /dev/null +++ b/tools/启动区域选择器.bat @@ -0,0 +1,35 @@ +@echo off +chcp 65001 >nul +title 抖音区域选择器 - 白色像素统计工具 + +echo ======================================== +echo 抖音区域选择器 - 白色像素统计工具 +echo ======================================== +echo. +echo 这个工具可以帮助你: +echo - 可视化选择图片区域(圈出x图标位置) +echo - 统计区域内白色像素数量 +echo - 保存区域坐标和分析结果 +echo. +echo 使用方法: +echo 1. 点击"文件" -> "打开图片" 选择截图 +echo 2. 滚轮缩放,右键拖拽调整视图 +echo 3. 依次点击多个点围成x图标形状 +echo 4. 右键或按空格键完成多边形选择 +echo 5. 按Enter键分析白色像素统计 +echo 6. Ctrl+S保存区域数据 +echo. +echo 快捷键: +echo Ctrl+O: 打开图片 +echo Ctrl+S: 保存区域数据 +echo Enter: 分析区域 +echo Delete: 清除选择 +echo +/-: 放大缩小 +echo Ctrl+0: 重置缩放 +echo. +echo ======================================== + +cd /d "%~dp0" +python simple_region_selector.py + +pause diff --git a/tools/打开图片 b/tools/打开图片 new file mode 100644 index 0000000..e69de29 diff --git a/typings/cv2.pyi b/typings/cv2.pyi index 935ef4e..fac7f98 100644 --- a/typings/cv2.pyi +++ b/typings/cv2.pyi @@ -26,5 +26,4 @@ def setLogLevel(level: int) -> None: ... class utils: class logging: LOG_LEVEL_SILENT: int - def setLogLevel(level: int) -> None: ... def equalizeHist(src: Any, dst: Any = ...) -> Any: ... diff --git a/webui/app.js b/webui/app.js index 3ce932f..93b6e6d 100644 --- a/webui/app.js +++ b/webui/app.js @@ -677,15 +677,13 @@ async function startRun() { async function testYanghao() { const deviceId = $("device").value || ""; const seconds = parseInt($("yanghao_recommend_duration_seconds").value || "60", 10); - await apiPost("/api/test-yanghao", { device_id: deviceId, seconds }); - appendLog([`[WEB] 已启动测试养号:device=${deviceId || '(auto)'} seconds=${seconds}`]); + // 已移除测试养号功能 } async function testComment() { const deviceId = $("device").value || ""; const text = ""; - await apiPost("/api/test-comment", { device_id: deviceId, text }); - appendLog([`[WEB] 已启动测试评论:device=${deviceId || '(auto)'}${text ? ' text=自定义' : ''}`]); + // 已移除测试评论功能 } async function stopRun() { diff --git a/webui/index.html b/webui/index.html index 81b0fea..ee1eb22 100644 --- a/webui/index.html +++ b/webui/index.html @@ -10,7 +10,7 @@
-
抖音挂机控制台
+
抖音挂机控制å�?/div>
配置与运行(纯坐标点击)
@@ -18,8 +18,7 @@ - 开始运行 - + 开始运è¡?
- +
- +
- +