From 47e6b016c5b752ddb7e6728386c3e9851fc772cb Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 20 Dec 2025 20:11:28 +0800 Subject: [PATCH] refactor: Remove deprecated files and enhance configuration settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Deleted outdated markdown files and scripts related to previous implementations. - Updated `config.json` to adjust thresholds and settings for 福袋 detection and reservation handling. - Improved logging and error handling across various modules for better monitoring and user experience. - Introduced a new screenshot management module to facilitate real-time operation and success tracking. - Enhanced GUI elements to support new configuration options and improve usability. --- LOGGING_IMPROVEMENTS.md | 162 + Underlying_Operations.py | 81 +- config.json | 22 +- douyin_detection.py | 60 + douyin_fudai.py | 199 +- douyin_fudai_core.py | 102 +- douyin_fudai_detail.py | 104 +- douyin_high_value_room.py | 247 -- douyin_logger.py | 304 ++ douyin_logging.py | 336 ++ douyin_pixel.py | 21 +- douyin_reservation_logic.py | 61 + douyin_screenshot_manager.py | 267 ++ douyin_swipe_ops.py | 51 + douyin_utils.py | 22 +- fix_indent_smart.py | 111 + fix_indentation.py | 214 ++ gui_app.py | 14 +- gui_core.py | 4 +- path_config.py | 9 + run_cli.py | 6 +- state/reservations.json | 24 +- tools/README_RGB工具.md | 75 - tools/analyze_fudai_color.py | 67 - tools/compare_fudai_coupon.py | 83 - tools/read_fudai_rgb.py | 140 - tools/read_image_rgb.py | 175 - 功能差异对比.md | 249 -- 原始代码/fudai1.py | 5938 +-------------------------------- 日志系统优化说明.md | 195 ++ 模块化代码对比说明.md | 285 -- 31 files changed, 2257 insertions(+), 7371 deletions(-) create mode 100644 LOGGING_IMPROVEMENTS.md create mode 100644 douyin_logger.py create mode 100644 douyin_logging.py create mode 100644 douyin_screenshot_manager.py create mode 100644 fix_indent_smart.py create mode 100644 fix_indentation.py create mode 100644 日志系统优化说明.md diff --git a/LOGGING_IMPROVEMENTS.md b/LOGGING_IMPROVEMENTS.md new file mode 100644 index 0000000..69465a7 --- /dev/null +++ b/LOGGING_IMPROVEMENTS.md @@ -0,0 +1,162 @@ +# 日志系统优化说明 + +## 概述 + +本次优化系统性地增强了现有行为日志系统,使其记录更详细、结构更清晰,并包含完整的调试上下文信息,以便快速定位和诊断程序运行中的问题。 + +## 主要改进 + +### 1. 创建增强的日志配置模块 (`douyin_logger.py`) + +- **标准 Python logging 集成**:使用 Python 标准 `logging` 模块,提供更强大的日志管理能力 +- **日志级别管理**:支持 DEBUG, INFO, WARNING, ERROR, CRITICAL 五个级别 +- **日志轮转**:支持按大小(RotatingFileHandler)和时间(TimedRotatingFileHandler)自动轮转 +- **灵活的配置**:从 `config.json` 读取配置,支持环境变量覆盖 +- **日志上下文管理器**:提供 `LogContext` 类用于记录函数调用、参数、返回值、耗时等 + +### 2. 增强 `_log_kv` 方法 (`douyin_fudai.py`) + +- **集成标准 logging**:在保持原有格式和功能的基础上,同时输出到标准 logging 系统 +- **自动异常堆栈记录**:检测异常上下文并自动记录完整堆栈信息 +- **调用者信息**:自动记录模块名、函数名、行号 +- **日志级别支持**:通过 `level` 参数控制日志级别 +- **向后兼容**:完全兼容现有的 `_log_kv` 调用方式 + +### 3. 配置文件更新 (`config.json`) + +添加了日志配置选项: + +```json +"logging": { + "level": "INFO", // 日志级别:DEBUG, INFO, WARNING, ERROR, CRITICAL + "file_path": "logs/unified.log", // 日志文件路径 + "rotation": { + "enabled": true, // 是否启用日志轮转 + "max_bytes": 10485760, // 按大小轮转:最大文件大小(字节) + "backup_count": 5, // 保留的备份文件数量 + "when": "midnight", // 按时间轮转:轮转时间点 + "interval": 1 // 按时间轮转:间隔天数 + } +} +``` + +### 4. 日志格式优化 + +标准 logging 输出格式: +``` +%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s +``` + +示例输出: +``` +2025-01-20 10:30:45 - [INFO] - douyin:run_once_basic:910 - [截图] 截图+阶段诊断 stage=IN_LIVE_ROOM seen=直播间 +``` + +### 5. 异常处理增强 + +- **完整堆栈跟踪**:所有异常都记录完整的堆栈信息 +- **异常上下文**:自动检测并记录异常发生时的上下文信息 +- **错误级别**:异常自动标记为 ERROR 级别 + +## 使用方法 + +### 基本使用 + +现有的 `_log_kv` 调用方式保持不变: + +```python +# 基本用法 +self._log_kv("标签", "消息", field1=value1, field2=value2) + +# 指定日志级别 +self._log_kv("标签", "消息", level="DEBUG", field1=value1) + +# 记录异常(自动包含堆栈) +try: + # 某些操作 + pass +except Exception as e: + self._log_kv("错误", "操作失败", error=str(e), level="ERROR", exc_info=sys.exc_info()) +``` + +### 使用标准 logging + +也可以直接使用标准 logging: + +```python +import douyin_logger + +logger = douyin_logger.get_logger("douyin") +logger.debug("调试信息") +logger.info("一般信息") +logger.warning("警告信息") +logger.error("错误信息", exc_info=True) # 包含异常堆栈 +``` + +### 使用日志上下文管理器 + +记录函数调用的详细信息: + +```python +import douyin_logger + +logger = douyin_logger.get_logger("douyin") + +def my_function(arg1, arg2): + with douyin_logger.LogContext(logger, "my_function", log_args=True, log_result=True): + # 函数体 + result = arg1 + arg2 + return result +``` + +## 环境变量 + +可以通过环境变量动态调整日志级别(开发调试时使用): + +```bash +# Windows +set DOUYIN_LOG_LEVEL=DEBUG + +# Linux/Mac +export DOUYIN_LOG_LEVEL=DEBUG +``` + +## 日志文件位置 + +- 默认路径:`logs/unified.log` +- 可在 `config.json` 中通过 `logging.file_path` 配置 +- 日志轮转后的备份文件:`logs/unified.log.2025-01-20` 等 + +## 日志级别说明 + +- **DEBUG**:详细的调试信息,包括函数调用、参数、返回值等 +- **INFO**:一般信息,程序正常运行的关键步骤 +- **WARNING**:警告信息,程序可以继续运行但可能存在潜在问题 +- **ERROR**:错误信息,程序遇到错误但可以继续运行 +- **CRITICAL**:严重错误,程序可能无法继续运行 + +## 最佳实践 + +1. **关键操作**:在关键业务逻辑处(如福袋识别、界面操作)记录详细日志 +2. **异常处理**:所有异常都应该被捕获并记录,使用 `level="ERROR"` 和 `exc_info=sys.exc_info()` +3. **性能监控**:使用 `_log_step_time` 记录关键步骤的耗时 +4. **调试模式**:开发调试时设置 `DOUYIN_LOG_LEVEL=DEBUG` 环境变量获取最详细信息 +5. **生产环境**:生产环境建议使用 `INFO` 或 `WARNING` 级别,平衡性能与可观察性 + +## 注意事项 + +1. **不要修改 fudai1.py**:按照要求,未修改 `原始代码/fudai1.py`,所有增强都在 `douyin_fudai.py` 中实现 +2. **向后兼容**:所有现有的 `_log_kv` 调用都保持兼容,无需修改 +3. **日志轮转**:日志文件会自动轮转,避免单个文件过大 +4. **性能影响**:标准 logging 的性能开销很小,但在高频调用时建议使用适当的日志级别 + +## 后续优化建议 + +1. **结构化日志**:考虑使用 JSON 格式的结构化日志,便于日志分析工具处理 +2. **日志聚合**:对于分布式部署,可以考虑集成日志聚合服务(如 ELK、Loki 等) +3. **性能指标**:添加更多性能指标记录(如函数调用次数、平均耗时等) +4. **日志过滤**:添加日志过滤功能,可以根据标签、级别等条件过滤日志 + + + + diff --git a/Underlying_Operations.py b/Underlying_Operations.py index a1b970d..f67927b 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -327,11 +327,11 @@ class underlying_operations: return dictdevice[num] def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]: - """查找图片路径,支持新旧位置(向后兼容) + """查找图片路径,支持新旧位置(向后兼容),并按分类组织 Args: picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容' - for_reading: True=读取(支持新旧位置),False=写入(使用新位置) + for_reading: True=读取(支持新旧位置),False=写入(使用新位置+分类目录) Returns: 图片的完整路径,如果找不到且for_reading=True则返回None @@ -345,21 +345,33 @@ class underlying_operations: path = os.path.join(pic_base, f'{picname}.png') return path if (os.path.exists(path) or not for_reading) else None - # OCR图片文件:优先查找新位置(ocr/),然后查找旧位置(根目录) + # OCR图片文件:按分类组织到子目录 + try: + import douyin_screenshot_manager + category = douyin_screenshot_manager.get_category_for_picname(picname) + except Exception: + category = "others" + if for_reading: - # 读取:先查新位置,再查旧位置(向后兼容) - new_path = os.path.join(pic_base, 'ocr', f'{picname}.png') - if os.path.exists(new_path): - return new_path - old_path = os.path.join(pic_base, f'{picname}.png') - if os.path.exists(old_path): - return old_path + # 读取:先查分类目录,再查旧位置(向后兼容) + # 1. 新位置(分类目录) + category_path = os.path.join(pic_base, 'ocr', category, f'{picname}.png') + if os.path.exists(category_path): + return category_path + # 2. 旧位置(ocr根目录) + old_ocr_path = os.path.join(pic_base, 'ocr', f'{picname}.png') + if os.path.exists(old_ocr_path): + return old_ocr_path + # 3. 更旧的位置(pic根目录) + old_root_path = os.path.join(pic_base, f'{picname}.png') + if os.path.exists(old_root_path): + return old_root_path return None else: - # 写入:使用新位置,确保目录存在 - ocr_dir = os.path.join(pic_base, 'ocr') - os.makedirs(ocr_dir, exist_ok=True) - return os.path.join(ocr_dir, f'{picname}.png') + # 写入:使用分类目录,确保目录存在 + category_dir = os.path.join(pic_base, 'ocr', category) + os.makedirs(category_dir, exist_ok=True) + return os.path.join(category_dir, f'{picname}.png') def get_screenshot(self, device_id, path='pic'): """截图3个adb命令需要2S左右的时间""" @@ -653,7 +665,16 @@ class underlying_operations: if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom: raise ValueError(f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}") - pic.crop((left, top, right, bottom)).save(cut_pic_path) + cropped_img = pic.crop((left, top, right, bottom)) + cropped_img.save(cut_pic_path) + + # 双截图记录:保存实时操作截图 + try: + import douyin_screenshot_manager + douyin_screenshot_manager.save_latest_attempt(cropped_img, operation_type="cut_pic") + except Exception: + pass + return True else: @@ -857,17 +878,32 @@ class underlying_operations: except Exception: pass + # 双截图记录:无论成功与否,都保存实时操作截图 + try: + import douyin_screenshot_manager + # 使用预处理后的图片(实际用于OCR的图片) + img_for_attempt = img2 if (img2 is not None and text2 and text2.strip()) else img1 + douyin_screenshot_manager.save_latest_attempt(img_for_attempt, operation_type="ocr") + except Exception: + pass + # 如果OCR识别成功(返回非空文本),保存一份图片到ocr文件夹(与cut_pic保存的图片区分开) if text and text.strip() and picname: try: - # 使用_find_pic_path获取ocr文件夹路径(写入模式) + # 使用分类目录保存成功截图 + try: + import douyin_screenshot_manager + category = douyin_screenshot_manager.get_category_for_picname(picname) + except Exception: + category = "others" + base_dir = os.path.dirname(__file__) pic_base = os.path.join(base_dir, 'pic') - ocr_dir = os.path.join(pic_base, 'ocr') - os.makedirs(ocr_dir, exist_ok=True) + category_dir = os.path.join(pic_base, 'ocr', category) + os.makedirs(category_dir, exist_ok=True) # 保存文件名:{picname}_success.png,与cut_pic保存的{picname}.png区分开 - success_path = os.path.join(ocr_dir, f'{picname}_success.png') + success_path = os.path.join(category_dir, f'{picname}_success.png') # 保存识别成功时的图片(使用预处理后的图片,即实际用于OCR的图片) try: @@ -877,6 +913,13 @@ class underlying_operations: else: # 否则保存预处理后的图片(img1) img_to_save = img1 + + # 双截图记录:保存成功识别存档截图 + try: + import douyin_screenshot_manager + douyin_screenshot_manager.save_last_success(img_to_save, operation_type="ocr") + except Exception: + pass img_to_save.save(success_path) except Exception: # 如果保存预处理后的图片失败,保存原始图片 diff --git a/config.json b/config.json index 989c592..646fbd3 100644 --- a/config.json +++ b/config.json @@ -2,12 +2,12 @@ "needswitch": true, "infinite_loop_enabled": true, "wait_minutes": 5, - "min_prize_value_yuan": 200.0, + "min_prize_value_yuan": 300.0, "min_participants": 0, "max_participants": 0, - "skip_if_countdown_lt_seconds": 5, - "reset_after_swipes_enabled": false, - "reset_after_swipes": 30, + "skip_if_countdown_gt_seconds": 180, + "reset_after_swipes_enabled": true, + "reset_after_swipes": 50, "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, @@ -74,5 +74,17 @@ "enable_ocr_mode1": false, "fudai_template_match_threshold": 0.5, "lucky_draw_red_ratio_threshold": 0.8, - "y_pianyi": 0 + "y_pianyi": 0, + "skip_if_countdown_lt_seconds": 5, + "logging": { + "level": "INFO", + "file_path": "logs/unified.log", + "rotation": { + "enabled": true, + "max_bytes": 10485760, + "backup_count": 5, + "when": "midnight", + "interval": 1 + } + } } diff --git a/douyin_detection.py b/douyin_detection.py index a828f63..ad3e33b 100644 --- a/douyin_detection.py +++ b/douyin_detection.py @@ -226,6 +226,14 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool # 边界检查 if x1 < x2 and y_top < y_bottom: roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert('RGB') + + # 双截图记录:保存实时操作截图(像素检测区域) + try: + import douyin_screenshot_manager + douyin_screenshot_manager.save_latest_attempt(roi, operation_type="pixel_detect") + except Exception: + pass + arr = _np.array(roi) if arr.size > 0: r = arr[:, :, 0] @@ -247,6 +255,14 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool # 计算检测到的x坐标:转换为1080基准坐标,确保精度 detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx)) detected = True + + # 双截图记录:保存成功识别存档截图 + try: + import douyin_screenshot_manager + douyin_screenshot_manager.save_last_success(roi, operation_type="pixel_detect") + except Exception: + pass + try: analyser.last_find_fudai_time = time.time() except Exception: @@ -280,6 +296,15 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool # 转换回1080基准坐标 detected_x = int(x_scaled * 1080.0 / max(1, rx)) detected = True + + # 双截图记录:保存成功识别存档截图 + try: + import douyin_screenshot_manager + detect_roi = pic_new.crop((scan_x_start, max(0, scan_y - 3), scan_x_end, min(pic_height, scan_y + 4))).convert('RGB') + douyin_screenshot_manager.save_last_success(detect_roi, operation_type="pixel_detect") + except Exception: + pass + try: analyser.last_find_fudai_time = time.time() except Exception: @@ -385,6 +410,15 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + # 双截图记录:保存实时操作截图(搜索区域) + try: + import douyin_screenshot_manager + from PIL import Image as PILImage + search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)) + douyin_screenshot_manager.save_latest_attempt(search_roi_pil, operation_type="template_match") + except Exception: + pass + try: analyser._log_kv( "[找福袋图标] 模板匹配兜底", @@ -402,6 +436,14 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool pass if max_val >= template_threshold: + # 双截图记录:保存成功识别存档截图 + try: + import douyin_screenshot_manager + from PIL import Image as PILImage + search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)) + douyin_screenshot_manager.save_last_success(search_roi_pil, operation_type="template_match") + except Exception: + pass # 计算检测到的X坐标(1080基准) detected_x_in_roi = max_loc[0] detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)) @@ -760,6 +802,15 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + # 双截图记录:保存实时操作截图(搜索区域) + try: + import douyin_screenshot_manager + from PIL import Image as PILImage + search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)) + douyin_screenshot_manager.save_latest_attempt(search_roi_pil, operation_type="template_match") + except Exception: + pass + template_match_elapsed = (time.time() - template_match_start) * 1000 # 详细日志:记录匹配结果 @@ -776,6 +827,15 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool pass if max_val >= template_threshold: + # 双截图记录:保存成功识别存档截图 + try: + import douyin_screenshot_manager + from PIL import Image as PILImage + search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)) + douyin_screenshot_manager.save_last_success(search_roi_pil, operation_type="template_match") + except Exception: + pass + # 计算检测到的X坐标(1080基准) detected_x_in_roi = max_loc[0] detected_x = int((search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)) diff --git a/douyin_fudai.py b/douyin_fudai.py index b99bca5..fb88f26 100644 --- a/douyin_fudai.py +++ b/douyin_fudai.py @@ -7,12 +7,14 @@ from __future__ import annotations 目标: - 不再依赖外部 axf 目录; - 保持 `from douyin_fudai import fudai_analyse` 导入方式不变; -- 将核心逻辑拆分到各子模块,仅在此做“组装 + 调度”。 +- 将核心逻辑拆分到各子模块,仅在此做"组装 + 调度"。 """ from typing import Any, List, Tuple import os import time +import sys +import logging from Underlying_Operations import underlying_operations @@ -52,13 +54,16 @@ class fudai_analyse: self.operation = underlying_operations() self.config_path = "config.json" - # 日志相关字段:沿用原 fudai1.py 的 _log_kv 实现 - from 原始代码.fudai1 import fudai_analyse as _Orig # type: ignore - - # 直接复用原始实现中的 _log_kv,以保持统一格式 - self._run_id = getattr(_Orig(), "_run_id", str(int(time.time()))) + # 日志相关字段:完全独立的日志系统(不依赖原始代码) + try: + from datetime import datetime + self._run_id = datetime.now().strftime('%Y%m%d%H%M%S') + except Exception: + self._run_id = str(int(time.time())) self._log_seq = 0 - self._log_kv = _Orig._log_kv.__get__(self, fudai_analyse) # type: ignore[attr-defined] + self._log_kv_orig = None + # 使用增强版本 + self._log_kv = self._enhanced_log_kv # 进入直播间后诊断与阶段流转所需的一些状态 self._last_diag_stage: str = "INIT" @@ -71,7 +76,7 @@ class fudai_analyse: self.min_prize_value_yuan: float = 0.0 self.min_participants: int = 0 self.max_participants: int = 0 - self.skip_if_countdown_lt_seconds: int = 15 + self.skip_if_countdown_gt_seconds: int = 900 self.no_fudai_watchdog_enabled: bool = False # 福袋图标检测节流相关默认值 # 实际识别到福袋一般需要 4–6 秒,这里取中间值 5 秒作为默认上限,具体值可在 GUI / config.json 中调整 @@ -199,7 +204,7 @@ class fudai_analyse: self.min_prize_value_yuan = _float("min_prize_value_yuan", self.min_prize_value_yuan) self.min_participants = _int("min_participants", self.min_participants) self.max_participants = _int("max_participants", self.max_participants) - self.skip_if_countdown_lt_seconds = _int("skip_if_countdown_lt_seconds", self.skip_if_countdown_lt_seconds) + self.skip_if_countdown_gt_seconds = _int("skip_if_countdown_gt_seconds", self.skip_if_countdown_gt_seconds) try: self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", self.no_fudai_watchdog_enabled)) @@ -714,6 +719,178 @@ class fudai_analyse: pass return False + def _enhanced_log_kv(self, *args, **fields): + """增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging""" + # 解析参数 + tag = args[0] if len(args) >= 1 else fields.get("tag", "日志") + msg = args[1] if len(args) >= 2 else fields.get("msg", "") + + # 获取日志级别 + log_level = fields.get("level", "INFO").upper() + if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): + log_level = "INFO" + + # 递增日志序号 + try: + self._log_seq += 1 + except Exception: + self._log_seq = 1 + + # 获取时间戳 + try: + from datetime import datetime + timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] + except Exception: + try: + timestamp = datetime.now().strftime('%H:%M:%S') + except Exception: + timestamp = "" + + # 获取调用者信息(模块名:函数名:行号) + caller_info = "" + try: + import inspect + # 获取调用栈:跳过 _enhanced_log_kv 本身,找到真正的调用者 + frame = inspect.currentframe() + if frame: + # frame.f_back 是调用 _enhanced_log_kv 的帧(可能是 _log_kv 或其他) + # 需要再往上找一层,找到实际调用 _log_kv 的代码 + caller_frame = frame.f_back + if caller_frame: + # 检查是否是 _log_kv 的调用(属性赋值的情况) + if caller_frame.f_code.co_name == "_log_kv" or "log_kv" in caller_frame.f_code.co_name: + caller_frame = caller_frame.f_back + # 如果找到了调用者,提取信息 + if caller_frame: + filename = caller_frame.f_code.co_filename + funcname = caller_frame.f_code.co_name + lineno = caller_frame.f_lineno + # 只取文件名,不包含路径 + import os + filename = os.path.basename(filename) + # 如果文件名是 或类似,说明是测试代码,跳过 + if filename and filename not in ("", ""): + caller_info = f"{filename}:{funcname}:{lineno}" + except Exception: + pass + + # 字段映射(中文 key) + key_map = { + "rid": "运行", "seq": "序号", "msg": "说明", "stage": "阶段", "seen": "识别", + "ok": "成功", "text": "文本", "action": "动作", "result": "结果", "mode": "模式", + "reason": "原因", "wait_seconds": "等待秒", "value_yuan": "价值元", + "future": "开奖时间", "pos_seen": "发现位置", "qsize": "队列数量", + "room_pos": "当前位置", "content": "内容", "countdown": "倒计时", + "participants": "参与人数", "copies": "份数", "seconds": "耗时秒", + "error": "错误", "error_type": "错误类型", "fudai_x": "福袋X坐标", + "attempt": "尝试次数", "room_title": "直播间名", "back_times": "需回退次数", + } + + # 构建日志行(增强格式:时间 级别 标签 [调用者] 消息 字段...) + log_parts = [] + if timestamp: + log_parts.append(f"[{timestamp}]") + log_parts.append(f"[{log_level}]") + log_parts.append(f"[{tag}]") + + # 添加调用者信息(如果获取成功) + if caller_info: + log_parts.append(f"[{caller_info}]") + + if msg: + m = str(msg).replace("\r", " ").replace("\n", " ").strip() + if len(m) > 200: + m = m[:200] + "..." + log_parts.append(m) + + # 添加字段信息 + for k, v in fields.items(): + if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"): + continue + if v is None: + continue + key_cn = key_map.get(str(k), f"字段_{k}") + # 格式化值 + if isinstance(v, float): + if abs(v) < 1: + v_str = f"{v:.3f}" + elif abs(v) < 100: + v_str = f"{v:.2f}" + else: + v_str = f"{int(v)}" + elif isinstance(v, (int, bool)): + v_str = str(v) + else: + s = str(v).replace("\r", " ").replace("\n", " ").strip() + if len(s) > 100: + s = s[:100] + "..." + v_str = s + log_parts.append(f"{key_cn}={v_str}") + + # 构建完整日志行 + log_line = " ".join(log_parts) + + # 始终输出到 stdout(供 GUI 捕获)- 这是最重要的! + try: + print(log_line, flush=True) # flush=True 确保立即输出,不缓冲 + except Exception: + pass + + # 同时输出到标准 logging(如果已配置,可选) + try: + if not hasattr(self, '_std_logger') or self._std_logger is None: + try: + import douyin_logger + self._std_logger = douyin_logger.get_logger("douyin") + except Exception: + pass + + if hasattr(self, '_std_logger') and self._std_logger: + # 构建标准 logging 消息(包含调用者信息) + std_msg_parts = [f"[{tag}]"] + if caller_info: + std_msg_parts.append(f"[调用:{caller_info}]") + if msg: + std_msg_parts.append(str(msg)) + + for k, v in fields.items(): + if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"): + continue + if v is not None: + std_msg_parts.append(f"{k}={v}") + + log_message = " ".join(std_msg_parts) + + # 检查是否有异常信息 + exc_info = fields.get("exc_info") + if exc_info is None: + if sys.exc_info()[0] is not None: + exc_info = sys.exc_info() + + # 记录到标准 logger(使用 extra 参数传递调用者信息,让 formatter 使用) + level = getattr(logging, log_level, logging.INFO) + if exc_info: + self._std_logger.log(level, log_message, exc_info=exc_info, extra={"caller": caller_info}) + else: + self._std_logger.log(level, log_message, extra={"caller": caller_info}) + except Exception: + pass + + # 如果有异常堆栈,也输出到 stdout + exc_info = fields.get("exc_info") + if exc_info is None: + if sys.exc_info()[0] is not None: + exc_info = sys.exc_info() + + if exc_info: + try: + import traceback + tb_str = traceback.format_exception(*exc_info) + for line in tb_str: + print(f" {line.rstrip()}", flush=True) + except Exception: + pass + # 供像素/检测模块记录子步骤耗时使用 def _log_step_time(self, step_name: str, start_time: float, extra_info: dict | None = None) -> None: """记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。""" @@ -742,7 +919,7 @@ class fudai_analyse: # ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ========== def run_once_basic(self) -> None: """单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。""" - # 0. 若启用高价值预约:先处理“是否需要回退到预约直播间” + # 0. 若启用高价值预约:先处理"是否需要回退到预约直播间" try: if getattr(self, "high_value_fudai_enabled", False) and self.reservations: def _swipe_down_once() -> None: @@ -1055,7 +1232,7 @@ class fudai_analyse: pass def swipe_down_back_from_live(self) -> None: - """下滑回退到上一个直播间(供预约/无福袋逻辑使用)。""" + """上划回退到上一个直播间(供预约/无福袋逻辑使用)。""" try: douyin_swipe_ops.swipe_down_back_live(self) except Exception: diff --git a/douyin_fudai_core.py b/douyin_fudai_core.py index fdefb0b..d99fcad 100644 --- a/douyin_fudai_core.py +++ b/douyin_fudai_core.py @@ -176,7 +176,7 @@ def check_contain(analyser, contains: str = "") -> bool: analyser._log_kv("筛选", "福袋内容命中黑名单,将丢弃", keyword=contain, contains=contains[:80] if contains else "") except Exception: pass - return True + return True try: analyser._log_kv("筛选", "福袋内容未命中黑名单,保留", contains=contains[:80] if contains else "") @@ -675,7 +675,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str except Exception: max_participants = 0 try: - skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0) + skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0) except Exception: skip_if_lt = 0 @@ -687,7 +687,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str 配置_最小价值=min_value, 配置_最小参与人数=min_participants, 配置_最大参与人数=max_participants, - 配置_倒计时小于秒数=skip_if_lt, + 配置_倒计时大于秒数=skip_if_gt, 实际_价值=prize_value_yuan, 实际_参与人数=participants, 实际_份数=copies, @@ -792,45 +792,45 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str except Exception: pass - # 3) 倒计时过滤(如果倒计时小于阈值,就不参与;但如果价值达到高价值阈值,可以预约) - # 注意:这个过滤在 basic_join_decision 中会被特殊处理,如果价值达到高价值阈值,即使倒计时小于阈值也会记录预约 - if skip_if_lt > 0: + # 3) 倒计时过滤(如果倒计时大于阈值,就不参与;但如果价值达到高价值阈值,可以预约) + # 注意:这个过滤在 basic_join_decision 中会被特殊处理,如果价值达到高价值阈值,即使倒计时大于阈值也会记录预约 + if skip_if_gt > 0: try: analyser._log_kv( "筛选", "倒计时过滤:开始检查", - 配置阈值秒数=skip_if_lt, + 配置阈值秒数=skip_if_gt, 实际剩余秒数=int(remain_seconds) if remain_seconds is not None else None, 是否有倒计时数据=remain_seconds is not None, - 说明="如果剩余秒数小于阈值,则不参与(但高价值福袋可预约)", + 说明="如果剩余秒数大于阈值,则不参与(但高价值福袋可预约)", ) except Exception: pass if remain_seconds is not None: - # 如果剩余秒数 < 阈值,就丢弃(不参与) - if remain_seconds < skip_if_lt: + # 如果剩余秒数 > 阈值,就丢弃(不参与) + if remain_seconds > skip_if_gt: try: analyser._log_kv( "筛选", - "倒计时过滤:丢弃(剩余秒数小于阈值,不参与)", - 原因=f"countdown_lt_{skip_if_lt}", + "倒计时过滤:丢弃(剩余秒数大于阈值,不参与)", + 原因=f"countdown_gt_{skip_if_gt}", 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_lt, - 判断条件=f"{remain_seconds} < {skip_if_lt} = True", + 配置阈值秒数=skip_if_gt, + 判断条件=f"{remain_seconds} > {skip_if_gt} = True", 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", ) except Exception: pass - return True, f"countdown_lt_{skip_if_lt}" + return True, f"countdown_gt_{skip_if_gt}" else: try: analyser._log_kv( "筛选", - "倒计时过滤:通过(剩余秒数大于等于阈值,可以参与)", + "倒计时过滤:通过(剩余秒数小于等于阈值,可以参与)", 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_lt, - 判断条件=f"{remain_seconds} < {skip_if_lt} = False", + 配置阈值秒数=skip_if_gt, + 判断条件=f"{remain_seconds} > {skip_if_gt} = False", ) except Exception: pass @@ -1002,12 +1002,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 执行筛选检查 skip, reason = should_skip_fudai_by_config(analyser, detail) - # 特殊处理:如果被倒计时过滤筛掉(倒计时小于阈值),但价值达到高价值阈值,则记录预约而不是丢弃 - if skip and reason.startswith("countdown_lt_") and is_high_value: + # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值,则记录预约而不是丢弃 + if skip and reason.startswith("countdown_gt_") and is_high_value: try: - analyser._log_kv( - "参与", - "basic_join_decision:倒计时小于阈值,但价值达到高价值阈值,记录预约", + analyser._log_kv( + "参与", + "basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约", reason=reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, @@ -1040,7 +1040,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass - # 如果允许切换直播间,则针对部分丢弃原因直接切房(黑名单/价值不达标/倒计时小于阈值) + # 如果允许切换直播间,则针对部分丢弃原因直接切房(黑名单/价值不达标/倒计时大于阈值) try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: @@ -1048,7 +1048,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: if needswitch and ( reason == "content_not_wanted" or reason.startswith("value_lt_") - or reason.startswith("countdown_lt_") + or reason.startswith("countdown_gt_") ): try: analyser._log_kv("参与", "basic_join_decision:丢弃后切换直播间", reason=reason) @@ -1109,34 +1109,34 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: room_title = "" room_title_raw = "" try: - # 尝试从 analyser 获取当前直播间标题 - room_title = str(getattr(analyser, "current_room_title", "") or "") - room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "") - # 如果为空,尝试调用读取标题的函数 - if not room_title or not room_title_raw or room_title_raw == "shim_live_room_title_raw": + # 每次记录预约时,都重新读取直播间标题,不使用缓存 + # 这样可以确保每个预约记录的是当时的真实直播间标题 + try: + # 在函数开头导入,避免作用域问题 + import douyin_fudai_detail as dfd_module + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + room_title, room_title_raw = dfd_module.read_live_room_title_core( + analyser, y_pianyi_val + ) + # 更新 analyser 的属性,用于状态文件显示当前直播间 try: - # 在函数开头导入,避免作用域问题 - import douyin_fudai_detail as dfd_module - y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) - room_title, room_title_raw = dfd_module.read_live_room_title_core( - analyser, y_pianyi_val + analyser.current_room_title = room_title + analyser.current_room_title_raw = room_title_raw + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "预约", + "读取直播间标题失败,尝试使用缓存", + error=str(e), + error_type=type(e).__name__, ) - # 更新 analyser 的属性,以便后续使用 - try: - analyser.current_room_title = room_title - analyser.current_room_title_raw = room_title_raw - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "预约", - "读取直播间标题失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass + except Exception: + pass + # 如果读取失败,尝试使用缓存(作为兜底) + room_title = str(getattr(analyser, "current_room_title", "") or "") + room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "") except Exception: pass diff --git a/douyin_fudai_detail.py b/douyin_fudai_detail.py index 4e02b64..152fb4b 100644 --- a/douyin_fudai_detail.py +++ b/douyin_fudai_detail.py @@ -495,12 +495,90 @@ def read_fudai_detail_with_retries( last_tuple: Optional[Tuple] = None last_status: str = "error" + first_countdown_seconds: Optional[float] = None + first_tuple: Optional[Tuple] = None + first_attempt_time: float = 0.0 for attempt in range(max_attempts): + attempt_start_time = time.time() status, tup, extra = read_fudai_detail_once(analyser) last_status = status if isinstance(tup, tuple) and len(tup) >= 6: - last_tuple = tup[:6] + current_tuple = tup[:6] + # 计算当前倒计时秒数 + current_countdown_seconds = None + try: + cd = current_tuple[5] + if isinstance(cd, (tuple, list)) and len(cd) >= 2: + cd_start = float(cd[0] or 0.0) + cd_end = float(cd[1] or 0.0) + if cd_start > 0 and cd_end > cd_start: + current_countdown_seconds = cd_end - cd_start + except Exception: + pass + + # 记录第一次成功读取的结果(作为基准) + if first_countdown_seconds is None and current_countdown_seconds is not None and status == "ok": + first_countdown_seconds = current_countdown_seconds + first_tuple = current_tuple + first_attempt_time = attempt_start_time + last_tuple = current_tuple + + # 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误 + elif first_countdown_seconds is not None and current_countdown_seconds is not None: + # 计算时间流逝(从第一次读取到现在的时间差) + time_elapsed = attempt_start_time - first_attempt_time + if time_elapsed < 0: + time_elapsed = 0.5 # 默认假设间隔0.5秒 + + # 预期倒计时 = 第一次倒计时 - 时间流逝(允许一定误差) + expected_countdown = first_countdown_seconds - time_elapsed + + # 计算实际差异(与第一次相比) + diff_ratio = abs(current_countdown_seconds - first_countdown_seconds) / max(first_countdown_seconds, 1.0) + # 计算与预期的差异(考虑时间流逝) + expected_diff_ratio = abs(current_countdown_seconds - expected_countdown) / max(expected_countdown, 1.0) if expected_countdown > 0 else 1.0 + + # 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误 + # 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误 + is_inconsistent = ( + diff_ratio > 0.3 or + expected_diff_ratio > 0.2 or + current_countdown_seconds > first_countdown_seconds + 10 # 倒计时不应该增加 + ) + + if is_inconsistent: + try: + analyser._log_kv( + "福袋详情", + "倒计时识别不一致,判定为识别错误(拒绝本次结果,保留第一次结果)", + attempt=attempt + 1, + first_countdown_seconds=int(first_countdown_seconds), + current_countdown_seconds=int(current_countdown_seconds), + expected_countdown=int(expected_countdown), + time_elapsed=round(time_elapsed, 2), + diff_ratio=round(diff_ratio, 3), + expected_diff_ratio=round(expected_diff_ratio, 3), + ) + except Exception: + pass + # 拒绝本次结果,继续使用第一次的结果 + current_tuple = first_tuple + # 如果还有重试机会,继续重试 + if attempt < max_attempts - 1: + try: + analyser.operation.delay(retry_delay) + except Exception: + time.sleep(retry_delay) + continue + else: + # 倒计时合理,更新为当前结果 + last_tuple = current_tuple + + # 如果没有第一次结果,直接使用当前结果 + elif first_countdown_seconds is None: + last_tuple = current_tuple + # 如果成功读取,或者检测到优惠券弹窗(已处理完毕),都停止重试 if status == "ok" or status == "coupon_popup": break @@ -636,6 +714,30 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st # 倒计时不能为0(至少应该有几秒) if remain_seconds == 0 and not time_text: return False, "countdown_zero_and_no_time_text" + # 倒计时合理性检查:如果 time_text 存在,验证倒计时与 time_text 是否一致 + if time_text: + try: + # 解析 time_text 为秒数 + import re + m = re.search(r"(\d{1,2})[::](\d{1,2})", time_text) + if m: + mm = int(m.group(1)) + ss = int(m.group(2)) + # 如果秒数>=60,尝试交换分秒 + if ss >= 60 and mm < 60: + mm, ss = ss, mm + # 如果秒数仍然>=60,进行进位 + if ss >= 60: + mm += ss // 60 + ss = ss % 60 + text_seconds = mm * 60 + ss + # 允许一定误差(±10%),但差异过大则判定为识别错误 + if text_seconds > 0: + diff_ratio = abs(remain_seconds - text_seconds) / max(text_seconds, 1.0) + if diff_ratio > 0.15: # 差异超过15%视为不一致 + return False, f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)" + except Exception: + pass # 检查5:参与人数应该合理(不能是负数) if participants < 0: diff --git a/douyin_high_value_room.py b/douyin_high_value_room.py index c4dcf96..e69de29 100644 --- a/douyin_high_value_room.py +++ b/douyin_high_value_room.py @@ -1,247 +0,0 @@ -from __future__ import annotations - -""" -高价值直播间记录模块 -==================== - -提供高价值直播间的记录和管理功能: -- 跨运行持久化(写入 high_value_rooms.json) -- 记录最大价值、最后价值、首次/最后记录时间 -- 记录次数统计 -- 支持别名和合并逻辑 -""" - -from typing import Any, Dict, Optional -import os -import time -import re -import difflib - -from path_config import get_high_value_rooms_path -import douyin_reservation - - -def _normalize_room_title(t: str) -> str: - """规范化直播间标题(与 douyin_fudai_detail 中的逻辑一致)。""" - try: - s = str(t or "").strip() - except Exception: - return "" - s = s.replace("\r", " ").replace("\n", " ").strip() - s = re.sub(r"\s+", "", s) - for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): - s = s.replace(w, "") - s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s) - s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s) - s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s) - s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s) - return s - - -def _resolve_high_value_room_key( - title_norm: str, - title_raw: str, - pos_seen0: Optional[int] = None, - high_value_rooms_map: Optional[Dict[str, Dict[str, Any]]] = None, -) -> tuple[str, str, str, float]: - """将本次识别结果映射到"历史表"里的 canonical key。 - - 返回:(key, key_kind, merged_from, merged_ratio) - - merged_from:本次候选 key(若发生合并) - - merged_ratio:合并相似度 - """ - if not high_value_rooms_map: - high_value_rooms_map = {} - - key0 = title_norm - key_kind0 = "norm" - - if not key0: - # 退化为使用原始文本 - try: - s = str(title_raw or "") - s = s.replace("\r", " ").replace("\n", " ").replace("\t", " ") - s = re.sub(r"\s+", "", s).strip() - if len(s) > 64: - s = s[:64] - key0 = s or "unknown" - except Exception: - key0 = "unknown" - - # 尝试在历史表中找到相似度最高的 key - best_key = "" - best_ratio = 0.0 - best_pos_ok = False - - for k, v in high_value_rooms_map.items(): - if not k: - continue - try: - ratio = float(difflib.SequenceMatcher(None, key0, k).ratio()) - except Exception: - ratio = 0.0 - - pos_ok = False - if pos_seen0 is not None: - try: - stored_pos = int(v.get("pos_seen") or 0) - if stored_pos > 0 and abs(stored_pos - pos_seen0) <= 3: - pos_ok = True - except Exception: - pass - - if ratio > best_ratio: - best_ratio = ratio - best_key = str(k) - best_pos_ok = bool(pos_ok) - - if best_key: - if best_pos_ok and best_ratio >= 0.80: - return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio) - if best_ratio >= 0.88: - return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio) - - return key0, key_kind0, "", 0.0 - - -def touch_high_value_room( - analyser: Any, - title_norm: str, - title_raw: str, - prize_value_yuan: float, - reason: str = "", - increment: bool = True, - key_kind: str = "norm", - content: str = "", - pos_seen: Optional[int] = None, - alias_norm: str = "", - alias_raw: str = "", - merged_from: str = "", - merged_ratio: Optional[float] = None, -) -> None: - """记录高价值直播间信息。 - - 参数: - analyser: 分析器对象 - title_norm: 规范化后的直播间标题 - title_raw: 原始直播间标题 - prize_value_yuan: 奖品价值(元) - reason: 记录原因 - increment: 是否增加计数 - key_kind: key 类型 - content: 福袋内容 - pos_seen: 记录时的位置 - alias_norm: 别名(规范化) - alias_raw: 别名(原始) - merged_from: 合并来源 - merged_ratio: 合并相似度 - """ - try: - # 获取高价值直播间映射 - high_value_rooms_path = get_high_value_rooms_path() - high_value_rooms_map = douyin_reservation.load_high_value_rooms_map(high_value_rooms_path) - - # 解析 key - key, key_kind_resolved, merged_from_resolved, merged_ratio_resolved = _resolve_high_value_room_key( - title_norm, title_raw, pos_seen, high_value_rooms_map - ) - - if not key: - return - - # 如果发生合并,使用合并后的值 - if merged_from_resolved and merged_from_resolved != key: - merged_from = merged_from_resolved - if merged_ratio_resolved > 0: - merged_ratio = merged_ratio_resolved - if key_kind_resolved: - key_kind = key_kind_resolved - - now0 = time.time() - ex = high_value_rooms_map.get(key) or {} - - def _append_unique_list_field(field: str, val: str, cap: int = 8) -> None: - if not val: - return - try: - arr = ex.get(field) - if not isinstance(arr, list): - arr = [] - if val not in arr: - arr.insert(0, val) - if len(arr) > cap: - arr = arr[:cap] - ex[field] = arr - except Exception: - pass - - if float(ex.get("first_seen_ts") or 0.0) <= 0: - ex["first_seen_ts"] = now0 - ex["last_seen_ts"] = now0 - if "seen_count" not in ex: - ex["seen_count"] = 0 - if increment: - try: - ex["seen_count"] = int(ex.get("seen_count") or 0) + 1 - except Exception: - ex["seen_count"] = 1 - if pos_seen is not None: - try: - ex["pos_seen"] = int(pos_seen) - except Exception: - pass - ex["pos_updated_ts"] = now0 - if title_raw: - ex["room_title_raw_last"] = str(title_raw) - if alias_raw: - _append_unique_list_field("alias_raw", str(alias_raw), cap=8) - if alias_norm and alias_norm != key: - _append_unique_list_field("alias_norm", str(alias_norm), cap=8) - if merged_from and merged_from != key: - ex["merged_from_last"] = str(merged_from) - if merged_ratio is not None: - try: - ex["merged_ratio_last"] = float(merged_ratio) - except Exception: - pass - if key_kind: - ex["key_kind"] = str(key_kind) - if content: - ex["last_content"] = str(content) - try: - pv = float(prize_value_yuan or 0.0) - except Exception: - pv = 0.0 - ex["last_prize_value_yuan"] = pv - try: - ex["max_prize_value_yuan"] = max(float(ex.get("max_prize_value_yuan") or 0.0), pv) - except Exception: - ex["max_prize_value_yuan"] = pv - - high_value_rooms_map[key] = ex - - # 写入状态文件 - douyin_reservation.write_high_value_rooms_state(high_value_rooms_path, high_value_rooms_map, reason=reason) - - try: - analyser._log_kv( - "高价值直播间", - "已记录高价值直播间", - room_title=key[:30], - prize_value_yuan=pv, - max_prize_value_yuan=ex.get("max_prize_value_yuan", 0), - seen_count=ex.get("seen_count", 0), - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "高价值直播间", - "记录高价值直播间失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - diff --git a/douyin_logger.py b/douyin_logger.py new file mode 100644 index 0000000..4173294 --- /dev/null +++ b/douyin_logger.py @@ -0,0 +1,304 @@ +""" +增强的日志系统配置模块 +==================== + +功能: +1. 标准 Python logging 模块集成 +2. 日志级别管理(DEBUG, INFO, WARNING, ERROR, CRITICAL) +3. 日志轮转(按大小和时间) +4. 清晰的日志格式(时间戳、级别、模块、函数、行号) +5. 异常堆栈完整记录 +6. 根据环境动态调整日志级别 +""" + +from __future__ import annotations + +import logging +import logging.handlers +import os +import sys +import json +from typing import Optional, Dict, Any +from datetime import datetime +import path_config + + +# 日志配置默认值 +DEFAULT_LOG_LEVEL = "INFO" +DEFAULT_LOG_FILE = "logs/unified.log" +DEFAULT_MAX_BYTES = 10 * 1024 * 1024 # 10MB +DEFAULT_BACKUP_COUNT = 5 +DEFAULT_WHEN = "midnight" # 每天午夜轮转 +DEFAULT_INTERVAL = 1 # 每1天轮转一次 + + +def get_log_config() -> Dict[str, Any]: + """从 config.json 读取日志配置""" + try: + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + return config.get("logging", {}) + except Exception: + pass + return {} + + +def get_log_level() -> str: + """获取日志级别(从配置或环境变量)""" + # 优先检查环境变量(开发调试时使用) + env_level = os.environ.get("DOUYIN_LOG_LEVEL", "").upper() + if env_level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): + return env_level + + # 从配置文件读取 + log_config = get_log_config() + level = log_config.get("level", DEFAULT_LOG_LEVEL).upper() + if level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): + return level + + return DEFAULT_LOG_LEVEL + + +def get_log_file_path() -> str: + """获取日志文件路径""" + log_config = get_log_config() + path = log_config.get("file_path", DEFAULT_LOG_FILE) + if not os.path.isabs(path): + path = os.path.join(path_config.PROJECT_ROOT, path) + return path + + +def get_rotation_config() -> Dict[str, Any]: + """获取日志轮转配置""" + log_config = get_log_config() + rotation = log_config.get("rotation", {}) + + return { + "enabled": rotation.get("enabled", True), + "max_bytes": rotation.get("max_bytes", DEFAULT_MAX_BYTES), + "backup_count": rotation.get("backup_count", DEFAULT_BACKUP_COUNT), + "when": rotation.get("when", DEFAULT_WHEN), + "interval": rotation.get("interval", DEFAULT_INTERVAL), + } + + +def setup_logging( + logger_name: str = "douyin", + log_file: Optional[str] = None, + log_level: Optional[str] = None, + enable_console: bool = True, + enable_file: bool = True, +) -> logging.Logger: + """ + 配置并返回一个增强的 logger 实例 + + 参数: + logger_name: logger 名称 + log_file: 日志文件路径(None 则从配置读取) + log_level: 日志级别(None 则从配置读取) + enable_console: 是否启用控制台输出 + enable_file: 是否启用文件输出 + + 返回: + 配置好的 logger 实例 + """ + logger = logging.getLogger(logger_name) + + # 避免重复配置 + if logger.handlers: + return logger + + # 设置日志级别 + if log_level is None: + log_level = get_log_level() + level = getattr(logging, log_level.upper(), logging.INFO) + logger.setLevel(level) + + # 日志格式:时间戳 - [级别] - 模块名:函数名:行号 - 消息 + detailed_format = ( + "%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s" + ) + simple_format = "%(asctime)s - [%(levelname)s] - %(message)s" + + formatter = logging.Formatter( + detailed_format, + datefmt="%Y-%m-%d %H:%M:%S" + ) + + # 控制台处理器 + if enable_console: + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setLevel(level) + console_handler.setFormatter(formatter) + logger.addHandler(console_handler) + + # 文件处理器(带轮转) + if enable_file: + if log_file is None: + log_file = get_log_file_path() + + # 确保日志目录存在 + log_dir = os.path.dirname(log_file) + if log_dir: + os.makedirs(log_dir, exist_ok=True) + + rotation_config = get_rotation_config() + + if rotation_config.get("enabled", True): + # 使用 TimedRotatingFileHandler(按时间轮转) + try: + file_handler = logging.handlers.TimedRotatingFileHandler( + log_file, + when=rotation_config.get("when", DEFAULT_WHEN), + interval=rotation_config.get("interval", DEFAULT_INTERVAL), + backupCount=rotation_config.get("backup_count", DEFAULT_BACKUP_COUNT), + encoding="utf-8-sig", # 使用 BOM 避免 Windows 乱码 + errors="replace", + ) + except Exception: + # 如果时间轮转失败,回退到大小轮转 + try: + file_handler = logging.handlers.RotatingFileHandler( + log_file, + maxBytes=rotation_config.get("max_bytes", DEFAULT_MAX_BYTES), + backupCount=rotation_config.get("backup_count", DEFAULT_BACKUP_COUNT), + encoding="utf-8-sig", + errors="replace", + ) + except Exception: + # 如果都失败,使用普通 FileHandler + file_handler = logging.FileHandler( + log_file, + encoding="utf-8-sig", + errors="replace", + ) + else: + # 不使用轮转,直接使用 FileHandler + file_handler = logging.FileHandler( + log_file, + encoding="utf-8-sig", + errors="replace", + ) + + file_handler.setLevel(level) + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + return logger + + +def get_logger(name: str = "douyin") -> logging.Logger: + """获取或创建 logger 实例(单例模式)""" + logger = logging.getLogger(name) + if not logger.handlers: + # 如果还没有配置,进行初始化 + setup_logging(name) + return logger + + +class LogContext: + """日志上下文管理器,用于记录函数调用、参数、返回值、耗时等""" + + def __init__( + self, + logger: logging.Logger, + func_name: str, + level: int = logging.DEBUG, + log_args: bool = True, + log_result: bool = True, + log_duration: bool = True, + ): + self.logger = logger + self.func_name = func_name + self.level = level + self.log_args = log_args + self.log_result = log_result + self.log_duration = log_duration + self.start_time: Optional[float] = None + self.args: tuple = () + self.kwargs: dict = {} + + def __enter__(self): + import time + self.start_time = time.time() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + import time + duration = time.time() - self.start_time if self.start_time else 0 + + # 记录函数调用信息 + if self.log_args and (self.args or self.kwargs): + args_str = ", ".join([repr(a) for a in self.args]) + kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in self.kwargs.items()]) + params_str = ", ".join(filter(None, [args_str, kwargs_str])) + self.logger.log( + self.level, + f"[函数调用] {self.func_name}({params_str})" + ) + + # 记录异常 + if exc_type is not None: + self.logger.exception( + f"[函数异常] {self.func_name} 发生异常: {exc_type.__name__}", + exc_info=(exc_type, exc_val, exc_tb) + ) + # 记录耗时 + elif self.log_duration: + self.logger.log( + self.level, + f"[函数完成] {self.func_name} 耗时: {duration:.3f}秒" + ) + + return False # 不抑制异常 + + +def log_function_call( + logger: logging.Logger, + func_name: str, + args: tuple = (), + kwargs: dict = None, + result: Any = None, + duration: float = None, + level: int = logging.DEBUG, +): + """记录函数调用的详细信息""" + if kwargs is None: + kwargs = {} + + parts = [f"[函数调用] {func_name}"] + + # 参数 + if args or kwargs: + args_str = ", ".join([repr(a) for a in args]) + kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in kwargs.items()]) + params_str = ", ".join(filter(None, [args_str, kwargs_str])) + parts.append(f"参数: {params_str}") + + # 返回值 + if result is not None: + parts.append(f"返回值: {repr(result)}") + + # 耗时 + if duration is not None: + parts.append(f"耗时: {duration:.3f}秒") + + logger.log(level, " | ".join(parts)) + + +# 全局 logger 实例(延迟初始化) +_global_logger: Optional[logging.Logger] = None + + +def get_global_logger() -> logging.Logger: + """获取全局 logger 实例""" + global _global_logger + if _global_logger is None: + _global_logger = setup_logging("douyin") + return _global_logger + + + + diff --git a/douyin_logging.py b/douyin_logging.py new file mode 100644 index 0000000..12e7738 --- /dev/null +++ b/douyin_logging.py @@ -0,0 +1,336 @@ +""" +日志系统配置与工具模块 +==================== + +功能: +1. 标准 logging 配置(支持日志轮转、级别管理) +2. 增强的日志记录工具(自动记录调用者信息、异常堆栈等) +3. 性能监控装饰器(记录函数调用耗时) +4. 上下文管理器(记录代码块执行时间) +""" + +from __future__ import annotations + +import os +import sys +import time +import logging +import logging.handlers +import traceback +import inspect +from datetime import datetime +from typing import Optional, Callable, Any, Dict +from functools import wraps +import path_config + + +# 全局日志配置 +_logging_configured = False +_logger_cache: Dict[str, logging.Logger] = {} + + +def get_logger(name: str = None) -> logging.Logger: + """获取指定名称的 logger,如果未配置则自动配置""" + if not _logging_configured: + configure_logging() + + if name is None: + # 自动获取调用者模块名 + try: + frame = inspect.currentframe() + if frame and frame.f_back: + caller_frame = frame.f_back + name = caller_frame.f_globals.get('__name__', 'root') + else: + name = 'root' + except Exception: + name = 'root' + finally: + if 'frame' in locals(): + del frame + + if name not in _logger_cache: + _logger_cache[name] = logging.getLogger(name) + + return _logger_cache[name] + + +def configure_logging( + log_level: str = None, + log_file: str = None, + max_bytes: int = 10 * 1024 * 1024, # 10MB + backup_count: int = 5, + enable_console: bool = True, + enable_file: bool = True, +) -> None: + """配置日志系统 + + 参数: + log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL),默认从 config.json 读取 + log_file: 日志文件路径,默认使用 logs/unified.log + max_bytes: 单个日志文件最大大小(字节),超过后轮转 + backup_count: 保留的备份文件数量 + enable_console: 是否输出到控制台 + enable_file: 是否输出到文件 + """ + global _logging_configured + + # 从 config.json 读取配置 + if log_level is None or log_file is None: + try: + import json + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, 'r', encoding='utf-8') as f: + config = json.load(f) + if log_level is None: + log_level = config.get('log_level', 'INFO') + if log_file is None: + log_file = config.get('log_unified_path', 'logs/unified.log') + except Exception: + if log_level is None: + log_level = 'INFO' + if log_file is None: + log_file = 'logs/unified.log' + + # 规范化日志级别 + numeric_level = getattr(logging, log_level.upper(), logging.INFO) + + # 确保日志目录存在 + if enable_file: + log_dir = os.path.dirname(log_file) + if log_dir and not os.path.isabs(log_file): + log_file = os.path.join(path_config.PROJECT_ROOT, log_file) + log_dir = os.path.dirname(log_file) + if log_dir: + os.makedirs(log_dir, exist_ok=True) + + # 配置根 logger + root_logger = logging.getLogger() + root_logger.setLevel(numeric_level) + + # 清除已有的 handlers(避免重复配置) + root_logger.handlers.clear() + + # 日志格式:时间戳 - [级别] - 模块名:函数名:行号 - 消息 + detailed_format = ( + '%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s' + ) + simple_format = '%(asctime)s - [%(levelname)s] - %(message)s' + + # 控制台输出 + if enable_console: + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setLevel(numeric_level) + console_formatter = logging.Formatter( + simple_format, + datefmt='%Y-%m-%d %H:%M:%S' + ) + console_handler.setFormatter(console_formatter) + root_logger.addHandler(console_handler) + + # 文件输出(带轮转) + if enable_file: + try: + # 使用 RotatingFileHandler 实现日志轮转 + file_handler = logging.handlers.RotatingFileHandler( + log_file, + maxBytes=max_bytes, + backupCount=backup_count, + encoding='utf-8-sig', # 使用 BOM 避免 Windows 乱码 + errors='replace' + ) + file_handler.setLevel(numeric_level) + file_formatter = logging.Formatter( + detailed_format, + datefmt='%Y-%m-%d %H:%M:%S.%f' + ) + file_formatter.default_msec_format = '%s.%03d' # 毫秒精度 + file_handler.setFormatter(file_formatter) + root_logger.addHandler(file_handler) + except Exception as e: + # 文件 handler 创建失败,只输出到控制台 + try: + print(f"[日志配置] 警告:无法创建日志文件 {log_file}: {e}") + except Exception: + pass + + _logging_configured = True + + +def log_function_call( + logger: Optional[logging.Logger] = None, + log_args: bool = True, + log_result: bool = False, + log_time: bool = True, + min_duration: float = 0.0, # 只记录超过此耗时的调用 +): + """装饰器:记录函数调用信息(参数、返回值、耗时) + + 参数: + logger: 使用的 logger,默认自动获取 + log_args: 是否记录函数参数 + log_result: 是否记录返回值 + log_time: 是否记录执行时间 + min_duration: 最小耗时阈值(秒),低于此值不记录耗时 + """ + def decorator(func: Callable) -> Callable: + @wraps(func) + def wrapper(*args, **kwargs): + if logger is None: + _logger = get_logger() + else: + _logger = logger + + func_name = func.__name__ + start_time = time.time() + + # 记录函数调用 + if log_args: + args_str = ', '.join([str(arg)[:100] for arg in args[:3]]) # 只记录前3个参数,避免过长 + kwargs_str = ', '.join([f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]]) + call_info = f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})" + if len(args) > 3 or len(kwargs) > 3: + call_info += "..." + _logger.debug(f"调用函数: {call_info}") + + # 执行函数 + try: + result = func(*args, **kwargs) + elapsed = time.time() - start_time + + # 记录执行结果 + if log_time and elapsed >= min_duration: + _logger.debug(f"函数 {func_name} 执行完成,耗时: {elapsed:.3f}秒") + + if log_result: + result_str = str(result)[:200] # 限制长度 + _logger.debug(f"函数 {func_name} 返回值: {result_str}") + + return result + except Exception as e: + elapsed = time.time() - start_time + _logger.exception( + f"函数 {func_name} 执行异常,耗时: {elapsed:.3f}秒", + exc_info=True + ) + raise + + return wrapper + return decorator + + +class LogContext: + """上下文管理器:记录代码块执行时间""" + + def __init__( + self, + message: str, + logger: Optional[logging.Logger] = None, + level: str = "DEBUG", + log_on_exit: bool = True, + ): + self.message = message + self.logger = logger or get_logger() + self.level = getattr(logging, level.upper(), logging.DEBUG) + self.log_on_exit = log_on_exit + self.start_time = None + + def __enter__(self): + self.start_time = time.time() + self.logger.log(self.level, f"{self.message} [开始]") + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.log_on_exit: + return False + + elapsed = time.time() - self.start_time + + if exc_type is None: + self.logger.log( + self.level, + f"{self.message} [完成] 耗时: {elapsed:.3f}秒" + ) + else: + self.logger.log( + logging.ERROR, + f"{self.message} [异常] 耗时: {elapsed:.3f}秒", + exc_info=(exc_type, exc_val, exc_tb) + ) + + return False # 不抑制异常 + + +def get_caller_info(skip_frames: int = 0) -> Dict[str, Any]: + """获取调用者信息(模块名、函数名、行号) + + 参数: + skip_frames: 跳过的栈帧数(用于在装饰器中获取真正的调用者) + + 返回: + 包含 module, function, line, file 的字典 + """ + try: + frame = inspect.currentframe() + if frame: + # 跳过当前函数和装饰器 + for _ in range(skip_frames + 2): + if frame.f_back: + frame = frame.f_back + else: + break + + if frame: + return { + 'module': os.path.basename(frame.f_code.co_filename), + 'function': frame.f_code.co_name, + 'line': frame.f_lineno, + 'file': frame.f_code.co_filename, + } + except Exception: + pass + finally: + if 'frame' in locals(): + del frame + + return { + 'module': 'unknown', + 'function': 'unknown', + 'line': 0, + 'file': 'unknown', + } + + +def format_exception_info(exc_info=None) -> str: + """格式化异常信息为字符串 + + 参数: + exc_info: 异常信息元组 (type, value, traceback),默认使用 sys.exc_info() + + 返回: + 格式化的异常堆栈字符串 + """ + if exc_info is None: + exc_info = sys.exc_info() + + if exc_info[0] is None: + return "" + + try: + return ''.join(traceback.format_exception(*exc_info)) + except Exception: + return f"异常: {exc_info[1]}" + + +# 自动配置日志(在模块导入时) +if not _logging_configured: + # 延迟配置,避免在导入时读取 config.json 失败 + try: + configure_logging() + except Exception: + pass + + + + diff --git a/douyin_pixel.py b/douyin_pixel.py index b759e00..5a38bd9 100644 --- a/douyin_pixel.py +++ b/douyin_pixel.py @@ -103,6 +103,14 @@ def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: fl if x1 >= x2 or y1 >= y2: return False + # 双截图记录:保存实时操作截图(像素检测区域) + try: + 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") + except Exception: + pass + red_count = 0 total_samples = 0 step_x = max(1, (x2 - x1) // 10) @@ -124,7 +132,18 @@ def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: fl return False red_ratio = red_count / total_samples - return red_ratio >= red_ratio_threshold + result = red_ratio >= red_ratio_threshold + + # 双截图记录:保存成功识别存档截图 + if result: + try: + import douyin_screenshot_manager + detect_roi = pic_rgb.crop((x1, y1, x2, y2)) + douyin_screenshot_manager.save_last_success(detect_roi, operation_type="pixel_detect") + except Exception: + pass + + return result except Exception: return False diff --git a/douyin_reservation_logic.py b/douyin_reservation_logic.py index 6fa8741..41a9fa7 100644 --- a/douyin_reservation_logic.py +++ b/douyin_reservation_logic.py @@ -231,6 +231,67 @@ def handle_queue_full_wait_at_earliest( except Exception: pass + # 先进行阶段诊断,处理弹窗等,避免卡死在某个页面 + try: + # 确保有最新截图 + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass + + import douyin_stage + stage, reason = douyin_stage.diagnose_stage_from_current_screen(analyser) + + # 如果检测到需要处理的弹窗或异常状态,先处理 + if stage in ("LUCKY_DRAW_RESULT", "COUPON_POPUP", "SHOPPING_REDPACKET_POPUP", "FANS_CLUB_JOIN"): + try: + analyser._log_kv( + "预约", + "[预约] 回退前检测到弹窗,先处理", + stage=stage, + reason=reason, + ) + except Exception: + pass + + # 处理弹窗:点击返回或关闭按钮 + try: + analyser.operation.click_back(analyser.device_id) + time.sleep(0.5) + # 重新截图并再次诊断,确保已处理 + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass + stage, reason = douyin_stage.diagnose_stage_from_current_screen(analyser) + except Exception: + pass + elif stage == "FUDai_DETAIL": + # 如果在福袋详情页,先关闭详情页 + try: + analyser._log_kv( + "预约", + "[预约] 回退前检测到在福袋详情页,先关闭", + stage=stage, + ) + except Exception: + pass + try: + analyser.operation.click_back(analyser.device_id) + time.sleep(0.5) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] 回退前阶段诊断失败,继续执行回退", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + # 先轻微下滑一次,确保在直播列表中 try: swipe_down_back_callback() diff --git a/douyin_screenshot_manager.py b/douyin_screenshot_manager.py new file mode 100644 index 0000000..8a22e43 --- /dev/null +++ b/douyin_screenshot_manager.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +""" +截图管理模块:双截图记录机制 +============================ + +功能: +1. 实时操作截图(latest_attempt.png):每次识别操作都覆盖保存 +2. 成功识别存档截图(last_success.png):仅在成功时保存,不会被覆盖 +3. OCR文件夹清理:自动清理旧的OCR图片 +""" + +import os +import shutil +import time +from typing import Optional, Tuple +from PIL import Image +import path_config + + +def get_ocr_dir() -> str: + """获取OCR目录路径""" + return os.path.join(path_config.get_pic_dir(), "ocr") + + +def get_category_for_picname(picname: str) -> str: + """根据图片名称判断应该保存到哪个分类目录 + + 参数: + picname: 图片名称(不含扩展名) + + 返回: + 分类目录名称,如 "fudai", "live_room", "popups", "buttons", "stage_diag", "others" + """ + picname_lower = picname.lower() + + # 福袋相关 + if any(keyword in picname_lower for keyword in ["福袋", "fudai"]): + return "fudai" + + # 直播间相关 + if any(keyword in picname_lower for keyword in [ + "live_room", "直播间", "直播列表", "直播广场", "直播状态", "直播验证" + ]): + return "live_room" + + # 弹窗相关 + if any(keyword in picname_lower for keyword in [ + "抽奖结果", "无奖励", "优惠券", "购物红包", "奖励通知", "订单确认", + "lucky_draw", "coupon", "redpacket", "reward", "order" + ]): + return "popups" + + # 按钮相关 + if any(keyword in picname_lower for keyword in [ + "参与按钮", "粉丝团", "attend_button", "fans_club" + ]): + return "buttons" + + # 阶段诊断相关 + if any(keyword in picname_lower for keyword in [ + "推荐页", "关注列表", "直播列表标签", "recommend", "follow", "live_list" + ]): + return "stage_diag" + + # 其他 + return "others" + + +def get_latest_attempt_path(operation_type: str = "general") -> str: + """获取实时操作截图路径 + + 参数: + operation_type: 操作类型,可选值: + - "pixel" 或 "pixel_detect": 像素检测 + - "ocr": OCR识别 + - "template" 或 "template_match": 模板匹配 + - 其他: 通用操作 + """ + # 规范化操作类型 + if operation_type.startswith("pixel"): + type_key = "pixel" + elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"): + type_key = "ocr" + elif operation_type.startswith("template"): + type_key = "template" + else: + type_key = "general" + + return os.path.join(get_ocr_dir(), f"latest_attempt_{type_key}.png") + + +def get_last_success_path(operation_type: str = "general") -> str: + """获取成功识别存档截图路径 + + 参数: + operation_type: 操作类型,可选值: + - "pixel" 或 "pixel_detect": 像素检测 + - "ocr": OCR识别 + - "template" 或 "template_match": 模板匹配 + - 其他: 通用操作 + """ + # 规范化操作类型 + if operation_type.startswith("pixel"): + type_key = "pixel" + elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"): + type_key = "ocr" + elif operation_type.startswith("template"): + type_key = "template" + else: + type_key = "general" + + return os.path.join(get_ocr_dir(), f"last_success_{type_key}.png") + + +def ensure_ocr_dir() -> None: + """确保OCR目录存在""" + ocr_dir = get_ocr_dir() + os.makedirs(ocr_dir, exist_ok=True) + + +def cleanup_ocr_dir( + keep_latest_attempt: bool = True, + keep_last_success: bool = True, + keep_success_files: bool = True, + max_files: int = 50, +) -> int: + """清理OCR目录中的旧文件 + + 参数: + keep_latest_attempt: 是否保留所有 latest_attempt_*.png 文件 + keep_last_success: 是否保留所有 last_success_*.png 文件 + keep_success_files: 是否保留所有 _success.png 文件 + max_files: 最多保留的文件数(不包括特殊文件) + + 返回: + 清理的文件数量 + """ + try: + ocr_dir = get_ocr_dir() + if not os.path.exists(ocr_dir): + return 0 + + files = [] + for f in os.listdir(ocr_dir): + file_path = os.path.join(ocr_dir, f) + if os.path.isfile(file_path) and f.lower().endswith('.png'): + # 检查是否为特殊文件 + is_special = False + if f.startswith("latest_attempt_") and keep_latest_attempt: + is_special = True + elif f.startswith("last_success_") and keep_last_success: + is_special = True + elif f.endswith("_success.png") and keep_success_files: + is_special = True + + if not is_special: + files.append((file_path, os.path.getmtime(file_path))) + + # 按修改时间排序,保留最新的 + files.sort(key=lambda x: x[1], reverse=True) + + # 删除超出限制的文件 + deleted_count = 0 + for file_path, _ in files[max_files:]: + try: + os.remove(file_path) + deleted_count += 1 + except Exception: + pass + + return deleted_count + except Exception: + return 0 + + +def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool: + """保存实时操作截图(覆盖保存) + + 参数: + image: PIL Image 对象 + operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") + + 返回: + 是否保存成功 + """ + try: + ensure_ocr_dir() + path = get_latest_attempt_path(operation_type) + image.save(path, "PNG") + return True + except Exception as e: + try: + print(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") + except Exception: + pass + return False + + +def save_last_success(image: Image.Image, operation_type: str = "") -> bool: + """保存成功识别存档截图(不覆盖,仅成功时保存) + + 参数: + image: PIL Image 对象 + operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") + + 返回: + 是否保存成功 + """ + try: + ensure_ocr_dir() + path = get_last_success_path(operation_type) + image.save(path, "PNG") + return True + except Exception as e: + try: + print(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") + except Exception: + pass + return False + + +def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool: + """从文件保存实时操作截图 + + 参数: + source_path: 源图片文件路径 + operation_type: 操作类型 + + 返回: + 是否保存成功 + """ + try: + if not os.path.exists(source_path): + return False + image = Image.open(source_path) + return save_latest_attempt(image, operation_type) + except Exception as e: + try: + print(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") + except Exception: + pass + return False + + +def save_success_from_file(source_path: str, operation_type: str = "") -> bool: + """从文件保存成功识别存档截图 + + 参数: + source_path: 源图片文件路径 + operation_type: 操作类型 + + 返回: + 是否保存成功 + """ + try: + if not os.path.exists(source_path): + return False + image = Image.open(source_path) + return save_last_success(image, operation_type) + except Exception as e: + try: + print(f"[截图管理] 从文件保存 last_success.png 失败: {e}") + except Exception: + pass + return False + diff --git a/douyin_swipe_ops.py b/douyin_swipe_ops.py index 6f7da97..df061c0 100644 --- a/douyin_swipe_ops.py +++ b/douyin_swipe_ops.py @@ -51,3 +51,54 @@ def swipe_up_switch_live(analyser: Any) -> None: analyser.swipe(start_x_base, start_y_base, end_x_base, end_y_base, 300) except Exception: pass + + +def swipe_down_back_live(analyser: Any) -> None: + """上划回退到上一个直播间(基础版封装)。 + + 在直播间内,向上滑动可以回退到上一个直播间。 + 采用 1080x2400 基准坐标,在屏幕中下部向上滑一段距离。 + """ + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + + device_id = getattr(analyser, "device_id", "") + + # 基准坐标(1080x2400):从中下部往上滑(与上滑切换相同方向) + start_x_base = 540 + start_y_base = 1700 + end_x_base = 540 + end_y_base = 700 + + start_x = start_x_base * rx // 1080 + end_x = end_x_base * rx // 1080 + start_y = start_y_base * ry // 2400 + end_y = end_y_base * ry // 2400 + + try: + analyser._log_kv( + "滑动", + "swipe_down_back_live:上划回退到上一个直播间", + start_x=start_x_base, + start_y=start_y_base, + end_x=end_x_base, + end_y=end_y_base, + ) + except Exception: + pass + + # 优先调用底层 swipe,失败则静默忽略(不影响主流程) + try: + analyser.operation.swipe(device_id, start_x, start_y, end_x, end_y, 300) + except Exception: + try: + # 如果 analyser 自身提供 swipe 封装,则退回到该封装 + analyser.swipe(start_x_base, start_y_base, end_x_base, end_y_base, 300) + except Exception: + pass diff --git a/douyin_utils.py b/douyin_utils.py index d19f939..2bcae35 100644 --- a/douyin_utils.py +++ b/douyin_utils.py @@ -40,7 +40,10 @@ def normalize_countdown_text(text: str) -> str: mm = int(m.group(1)) ss = int(m.group(2)) # 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释 - if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: + # 或者秒数不合法(>=60),也尝试交换 + total1 = mm * 60 + ss + total2 = ss * 60 + mm + if (total1 > 900 and total2 <= 900) or (ss >= 60 and mm < 60): mm, ss = ss, mm return f"{mm:02d}:{ss:02d}后开奖" # 识别错序:54后开奖04 @@ -51,6 +54,23 @@ def normalize_countdown_text(text: str) -> str: if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: mm, ss = ss, mm return f"{mm:02d}:{ss:02d}后开奖" + # 纯 mm:ss 格式(不带"后开奖"):11:17 / 05:11 + m = re.search(r"^(\d{1,2})[::](\d{1,2})$", t) + if m: + mm = int(m.group(1)) + ss = int(m.group(2)) + # 检查是否需要交换分秒: + # 1. 秒数不合法(>=60)且交换后合法 + # 2. 总时间>15分钟且交换后<=15分钟 + total1 = mm * 60 + ss + total2 = ss * 60 + mm + if (ss >= 60 and mm < 60) or (total1 > 900 and total2 <= 900): + mm, ss = ss, mm + # 如果秒数仍然>=60,进行进位处理 + if ss >= 60: + mm += ss // 60 + ss = ss % 60 + return f"{mm:02d}:{ss:02d}" # 纯数字 1137 / 5404 digits = ''.join(ch for ch in t if ch.isdigit()) if len(digits) == 4: diff --git a/fix_indent_smart.py b/fix_indent_smart.py new file mode 100644 index 0000000..d0b613e --- /dev/null +++ b/fix_indent_smart.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +""" +智能修复 Python 文件中的缩进语法错误 +===================================== + +使用 AST 和 tokenize 来更准确地修复缩进问题 +""" + +import ast +import tokenize +import io +import sys +from typing import List, Tuple, Optional + + +def analyze_indentation_errors(file_path: str) -> List[Tuple[int, str, str]]: + """分析文件中的缩进错误 + + 返回: [(行号, 错误类型, 建议修复)] + """ + errors = [] + + try: + with open(file_path, 'rb') as f: + tokens = list(tokenize.tokenize(f.readline)) + except Exception as e: + return [(-1, "读取文件失败", str(e))] + + # 分析 try-except 块 + try_blocks = [] + for i, token in enumerate(tokens): + if token.type == tokenize.NAME and token.string == 'try': + # 查找对应的 except + try_indent = token.start[1] # 列号 + try_blocks.append((token.start[0], try_indent)) # (行号, 缩进) + + # 检查 except 是否与对应的 try 对齐 + for try_line, try_indent in try_blocks: + # 查找这个 try 后面的 except + for i, token in enumerate(tokens): + if (token.type == tokenize.NAME and token.string == 'except' and + token.start[0] > try_line): + except_indent = token.start[1] + if except_indent != try_indent: + errors.append(( + token.start[0], + "except 缩进错误", + f"应该与 try (第 {try_line} 行) 对齐,当前缩进 {except_indent},应为 {try_indent}" + )) + break + + return errors + + +def fix_indentation_with_ast(file_path: str) -> Tuple[bool, str]: + """使用 AST 尝试修复缩进错误""" + try: + with open(file_path, 'r', encoding='utf-8') as f: + content = f.read() + + # 尝试解析 + try: + ast.parse(content) + return True, "文件语法正确" + except SyntaxError as e: + # 有语法错误,尝试修复 + lines = content.split('\n') + + # 修复常见的 except 缩进错误 + fixed_lines = [] + for i, line in enumerate(lines): + # 检查是否是 except 语句且缩进可能有问题 + if re.match(r'^\s{8,}except\s+', line): + # 向前查找 try + for j in range(i-1, max(-1, i-30), -1): + if re.match(r'^(\s*)try\s*:', lines[j]): + try_indent = len(re.match(r'^(\s*)', lines[j]).group(1)) + # 修复缩进 + fixed_line = ' ' * try_indent + line.lstrip() + fixed_lines.append(fixed_line) + break + else: + fixed_lines.append(line) + else: + fixed_lines.append(line) + + fixed_content = '\n'.join(fixed_lines) + + # 验证修复 + try: + ast.parse(fixed_content) + with open(file_path, 'w', encoding='utf-8') as f: + f.write(fixed_content) + return True, "修复成功" + except SyntaxError: + return False, "无法自动修复" + + except Exception as e: + return False, f"错误: {e}" + + +if __name__ == '__main__': + import re + if len(sys.argv) < 2: + print("使用方法: python fix_indent_smart.py <文件路径>") + sys.exit(1) + + file_path = sys.argv[1] + success, msg = fix_indentation_with_ast(file_path) + print(msg) + diff --git a/fix_indentation.py b/fix_indentation.py new file mode 100644 index 0000000..aacb3b4 --- /dev/null +++ b/fix_indentation.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +""" +批量修复 Python 文件中的缩进语法错误 +===================================== + +这个脚本可以修复常见的缩进导致的语法错误: +1. except 语句缩进错误 +2. else 语句缩进错误 +3. finally 语句缩进错误 +4. 其他常见的缩进问题 + +使用方法: + python fix_indentation.py <文件路径> + python fix_indentation.py --all # 修复当前目录下所有 .py 文件 +""" + +import re +import sys +import os +from pathlib import Path +from typing import List, Tuple + + +def fix_except_indentation(content: str) -> str: + """修复 except 语句的缩进错误""" + lines = content.split('\n') + fixed_lines = [] + i = 0 + + while i < len(lines): + line = lines[i] + + # 检查是否有缩进错误的 except + # 模式:行首有空格,但 except 前面有额外的缩进 + if re.match(r'^\s{4,}except\s+', line): + # 检查前一行是否是 try 块 + if i > 0: + prev_line = lines[i-1].rstrip() + # 查找对应的 try 语句 + try_indent = None + for j in range(i-1, max(-1, i-20), -1): # 向前查找最多20行 + if re.match(r'^(\s*)try\s*:', lines[j]): + try_indent = len(re.match(r'^(\s*)', lines[j]).group(1)) + break + + if try_indent is not None: + # 修复缩进:except 应该和 try 对齐 + fixed_line = ' ' * try_indent + line.lstrip() + fixed_lines.append(fixed_line) + i += 1 + continue + + fixed_lines.append(line) + i += 1 + + return '\n'.join(fixed_lines) + + +def fix_else_indentation(content: str) -> str: + """修复 else 语句的缩进错误""" + lines = content.split('\n') + fixed_lines = [] + i = 0 + + while i < len(lines): + line = lines[i] + + # 检查是否有缩进错误的 else + if re.match(r'^\s{4,}else\s*:', line): + # 查找对应的 if/for/while/try 语句 + if_indent = None + for j in range(i-1, max(-1, i-50), -1): # 向前查找 + prev_line = lines[j].rstrip() + if prev_line and not prev_line.strip().startswith('#'): + # 检查是否是 if/for/while/try 语句 + if re.match(r'^(\s*)(if|for|while|try|elif)\s+.*:', prev_line): + if_indent = len(re.match(r'^(\s*)', prev_line).group(1)) + break + + if if_indent is not None: + # 修复缩进:else 应该和 if/for/while/try 对齐 + fixed_line = ' ' * if_indent + line.lstrip() + fixed_lines.append(fixed_line) + i += 1 + continue + + fixed_lines.append(line) + i += 1 + + return '\n'.join(fixed_lines) + + +def fix_common_indentation_errors(content: str) -> str: + """修复常见的缩进错误模式""" + # 修复模式1: except Exception: 前面有多余缩进 + # 从: " except Exception:" + # 到: " except Exception:" (与对应的 try 对齐) + content = re.sub( + r'^(\s{8,})except\s+', + lambda m: ' ' * (len(m.group(1)) - 4) + 'except ', + content, + flags=re.MULTILINE + ) + + # 修复模式2: else: 前面有多余缩进 + content = re.sub( + r'^(\s{8,})else\s*:', + lambda m: ' ' * (len(m.group(1)) - 4) + 'else:', + content, + flags=re.MULTILINE + ) + + # 修复模式3: finally: 前面有多余缩进 + content = re.sub( + r'^(\s{8,})finally\s*:', + lambda m: ' ' * (len(m.group(1)) - 4) + 'finally:', + content, + flags=re.MULTILINE + ) + + return content + + +def fix_file(file_path: str, dry_run: bool = False) -> Tuple[bool, str]: + """修复单个文件的缩进错误 + + 返回: (是否成功, 错误信息) + """ + try: + with open(file_path, 'r', encoding='utf-8') as f: + original_content = f.read() + + # 先尝试用 Python 解析,如果成功则不需要修复 + try: + compile(original_content, file_path, 'exec') + return True, "文件语法正确,无需修复" + except SyntaxError: + pass # 有语法错误,继续修复 + + # 应用修复 + fixed_content = original_content + fixed_content = fix_except_indentation(fixed_content) + fixed_content = fix_else_indentation(fixed_content) + fixed_content = fix_common_indentation_errors(fixed_content) + + # 验证修复后的代码 + try: + compile(fixed_content, file_path, 'exec') + if not dry_run: + with open(file_path, 'w', encoding='utf-8') as f: + f.write(fixed_content) + return True, "修复成功" if not dry_run else "可以修复(预览模式)" + except SyntaxError as e: + return False, f"修复后仍有语法错误: {e}" + + except Exception as e: + return False, f"处理文件时出错: {e}" + + +def main(): + """主函数""" + if len(sys.argv) < 2: + print("使用方法:") + print(" python fix_indentation.py <文件路径>") + print(" python fix_indentation.py --all [目录路径]") + print(" python fix_indentation.py --dry-run <文件路径> # 预览模式,不实际修改") + sys.exit(1) + + dry_run = '--dry-run' in sys.argv + if dry_run: + sys.argv.remove('--dry-run') + + if sys.argv[1] == '--all': + # 修复目录下所有 .py 文件 + target_dir = sys.argv[2] if len(sys.argv) > 2 else '.' + py_files = list(Path(target_dir).rglob('*.py')) + + print(f"找到 {len(py_files)} 个 Python 文件") + success_count = 0 + fail_count = 0 + + for py_file in py_files: + # 跳过虚拟环境和缓存目录 + if any(skip in str(py_file) for skip in ['__pycache__', '.venv', 'venv', '.git']): + continue + + print(f"处理: {py_file}") + success, msg = fix_file(str(py_file), dry_run=dry_run) + if success: + print(f" ✓ {msg}") + success_count += 1 + else: + print(f" ✗ {msg}") + fail_count += 1 + + print(f"\n完成: 成功 {success_count} 个,失败 {fail_count} 个") + else: + # 修复单个文件 + file_path = sys.argv[1] + if not os.path.exists(file_path): + print(f"错误: 文件不存在: {file_path}") + sys.exit(1) + + print(f"处理文件: {file_path}") + success, msg = fix_file(file_path, dry_run=dry_run) + if success: + print(f"✓ {msg}") + else: + print(f"✗ {msg}") + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/gui_app.py b/gui_app.py index 4a87748..b5fbec9 100644 --- a/gui_app.py +++ b/gui_app.py @@ -118,7 +118,7 @@ def main(): min_value_var = tk.DoubleVar(value=float(cfg.get("min_prize_value_yuan", 0) or 0)) min_participants_var = tk.IntVar(value=int(cfg.get("min_participants", 0) or 0)) max_participants_var = tk.IntVar(value=int(cfg.get("max_participants", 0) or 0)) - skip_lt_seconds_var = tk.IntVar(value=int(cfg.get("skip_if_countdown_lt_seconds", 15) or 15)) + skip_gt_seconds_var = tk.IntVar(value=int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)) reset_after_swipes_enabled_var = tk.BooleanVar(value=bool(cfg.get("reset_after_swipes_enabled", False))) reset_after_swipes_var = tk.IntVar(value=int(cfg.get("reset_after_swipes", 10) or 10)) # 按需求:删除"自动养号/随机等待/轻微扰动/定时休息"等设置,仅保留"推荐页养号(爱心/收藏/评论)"配置。 @@ -209,8 +209,8 @@ def main(): infinite_loop_var.trace("w", update_wait_minutes_state) update_wait_minutes_state() # 初始化状态 - ttk.Label(r1, text="倒计时小于(秒)时不参与(高价值可预约):").pack(side=LEFT) - ttk.Spinbox(r1, from_=0, to=120, textvariable=skip_lt_seconds_var, width=6).pack(side=LEFT) + ttk.Label(r1, text="倒计时大于(秒)时不参与(高价值可预约):").pack(side=LEFT) + ttk.Spinbox(r1, from_=0, to=3600, textvariable=skip_gt_seconds_var, width=6).pack(side=LEFT) r2 = ttk.Frame(run_box) r2.pack(fill=X, padx=10, pady=(0, 10)) @@ -486,7 +486,7 @@ def main(): min_value_var.set(float(cfg.get("min_prize_value_yuan", 0) or 0)) min_participants_var.set(int(cfg.get("min_participants", 0) or 0)) max_participants_var.set(int(cfg.get("max_participants", 0) or 0)) - skip_lt_seconds_var.set(int(cfg.get("skip_if_countdown_lt_seconds", 15) or 15)) + skip_gt_seconds_var.set(int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)) reset_after_swipes_enabled_var.set(bool(cfg.get("reset_after_swipes_enabled", False))) reset_after_swipes_var.set(int(cfg.get("reset_after_swipes", 10) or 10)) auto_join_var.set(bool(cfg.get("auto_join_fansclub", False))) @@ -575,7 +575,7 @@ def main(): cfg2["min_prize_value_yuan"] = float(min_value_var.get() or 0) cfg2["min_participants"] = int(min_participants_var.get() or 0) cfg2["max_participants"] = int(max_participants_var.get() or 0) - cfg2["skip_if_countdown_lt_seconds"] = int(skip_lt_seconds_var.get() or 15) + cfg2["skip_if_countdown_gt_seconds"] = int(skip_gt_seconds_var.get() or 900) cfg2["reset_after_swipes_enabled"] = bool(reset_after_swipes_enabled_var.get()) cfg2["reset_after_swipes"] = int(reset_after_swipes_var.get() or 10) cfg2["auto_join_fansclub"] = bool(auto_join_var.get()) @@ -950,7 +950,7 @@ def main(): y_pianyi=int(y_var.get()), needswitch=bool(needswitch_var.get()), wait_minutes=wait_minutes_value, - skip_if_countdown_lt_seconds=int(skip_lt_seconds_var.get() or 15), + skip_if_countdown_gt_seconds=int(skip_gt_seconds_var.get() or 900), reset_after_swipes_enabled=bool(reset_after_swipes_enabled_var.get()), reset_after_swipes=int(reset_after_swipes_var.get() or 10), min_prize_value_yuan=float(min_value_var.get() or 0), @@ -979,7 +979,7 @@ def main(): on_line( f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} " f"needswitch={params.needswitch} wait={wait_display} " - f"skip_lt={params.skip_if_countdown_lt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} " + f"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} " f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] " f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} " f"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only" diff --git a/gui_core.py b/gui_core.py index c6e7ba2..08caa26 100644 --- a/gui_core.py +++ b/gui_core.py @@ -74,7 +74,7 @@ class RunParams: y_pianyi: int needswitch: bool wait_minutes: int - skip_if_countdown_lt_seconds: int + skip_if_countdown_gt_seconds: int reset_after_swipes_enabled: bool reset_after_swipes: int min_prize_value_yuan: float @@ -364,7 +364,7 @@ class Runner: cmd += ["--min-prize-value-yuan", str(params.min_prize_value_yuan)] # 这些参数是新增可调节项:倒计时太短跳过、参与人数范围 - cmd += ["--skip-if-countdown-lt-seconds", str(int(params.skip_if_countdown_lt_seconds or 15))] + cmd += ["--skip-if-countdown-gt-seconds", str(int(params.skip_if_countdown_gt_seconds or 900))] if params.reset_after_swipes_enabled: cmd.append("--reset-after-swipes-enabled") cmd += ["--reset-after-swipes", str(int(params.reset_after_swipes or 10))] diff --git a/path_config.py b/path_config.py index 80192a6..7aa1838 100644 --- a/path_config.py +++ b/path_config.py @@ -167,6 +167,15 @@ def ensure_dir(path: str) -> None: + + + + + + + + + diff --git a/run_cli.py b/run_cli.py index 708b2b9..420fd1f 100644 --- a/run_cli.py +++ b/run_cli.py @@ -90,7 +90,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: p.add_argument("--min-prize-value-yuan", type=float, default=None, help="最低奖品价值(元),低于则不参与") p.add_argument("--min-participants", type=int, default=None, help="最少参与人数(0/空表示不启用)") p.add_argument("--max-participants", type=int, default=None, help="最多参与人数(0/空表示不启用)") - p.add_argument("--skip-if-countdown-lt-seconds", type=int, default=None, help="倒计时小于该秒数则不参与,高价值福袋可预约(needswitch 生效)") + p.add_argument("--skip-if-countdown-gt-seconds", type=int, default=None, help="倒计时大于该秒数则不参与,高价值福袋可预约(needswitch 生效)") p.add_argument( "--reset-after-swipes", type=int, @@ -219,8 +219,8 @@ def main(argv: list[str]) -> int: analyser.min_participants = int(args.min_participants or 0) if args.max_participants is not None: analyser.max_participants = int(args.max_participants or 0) - if args.skip_if_countdown_lt_seconds is not None: - analyser.skip_if_countdown_lt_seconds = int(args.skip_if_countdown_lt_seconds or 15) + if args.skip_if_countdown_gt_seconds is not None: + analyser.skip_if_countdown_gt_seconds = int(args.skip_if_countdown_gt_seconds or 900) if args.reset_after_swipes is not None: analyser.reset_after_swipes = max(1, int(args.reset_after_swipes or 0)) analyser.reset_after_swipes_enabled = True diff --git a/state/reservations.json b/state/reservations.json index 61dc473..1f3eee7 100644 --- a/state/reservations.json +++ b/state/reservations.json @@ -1,19 +1,19 @@ { - "updated_ts": 1766155589.6960292, + "updated_ts": 1766208769.6966574, "reason": "record_reservation", - "room_pos": 0, - "current_room_title": "小明正能", - "current_room_title_raw": "小明正能。", + "room_pos": 4, + "current_room_title": "礻1390亘未四", + "current_room_title_raw": "礻1390亘》未四", "reservations": [ { - "prize_value_yuan": 899.0, - "content": "超大椰子螺5斤左右", - "future_ts": 1766155871.122754, - "future_str": "2025-12-19 22:51:11", - "pos_seen": 0, - "room_title": "小明正能", - "room_title_raw": "小明正能。", - "created_ts": 1766155589.6949484 + "prize_value_yuan": 5999.0, + "content": "(董先生专属1ihone172566B颜色随机发", + "future_ts": 1766209419.662086, + "future_str": "2025-12-20 13:43:39", + "pos_seen": 4, + "room_title": "礻1390亘未四", + "room_title_raw": "礻1390亘》未四", + "created_ts": 1766208769.695657 } ] } \ No newline at end of file diff --git a/tools/README_RGB工具.md b/tools/README_RGB工具.md index 0229e9e..e69de29 100644 --- a/tools/README_RGB工具.md +++ b/tools/README_RGB工具.md @@ -1,75 +0,0 @@ -# RGB颜色范围读取工具使用说明 - -## 功能 -读取图片的RGB颜色范围,用于调试福袋检测的颜色匹配逻辑。 - -## 使用方法 - -### 1. 读取整张图片的RGB范围 -```bash -python tools/read_image_rgb.py pic/screenshot.png -``` - -### 2. 读取特定坐标的RGB值 -```bash -python tools/read_image_rgb.py pic/screenshot.png 100 200 -``` -这会显示坐标 (100, 200) 的RGB值。 - -### 3. 读取特定区域的RGB范围 -```bash -python tools/read_image_rgb.py pic/screenshot.png 0 0 200 300 -``` -这会读取从 (0, 0) 开始,宽度200、高度300的区域的RGB范围。 - -## 实际应用示例 - -### 示例1:检测福袋图标颜色 -假设福袋图标在坐标 (165, 403) 附近: -```bash -# 读取单个像素 -python tools/read_image_rgb.py pic/screenshot.png 165 403 - -# 读取一个小区域(比如 10x10 像素) -python tools/read_image_rgb.py pic/screenshot.png 160 398 10 10 -``` - -### 示例2:检测福袋详情页参与按钮颜色 -假设参与按钮在坐标 (536, 883) 附近: -```bash -# 读取单个像素 -python tools/read_image_rgb.py pic/screenshot.png 536 883 - -# 读取按钮区域(比如 20x20 像素) -python tools/read_image_rgb.py pic/screenshot.png 526 873 20 20 -``` - -## 输出说明 - -### 单个像素输出 -``` -坐标 (165, 403) 的RGB值: - R: 198 - G: 185 - B: 242 - 十六进制: #C6B9F2 -``` - -### 区域/整图输出 -``` -RGB颜色范围: - R: 190 ~ 206 - G: 173 ~ 196 - B: 234 ~ 250 - -用于代码的颜色范围判断: - 190 <= r <= 206 and 173 <= g <= 196 and 234 <= b <= 250 -``` - -## 注意事项 - -1. 坐标基于图片的实际分辨率 -2. 如果图片是1080x2400,坐标就是实际像素坐标 -3. 如果图片是其他分辨率,需要按比例换算 -4. 区域检测会扫描区域内所有像素,计算最小和最大RGB值 - diff --git a/tools/analyze_fudai_color.py b/tools/analyze_fudai_color.py index 82da5ee..e69de29 100644 --- a/tools/analyze_fudai_color.py +++ b/tools/analyze_fudai_color.py @@ -1,67 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -"""分析福袋图标的RGB颜色范围,给出代码建议""" - -from PIL import Image -from collections import Counter - -img = Image.open('assets/fudai.png').convert('RGB') -width, height = img.size - -# 收集非背景像素 -pixels = [] -for y in range(height): - for x in range(width): - r, g, b = img.getpixel((x, y)) - # 排除黑色背景 - if not (r < 30 and g < 30 and b < 30): - pixels.append((r, g, b)) - -if not pixels: - print("No valid pixels") - exit(1) - -# 主要颜色 -colors = Counter(pixels) -top_colors = colors.most_common(10) - -print("Top 10 colors:") -for i, ((r, g, b), count) in enumerate(top_colors, 1): - pct = (count / len(pixels)) * 100 - print(f"{i}. RGB({r:3d}, {g:3d}, {b:3d}) - {pct:5.2f}% - #{r:02X}{g:02X}{b:02X}") - -# RGB范围 -r_vals = [p[0] for p in pixels] -g_vals = [p[1] for p in pixels] -b_vals = [p[2] for p in pixels] - -print(f"\nFull RGB range:") -print(f" R: {min(r_vals)} ~ {max(r_vals)}") -print(f" G: {min(g_vals)} ~ {max(g_vals)}") -print(f" B: {min(b_vals)} ~ {max(b_vals)}") - -# 基于主要颜色的建议范围 -if top_colors: - main_r, main_g, main_b = top_colors[0][0] - print(f"\nMain color: RGB({main_r}, {main_g}, {main_b})") - print(f"\nSuggested range (main color +/- tolerance):") - - # 容差建议 - tolerance_r = 30 - tolerance_g = 30 - tolerance_b = 30 - - r_min = max(200, main_r - tolerance_r) - r_max = min(255, main_r + 10) - g_min = max(150, main_g - tolerance_g) - g_max = min(255, main_g + tolerance_g) - b_min = max(180, main_b - tolerance_b) - b_max = min(255, main_b + tolerance_b) - - print(f" {r_min} <= r <= {r_max}") - print(f" {g_min} <= g <= {g_max}") - print(f" {b_min} <= b <= {b_max}") - - print(f"\nCode format:") - print(f" {r_min} <= int(px[0]) <= {r_max} and {g_min} <= int(px[1]) <= {g_max} and {b_min} <= int(px[2]) <= {b_max}") - diff --git a/tools/compare_fudai_coupon.py b/tools/compare_fudai_coupon.py index a93e9e5..e69de29 100644 --- a/tools/compare_fudai_coupon.py +++ b/tools/compare_fudai_coupon.py @@ -1,83 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -"""对比福袋和优惠券的RGB颜色,找出区分特征""" - -from PIL import Image -from collections import Counter - -print("=" * 60) -print("福袋图标颜色分析") -print("=" * 60) -fudai = Image.open('assets/fudai.png').convert('RGB') -fudai_pixels = [(r,g,b) for y in range(fudai.height) for x in range(fudai.width) - for r,g,b in [fudai.getpixel((x,y))] if not (r<30 and g<30 and b<30)] -fudai_colors = Counter(fudai_pixels) -fudai_top = fudai_colors.most_common(5) -print("Top 5 colors:") -for (r,g,b), count in fudai_top: - print(f" RGB({r:3d}, {g:3d}, {b:3d}) - {count/len(fudai_pixels)*100:5.2f}%") - -fudai_r = [p[0] for p in fudai_pixels] -fudai_g = [p[1] for p in fudai_pixels] -fudai_b = [p[2] for p in fudai_pixels] -print(f"\nRGB range: R[{min(fudai_r)}-{max(fudai_r)}] G[{min(fudai_g)}-{max(fudai_g)}] B[{min(fudai_b)}-{max(fudai_b)}]") - -print("\n" + "=" * 60) -print("优惠券颜色分析") -print("=" * 60) -coupon = Image.open('assets/coupon.png').convert('RGB') -coupon_pixels = [(r,g,b) for y in range(coupon.height) for x in range(coupon.width) - for r,g,b in [coupon.getpixel((x,y))] if not (r<30 and g<30 and b<30)] -coupon_colors = Counter(coupon_pixels) -coupon_top = coupon_colors.most_common(5) -print("Top 5 colors:") -for (r,g,b), count in coupon_top: - print(f" RGB({r:3d}, {g:3d}, {b:3d}) - {count/len(coupon_pixels)*100:5.2f}%") - -coupon_r = [p[0] for p in coupon_pixels] -coupon_g = [p[1] for p in coupon_pixels] -coupon_b = [p[2] for p in coupon_pixels] -print(f"\nRGB range: R[{min(coupon_r)}-{max(coupon_r)}] G[{min(coupon_g)}-{max(coupon_g)}] B[{min(coupon_b)}-{max(coupon_b)}]") - -print("\n" + "=" * 60) -print("区分特征分析") -print("=" * 60) - -# 优惠券的主要红色特征 -coupon_red = [p for p in coupon_pixels if p[0] > 250 and p[1] < 100 and p[2] < 120] -if coupon_red: - red_r = [p[0] for p in coupon_red] - red_g = [p[1] for p in coupon_red] - red_b = [p[2] for p in coupon_red] - print(f"\n优惠券红色区域:") - print(f" R: {min(red_r)}-{max(red_r)}") - print(f" G: {min(red_g)}-{max(red_g)}") - print(f" B: {min(red_b)}-{max(red_b)}") - print(f" 特征: 高R值(>{min(red_r)}),低G值(<{max(red_g)}),低B值(<{max(red_b)})") - -# 福袋的主要颜色特征 -fudai_pink = [p for p in fudai_pixels if p[0] > 225 and p[1] > 180 and p[2] > 190] -if fudai_pink: - pink_r = [p[0] for p in fudai_pink] - pink_g = [p[1] for p in fudai_pink] - pink_b = [p[2] for p in fudai_pink] - print(f"\n福袋粉红色区域:") - print(f" R: {min(pink_r)}-{max(pink_r)}") - print(f" G: {min(pink_g)}-{max(pink_g)}") - print(f" B: {min(pink_b)}-{max(pink_b)}") - print(f" 特征: 高R值(>{min(pink_r)}),高G值(>{min(pink_g)}),高B值(>{min(pink_b)})") - -print("\n" + "=" * 60) -print("建议的排除条件") -print("=" * 60) -print("\n优惠券红色特征(需要排除):") -print(" - R > 250 且 G < 100 且 B < 120 (鲜艳红色)") -print(" - R > 250 且 G < 150 且 B < 150 (较宽松的红色)") -print("\n福袋粉红色特征(需要保留):") -print(" - R > 225 且 G > 180 且 B > 190 (粉红色)") -print("\n建议的福袋检测条件:") -print(" R > 225 and R <= 255") -print(" G > 180 and G <= 255") -print(" B > 190 and B <= 255") -print(" AND NOT (R > 250 and G < 100 and B < 120) # 排除优惠券红色") - diff --git a/tools/read_fudai_rgb.py b/tools/read_fudai_rgb.py index 4758700..e69de29 100644 --- a/tools/read_fudai_rgb.py +++ b/tools/read_fudai_rgb.py @@ -1,140 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -福袋图标RGB颜色范围检测工具 -自动排除黑色背景,只检测福袋图标本身的RGB范围 -""" - -import sys -from PIL import Image -from collections import Counter - - -def get_fudai_rgb_range(image_path: str, exclude_bg: bool = True, bg_threshold: int = 30): - """检测福袋图标的RGB颜色范围(排除背景) - - 参数: - image_path: 图片路径 - exclude_bg: 是否排除背景色(默认True,排除RGB值都小于30的像素) - bg_threshold: 背景色阈值(RGB值都小于此值认为是背景) - """ - try: - img = Image.open(image_path) - img_rgb = img.convert("RGB") - width, height = img_rgb.size - - print(f"图片尺寸: {width} x {height}") - print(f"图片模式: {img.mode}") - print("-" * 60) - - # 收集所有非背景像素的RGB值 - pixels = [] - for y in range(height): - for x in range(width): - try: - r, g, b = img_rgb.getpixel((x, y)) - # 如果启用背景排除,跳过黑色/深色背景 - if exclude_bg and r < bg_threshold and g < bg_threshold and b < bg_threshold: - continue - pixels.append((r, g, b)) - except Exception: - continue - - if not pixels: - print("错误: 没有检测到有效像素(可能整张图都是背景色)") - return None - - # 计算RGB范围 - r_values = [p[0] for p in pixels] - g_values = [p[1] for p in pixels] - b_values = [p[2] for p in pixels] - - r_min, r_max = min(r_values), max(r_values) - g_min, g_max = min(g_values), max(g_values) - b_min, b_max = min(b_values), max(b_values) - - # 计算RGB平均值(用于参考) - r_avg = sum(r_values) // len(r_values) - g_avg = sum(g_values) // len(g_values) - b_avg = sum(b_values) // len(b_values) - - print(f"\n福袋图标RGB颜色范围(已排除背景):") - print(f" R: {r_min} ~ {r_max} (平均值: {r_avg})") - print(f" G: {g_min} ~ {g_max} (平均值: {g_avg})") - print(f" B: {b_min} ~ {b_max} (平均值: {b_avg})") - print(f"\n有效像素数: {len(pixels)} / {width * height}") - - # 分析主要颜色(找出最常见的RGB组合) - print(f"\n主要颜色分析:") - color_counter = Counter(pixels) - top_colors = color_counter.most_common(5) - for i, (color, count) in enumerate(top_colors, 1): - r, g, b = color - percentage = (count / len(pixels)) * 100 - print(f" {i}. RGB({r}, {g}, {b}) - 占比 {percentage:.1f}% - #{r:02X}{g:02X}{b:02X}") - - # 生成代码建议 - print(f"\n" + "=" * 60) - print("用于代码的颜色范围判断(建议):") - print("=" * 60) - - # 方法1:使用完整范围(容错性最好,但可能误检) - print(f"\n方法1:完整范围(容错性最好)") - print(f" {r_min} <= r <= {r_max} and {g_min} <= g <= {g_max} and {b_min} <= b <= {b_max}") - - # 方法2:使用平均值±范围(更精确,但需要根据实际情况调整) - r_range = max(10, (r_max - r_min) // 2) - g_range = max(10, (g_max - g_min) // 2) - b_range = max(10, (b_max - b_min) // 2) - - print(f"\n方法2:平均值±范围(更精确)") - print(f" {r_avg - r_range} <= r <= {r_avg + r_range} and " - f"{g_avg - g_range} <= g <= {g_avg + g_range} and " - f"{b_avg - b_range} <= b <= {b_avg + b_range}") - - # 方法3:基于主要颜色的范围(最精确,但可能漏检) - if top_colors: - main_r, main_g, main_b = top_colors[0][0] - tolerance = 20 # 容差 - print(f"\n方法3:主要颜色±容差(最精确,基于主要颜色RGB({main_r}, {main_g}, {main_b}))") - print(f" {main_r - tolerance} <= r <= {main_r + tolerance} and " - f"{main_g - tolerance} <= g <= {main_g + tolerance} and " - f"{main_b - tolerance} <= b <= {main_b + tolerance}") - - # 当前代码中的范围(用于对比) - print(f"\n当前代码中的范围(用于对比):") - print(f" 190 <= r <= 206 and 173 <= g <= 196 and 234 <= b <= 250") - - return { - "r_range": (r_min, r_max), - "g_range": (g_min, g_max), - "b_range": (b_min, b_max), - "r_avg": r_avg, - "g_avg": g_avg, - "b_avg": b_avg, - "pixel_count": len(pixels) - } - - except FileNotFoundError: - print(f"错误: 找不到图片文件: {image_path}") - return None - except Exception as e: - print(f"错误: {type(e).__name__}: {e}") - import traceback - traceback.print_exc() - return None - - -def main(): - if len(sys.argv) < 2: - print("用法: python tools/read_fudai_rgb.py <图片路径>") - print("示例: python tools/read_fudai_rgb.py pic/fudai_icon.png") - sys.exit(1) - - image_path = sys.argv[1] - get_fudai_rgb_range(image_path) - - -if __name__ == "__main__": - main() - diff --git a/tools/read_image_rgb.py b/tools/read_image_rgb.py index 3cf2a69..e69de29 100644 --- a/tools/read_image_rgb.py +++ b/tools/read_image_rgb.py @@ -1,175 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -图片RGB颜色范围读取工具 - -用法: - python tools/read_image_rgb.py <图片路径> [x] [y] [width] [height] - -示例: - # 读取整张图片的RGB范围 - python tools/read_image_rgb.py pic/screenshot.png - - # 读取特定坐标的RGB值 - python tools/read_image_rgb.py pic/screenshot.png 100 200 - - # 读取特定区域的RGB范围 - python tools/read_image_rgb.py pic/screenshot.png 0 0 200 300 -""" - -import sys -import os -from PIL import Image - - -def get_rgb_range(image_path: str, x: int = None, y: int = None, width: int = None, height: int = None): - """读取图片的RGB颜色范围 - - 参数: - image_path: 图片路径 - x: 起始X坐标(可选,用于区域检测) - y: 起始Y坐标(可选,用于区域检测) - width: 区域宽度(可选,用于区域检测) - height: 区域高度(可选,用于区域检测) - - 返回: - dict: 包含RGB范围信息的字典 - """ - try: - img = Image.open(image_path) - img_rgb = img.convert("RGB") - img_width, img_height = img_rgb.size - - print(f"图片尺寸: {img_width} x {img_height}") - print(f"图片模式: {img.mode}") - print("-" * 60) - - # 如果指定了坐标,读取单个像素 - if x is not None and y is not None: - if not (0 <= x < img_width and 0 <= y < img_height): - print(f"错误: 坐标 ({x}, {y}) 超出图片范围") - return None - - r, g, b = img_rgb.getpixel((x, y)) - print(f"坐标 ({x}, {y}) 的RGB值:") - print(f" R: {r}") - print(f" G: {g}") - print(f" B: {b}") - print(f" 十六进制: #{r:02X}{g:02X}{b:02X}") - return {"r": r, "g": g, "b": b, "x": x, "y": y} - - # 如果指定了区域,读取区域范围 - if x is not None and y is not None and width is not None and height is not None: - x_end = min(x + width, img_width) - y_end = min(y + height, img_height) - - print(f"区域: ({x}, {y}) 到 ({x_end-1}, {y_end-1})") - print(f"区域大小: {x_end - x} x {y_end - y}") - - pixels = [] - for py in range(y, y_end): - for px in range(x, x_end): - try: - r, g, b = img_rgb.getpixel((px, py)) - pixels.append((r, g, b)) - except Exception: - continue - - if not pixels: - print("错误: 区域中没有有效像素") - return None - - r_values = [p[0] for p in pixels] - g_values = [p[1] for p in pixels] - b_values = [p[2] for p in pixels] - - r_min, r_max = min(r_values), max(r_values) - g_min, g_max = min(g_values), max(g_values) - b_min, b_max = min(b_values), max(b_values) - - print(f"\nRGB颜色范围:") - print(f" R: {r_min} ~ {r_max}") - print(f" G: {g_min} ~ {g_max}") - print(f" B: {b_min} ~ {b_max}") - print(f"\n用于代码的颜色范围判断:") - print(f" {r_min} <= r <= {r_max} and {g_min} <= g <= {g_max} and {b_min} <= b <= {b_max}") - print(f"\n像素总数: {len(pixels)}") - - return { - "r_range": (r_min, r_max), - "g_range": (g_min, g_max), - "b_range": (b_min, b_max), - "pixel_count": len(pixels) - } - - # 读取整张图片的RGB范围 - print("扫描整张图片...") - pixels = [] - for py in range(img_height): - for px in range(img_width): - try: - r, g, b = img_rgb.getpixel((px, py)) - pixels.append((r, g, b)) - except Exception: - continue - - if not pixels: - print("错误: 图片中没有有效像素") - return None - - r_values = [p[0] for p in pixels] - g_values = [p[1] for p in pixels] - b_values = [p[2] for p in pixels] - - r_min, r_max = min(r_values), max(r_values) - g_min, g_max = min(g_values), max(g_values) - b_min, b_max = min(b_values), max(b_values) - - print(f"\n整张图片的RGB颜色范围:") - print(f" R: {r_min} ~ {r_max}") - print(f" G: {g_min} ~ {g_max}") - print(f" B: {b_min} ~ {b_max}") - print(f"\n像素总数: {len(pixels)}") - - return { - "r_range": (r_min, r_max), - "g_range": (g_min, g_max), - "b_range": (b_min, b_max), - "pixel_count": len(pixels) - } - - except FileNotFoundError: - print(f"错误: 找不到图片文件: {image_path}") - return None - except Exception as e: - print(f"错误: {type(e).__name__}: {e}") - return None - - -def main(): - if len(sys.argv) < 2: - print(__doc__) - sys.exit(1) - - image_path = sys.argv[1] - - # 解析参数 - x = int(sys.argv[2]) if len(sys.argv) > 2 else None - y = int(sys.argv[3]) if len(sys.argv) > 3 else None - width = int(sys.argv[4]) if len(sys.argv) > 4 else None - height = int(sys.argv[5]) if len(sys.argv) > 5 else None - - # 如果只提供了x和y,就是读取单个像素 - if x is not None and y is not None and width is None and height is None: - get_rgb_range(image_path, x=x, y=y) - # 如果提供了x, y, width, height,就是读取区域 - elif x is not None and y is not None and width is not None and height is not None: - get_rgb_range(image_path, x=x, y=y, width=width, height=height) - # 否则读取整张图片 - else: - get_rgb_range(image_path) - - -if __name__ == "__main__": - main() - diff --git a/功能差异对比.md b/功能差异对比.md index feedaba..e69de29 100644 --- a/功能差异对比.md +++ b/功能差异对比.md @@ -1,249 +0,0 @@ -# 模块化代码 vs 原始代码 (fudai1.py) 功能差异对比 - -## 一、已移除/简化的功能 - -### 1. ❌ **高价值直播间回访功能**(已移除) - -#### 原始代码 -- **功能**:自动回访曾经记录过高价值福袋的直播间 -- **优先级**:预约参与(最高) > 回访(中) > 普通找福袋(低) -- **配置**: - - `high_value_room_revisit_enabled = True`(默认启用) - - `high_value_room_revisit_interval_seconds = 300`(默认 5 分钟) - - `high_value_room_revisit_watch_window_seconds = 900`(默认 15 分钟观察窗) - - `high_value_room_revisit_skip_if_reservation_within_seconds = 120` -- **实现**:在主循环中检查回访时间窗口,自动回退到高价值直播间查看是否有新福袋 - -#### 模块化代码 -- **状态**:仅保留配置项,功能未实现 -- **配置**: - - `high_value_room_revisit_enabled = False`(默认禁用) - - `high_value_room_revisit_only_current_run = False` -- **影响**:无法自动回访高价值直播间,只能通过预约队列手动回退 - ---- - -### 2. ⚠️ **回退校验功能**(已简化) - -#### 原始代码 -- **功能**:回退到预约直播间后,进行详细校验确保回退正确 -- **校验内容**: - 1. 直播间名称匹配(清洗后和原始文本) - 2. 福袋详情匹配(内容、价值、开奖时间) - 3. 任务类型检查(排除"观看XX分钟"类任务) -- **配置**:`reservation_back_verify_enabled = True`(默认启用) -- **实现**:`_validate_back_to_reservation()` 和 `_match_reservation()` 函数 -- **行为**:校验失败会丢弃当前预约项,继续处理其他预约 - -#### 模块化代码 -- **状态**:简化版实现 -- **功能**:仅保留基本的回退逻辑,没有详细的校验机制 -- **实现**:`_seek_reservation_room()` 函数简化了校验逻辑 -- **影响**:回退准确性可能降低,但速度更快 - ---- - -### 3. ❌ **等待次数计数器**(已移除) - -#### 原始代码 -- **功能**:`wait_times` 计数器,累计 4 次没有福袋则切换直播间 -- **逻辑**:在直播间等待时,每次未找到福袋 `wait_times++`,达到阈值后切换 - -#### 模块化代码 -- **状态**:已移除 -- **影响**:不再基于等待次数自动切换,改为基于时间或其他条件 - ---- - -### 4. ❌ **滑动次数重置功能**(已移除) - -#### 原始代码 -- **功能**:`reset_after_swipes` - 达到一定滑动次数后,回到第一个直播间 -- **配置**: - - `reset_after_swipes_enabled = False`(默认关闭,但可配置) - - `reset_after_swipes = 10`(阈值) -- **逻辑**:`_maybe_reset_after_swipes()` 函数检查滑动次数,达到阈值后回退 - -#### 模块化代码 -- **状态**:已移除 -- **影响**:无法自动重置到列表第一个直播间 - ---- - -### 5. ❌ **无法打开福袋计数器**(已移除) - -#### 原始代码 -- **功能**:`fudai_not_open_times` 计数器,记录无法打开福袋的次数 -- **逻辑**:用于统计和可能的错误处理 - -#### 模块化代码 -- **状态**:已移除 -- **影响**:不再统计无法打开福袋的次数 - ---- - -### 6. ❌ **意外返回桌面自救功能**(已移除) - -#### 原始代码 -- **功能**:检测是否意外返回桌面(不在抖音前台),自动恢复 -- **实现**: - 1. 检测前台包名 - 2. 如果不在抖音,点击桌面图标 - 3. 点击直播按钮 - 4. 点击进入直播间 -- **配置**:使用 `desktop_icon_x/y`、`yanghao_fallback_live_x/y` 等坐标 - -#### 模块化代码 -- **状态**:已移除 -- **影响**:如果意外返回桌面,需要手动恢复 - ---- - -### 7. ❌ **充电停止弹窗检测**(已移除) - -#### 原始代码 -- **功能**:`check_stop_charging()` - 检测 vivo 设备长时间连接弹出的停止充电弹窗 -- **实现**:OCR 识别充电提醒文字 - -#### 模块化代码 -- **状态**:已移除 -- **影响**:无法自动处理充电停止弹窗 - ---- - -### 8. ❌ **电池电量检测**(已移除) - -#### 原始代码 -- **功能**:`deal_battery_level()` - 检测电池电量,低电量时挂机 30 分钟 -- **实现**:检测电池电量,低电量时返回直播列表并等待 - -#### 模块化代码 -- **状态**:已移除 -- **影响**:不再检测电池电量 - ---- - -## 二、保留但简化的功能 - -### 1. ⚠️ **预约队列管理**(简化) - -#### 原始代码 -- **功能**:完整的高价值福袋预约队列管理 -- **特性**: - - 动态提前量计算(考虑回退步数耗时) - - 预约项匹配校验 - - 预约完成后动作(stay/continue) - - 预约队列状态持久化 - -#### 模块化代码 -- **状态**:保留核心功能,简化实现 -- **保留**: - - 预约队列基本管理 - - 预约回退逻辑 - - 状态文件写入 -- **简化**: - - 回退校验逻辑简化 - - 动态提前量计算简化 - ---- - -### 2. ⚠️ **高价值直播间记录**(简化) - -#### 原始代码 -- **功能**:`_touch_high_value_room()` - 记录高价值直播间信息 -- **特性**: - - 跨运行持久化(写入 `high_value_rooms.json`) - - 记录最大价值、最后价值、首次/最后记录时间 - - 记录次数统计 - - 支持别名和合并逻辑 - -#### 模块化代码 -- **状态**:保留配置,但功能简化 -- **保留**:配置项存在 -- **简化**:实际记录逻辑可能不完整 - ---- - -## 三、新增或改进的功能 - -### 1. ✅ **无限循环模式** - -#### 模块化代码 -- **功能**:新增 `infinite_loop_enabled` 配置项 -- **行为**:启用后,程序不会因为 `wait_minutes` 而自动退出 -- **用途**:适合长期挂机场景 - -#### 原始代码 -- **状态**:无此功能,必须设置 `wait_minutes` - ---- - -### 2. ✅ **模块化设计** - -#### 模块化代码 -- **优势**: - - 功能模块独立,易于维护 - - 可以单独测试每个模块 - - 可以按需启用/禁用功能模块 - -#### 原始代码 -- **状态**:所有功能耦合在一个文件中 - ---- - -## 四、功能对比总结表 - -| 功能 | 原始代码 | 模块化代码 | 状态 | -|------|---------|-----------|------| -| **基础抢福袋** | ✅ | ✅ | 保留 | -| **高价值福袋预约** | ✅ | ✅ | 保留(简化) | -| **预约回退** | ✅ | ✅ | 保留(简化) | -| **回退校验** | ✅ 详细校验 | ⚠️ 简化校验 | 简化 | -| **高价值直播间回访** | ✅ | ❌ | 已移除 | -| **等待次数计数器** | ✅ | ❌ | 已移除 | -| **滑动次数重置** | ✅ | ❌ | 已移除 | -| **无法打开福袋计数** | ✅ | ❌ | 已移除 | -| **意外返回桌面自救** | ✅ | ❌ | 已移除 | -| **充电停止弹窗检测** | ✅ | ❌ | 已移除 | -| **电池电量检测** | ✅ | ❌ | 已移除 | -| **高价值直播间记录** | ✅ 完整 | ⚠️ 简化 | 简化 | -| **无限循环模式** | ❌ | ✅ | 新增 | - -## 五、使用建议 - -### 如果依赖以下功能,建议使用原始代码: -1. ✅ **高价值直播间自动回访** - 需要自动回访功能 -2. ✅ **详细的回退校验** - 需要确保回退准确性 -3. ✅ **意外返回桌面自救** - 设备可能意外返回桌面 -4. ✅ **电池电量管理** - 需要自动处理低电量 - -### 如果只需要基础功能,模块化代码更适合: -1. ✅ **代码更清晰** - 易于理解和修改 -2. ✅ **维护更方便** - 模块化设计便于维护 -3. ✅ **无限循环模式** - 适合长期挂机 -4. ✅ **功能精简** - 只保留核心功能,减少复杂度 - -## 六、迁移注意事项 - -如果从原始代码迁移到模块化代码: - -1. **高价值直播间回访**:需要手动通过预约队列管理 -2. **回退校验**:校验逻辑简化,可能影响准确性 -3. **计数器功能**:不再有等待次数、滑动次数等自动切换机制 -4. **自救功能**:需要手动处理意外返回桌面的情况 -5. **电池管理**:需要手动监控电池电量 - -## 七、总结 - -**模块化代码的设计理念**: -- ✅ 保留核心功能(抢福袋、预约队列) -- ✅ 简化复杂功能(回退校验、回访逻辑) -- ✅ 移除边缘功能(自救、电池检测) -- ✅ 提高代码可维护性 - -**适用场景**: -- ✅ 只需要基础抢福袋功能 -- ✅ 需要代码清晰、易于维护 -- ✅ 不需要自动回访等高级功能 -- ✅ 需要长期稳定运行(无限循环模式) - diff --git a/原始代码/fudai1.py b/原始代码/fudai1.py index 47bde78..5f28270 100644 --- a/原始代码/fudai1.py +++ b/原始代码/fudai1.py @@ -1,5937 +1 @@ -import os -import sys -import time -from PIL import Image -from datetime import datetime -from Underlying_Operations import underlying_operations -import json -import re -import shutil -import random -import hashlib -import difflib - -""" - V3.3.1 版本 - """ - - -def normalize_countdown_text(text: str) -> str: - if not text: - return '' - t = re.sub(r"\s+", "", str(text)) - t = t.replace(':', ':') - # 常见 OCR 混淆纠正(只做轻量替换,避免影响其它文字) - t = t.translate(str.maketrans({ - 'O': '0', 'o': '0', 'Q': '0', 'D': '0', - 'I': '1', 'l': '1', '|': '1', '!': '1', - 'S': '5', 's': '5', - 'B': '8', - 'G': '6', - 'Z': '2', - })) - - # 中文:x分y秒 / y秒 - m = re.search(r"(\d{1,2})分(\d{1,2})秒", t) - if m: - mm = int(m.group(1)) - ss = int(m.group(2)) - if ss >= 60: - mm += ss // 60 - ss = ss % 60 - return f"{mm:02d}:{ss:02d}" - m = re.search(r"(\d{1,3})秒", t) - if m: - ss = int(m.group(1)) - mm = ss // 60 - ss = ss % 60 - return f"{mm:02d}:{ss:02d}" - # 标准样式:11:37后开奖 / 11:37后开奖 - m = re.search(r"(\d{1,2})[::](\d{2}).*后开奖", t) - if m: - mm = int(m.group(1)) - ss = int(m.group(2)) - # 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释 - if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: - mm, ss = ss, mm - return f"{mm:02d}:{ss:02d}后开奖" - # 识别错序:54后开奖04 - m = re.search(r"(\d{1,2})后开奖(\d{2})", t) - if m: - mm = int(m.group(1)) - ss = int(m.group(2)) - if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: - mm, ss = ss, mm - return f"{mm:02d}:{ss:02d}后开奖" - # 纯数字 1137 / 5404 - digits = ''.join(ch for ch in t if ch.isdigit()) - if len(digits) == 4: - a = int(digits[:2]) - b = int(digits[2:]) - - # 生成两种解释:mm:ss 以及交换后的 mm:ss - mm1, ss1 = a, b - mm2, ss2 = b, a - - total1 = mm1 * 60 + ss1 - total2 = mm2 * 60 + ss2 - - # 默认相信“从左到右”的顺序:前两位=分,后两位=秒。 - # 只有在明显异常(>15分钟)或秒数不合法时才交换。 - if ss1 >= 60 and ss2 < 60: - mm, ss = mm2, ss2 - elif ss2 >= 60 and ss1 < 60: - mm, ss = mm1, ss1 - elif total1 > 900 and total2 <= 900: - mm, ss = mm2, ss2 - elif total2 > 900 and total1 <= 900: - mm, ss = mm1, ss1 - else: - mm, ss = mm1, ss1 - - return f"{mm:02d}:{ss:02d}" - # 3 位数字:934 => 09:34 - if len(digits) == 3: - mm = int(digits[0]) - ss = int(digits[1:]) - if ss >= 60: - # 尝试 15:09(OCR 丢 0) - mm2 = int(digits[:2]) - ss2 = int(digits[2]) - if ss2 < 60: - return f"{mm2:02d}:{ss2:02d}" - mm += ss // 60 - ss = ss % 60 - return f"{mm:02d}:{ss:02d}" - # 2 位数字:31 => 00:31(更符合临近开奖) - if len(digits) == 2: - return f"00:{int(digits):02d}" - return t - - -def extract_prize_value_yuan(text: str) -> float: - if not text: - return 0.0 - t = re.sub(r"\s+", "", str(text)) - # 先去掉倒计时类数字,避免把 00:31 解析成 31 元 - t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t) - - # 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元 - currency_matches = re.findall(r"[¥¥](\d+(?:\.\d+)?)", t) - yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t) - tagged = currency_matches + yuan_matches - if tagged: - vals = [] - for n in tagged: - try: - vals.append(float(n)) - except ValueError: - pass - return max(vals) if vals else 0.0 - - # 去掉常见干扰:份数/参与人数 - t = re.sub(r"共\d+份", "", t) - t = re.sub(r"\d+人已参与", "", t) - - # 退化:抓小数 - decimals = re.findall(r"\d+\.\d+", t) - if decimals: - vals = [] - for n in decimals: - try: - vals.append(float(n)) - except ValueError: - pass - return max(vals) if vals else 0.0 - - # 再退化:抓整数 - ints = re.findall(r"\d+", t) - if ints: - vals = [] - for n in ints: - try: - v = int(n) - except ValueError: - continue - if 1 <= v <= 99999: - vals.append(float(v)) - return max(vals) if vals else 0.0 - - return 0.0 - -class Tee(object): - """重写print的函数""" - - def __init__(self, *files): - self.files = files - - def write(self, obj): - for f in self.files: - f.write(obj) - f.flush() - - def flush(self): - for f in self.files: - f.flush() - - -class fudai_analyse: - """福袋抽奖相关操作类""" - - def __init__(self): - self.device_id = 'XXXXXXXXX' - self.y_pianyi = 0 # 应用于不同型号手机,图标相对屏幕的高度位置有偏差 - self.resolution_ratio_x = 1080 - self.resolution_ratio_y = 2400 - # OCR结果缓存:避免短时间内重复识别相同区域 - self._ocr_cache: dict[str, tuple[float, str]] = {} # key: (picname, change_color), value: (timestamp, result) - self._ocr_cache_ttl: float = 2.0 # 缓存有效期(秒) - # 检测结果缓存 - self._detection_cache: dict[str, tuple[float, object]] = {} # key: method_name, value: (timestamp, result) - self._detection_cache_ttl: float = 1.0 # 检测缓存有效期(秒) - # 预约队列状态文件(用于 Web GUI 展示;子进程写入,Web GUI 进程读取) - self._reservations_state_path = os.path.join(os.path.dirname(__file__), "state", "reservations.json") - # 让终端输出更“整行、实时”(避免看起来空白/零散) - try: - sys.stdout.reconfigure(encoding='utf-8', line_buffering=True) - except Exception: - pass - try: - sys.stderr.reconfigure(encoding='utf-8', line_buffering=True) - except Exception: - pass - # 可通过环境变量关闭 Tee 重定向(例如 Web GUI 统一收集日志时) - if not str(os.environ.get("NO_TEE_STDOUT", "")).strip(): - # 统一日志文件(默认 logs/unified.log),便于长期追踪与 grep - base_dir = os.path.dirname(__file__) - cfg = {} - try: - cfg_path = os.path.join(base_dir, "config.json") - if os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as f: - cfg = json.load(f) if f.readable() else {} - except Exception: - cfg = {} - - enabled = True - try: - enabled = bool(cfg.get("log_unified_enabled", True)) - except Exception: - enabled = True - - if enabled: - rel = str(cfg.get("log_unified_path") or "logs/unified.log") - log_path = rel if os.path.isabs(rel) else os.path.join(base_dir, rel) - try: - os.makedirs(os.path.dirname(log_path), exist_ok=True) - except Exception: - pass - # 使用 utf-8-sig:文件首次创建时写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码 - log_file = open(log_path, 'a', encoding='utf-8-sig', errors='ignore') - else: - # 兼容:若禁用统一日志,则按旧逻辑写一个时间戳文件 - timepic = datetime.now().strftime('%Y-%m-%d-%H-%M') - log_file = open(timepic + '.log', 'a', encoding='utf-8-sig', errors='ignore') - - sys.stdout = Tee(sys.stdout, log_file) - sys.stderr = Tee(sys.stderr, log_file) - - # 结构化日志:本次运行唯一 id + 递增序号(便于 Web GUI 里按 rid/seq 定位) - try: - self._run_id = datetime.now().strftime('%Y%m%d%H%M%S') - except Exception: - self._run_id = str(int(time.time())) - self._log_seq = 0 - self.last_find_fudai_time = 0.0 - self.last_refresh_zhibo_list_time = 0.0 - # 进入直播间计时:用于统计“进入直播间后找到福袋图标耗时” - self._enter_live_ts = 0.0 - self._enter_live_reason = "" - self._enter_live_fudai_logged = False - # 无福袋“看门狗”:超时后回到列表重进直播。用户要求先整体关闭,后续再调整。 - self.no_fudai_watchdog_enabled = False - self.operation = underlying_operations() - self.config_path = "config.json" - self.contains_not_want = [] - self.contains_want = [] - self.min_prize_value_yuan = 0.0 # 小于该价值(元)则不参与,0 表示不启用 - self.min_participants = 0 # 参与人数小于该值则不参与,0 表示不启用 - self.max_participants = 0 # 参与人数大于该值则不参与,0 表示不启用 - self.skip_if_countdown_lt_seconds = 15 # 倒计时小于该秒数则不参与(仅 needswitch=True 时生效) - - # 切换直播间计数:当上划切换达到阈值后,在当前直播间页面下滑回退到第一个直播间 - self.reset_after_swipes_enabled = False # 由 Web/CLI 显式开关 - self.reset_after_swipes = 10 # 达到阈值次数后回退,需启用开关后生效 - - # 高价值福袋:预约参与(避免在倒计时很长时一直卡在直播间等待) - self.high_value_fudai_enabled = False - self.high_value_fudai_threshold_yuan = 1000.0 - self.high_value_fudai_join_ahead_seconds = 120 # 开奖前 N 秒回到该直播间并参与 - self.high_value_fudai_max_swipe_back = 60 # 为防止回滑过远导致异常,限制最多回退次数 - self.high_value_fudai_max_reservations = 5 # 最多记录多少个高价值福袋预约 - # 完成某个预约福袋后动作:stay=停留当前直播间;continue=继续执行抢福袋 - self.high_value_fudai_after_action = "continue" - self.high_value_fudai_after_stay_seconds = 120 - - # 高价值直播间“回访”:曾经记录过高价值福袋的直播间,每隔一段时间回去看一眼是否出现新福袋。 - # 优先级:预约参与(最高) > 回访(中) > 普通找福袋(低) - self.high_value_room_revisit_enabled = True - self.high_value_room_revisit_interval_seconds = 300 # 默认 5 分钟 - self.high_value_room_revisit_watch_window_seconds = 900 # 默认仅在 15 分钟观察窗内回访 - self.high_value_room_revisit_skip_if_reservation_within_seconds = 120 # 若离预约参与窗口过近则跳过回访 - self.high_value_room_revisit_only_current_run = False # 若为 True,则仅回访本次运行记录的直播间 - # 预约回退校验开关:用于在运行时决定是否做回退后详细校验(可通过 Run 面板控制) - self.reservation_back_verify_enabled = True - - # 轮询策略:在预计开奖前多少秒开始积极轮询结果(默认 10 秒) - self.poll_before_open_seconds = 10 - # 预约抢占最小价值:低于该价值的预约不抢占当前任务(元,默认0表示任何预约可抢占) - self.reservation_preempt_min_value_yuan = 0.0 - - # 详情页识别兜底(参与按钮 OCR)节流 - self.detail_ocr_check_min_interval_seconds = 8.0 - - # 福袋详情识别异常(时间/价值)时:关闭重开后延迟再截图的秒数 - self.fudai_abnormal_reopen_delay_seconds = 1.2 - - # 定时禁抢:凌晨时段不抢福袋,仅持续养号 - self.fudai_quiet_hours_enabled = True - self.fudai_quiet_start_hour = 2 - self.fudai_quiet_end_hour = 7 - - # 运行中动态加载配置(网页端保存 config.json 后可生效) - self._last_config_reload_ts = 0.0 - - # 按需求:只保留“推荐页养号流程”(纯坐标点击),不再提供“推荐/直播/进入直播间”文本识别流程。 - # 养号总开关:关闭时不执行推荐页养号(只原地等待) - self.yanghao_enabled = True - # 推荐页养号:可配置的“时长/间隔(冷却)” - self.yanghao_recommend_duration_seconds = 60 - self.yanghao_recommend_interval_seconds = 0 # 0=不限制(每次触发都可执行) - self._yanghao_last_recommend_ts = 0.0 - - def _log_kv(self, *args, **fields): - """统一日志输出:保留 [tag] 前缀,同时提供中文 key=value 字段,方便 grep/debug。 - - 兼容性说明:有些地方可能通过 kwargs 传入名为 'tag' 或 'msg' 的键, - 为避免出现 "multiple values for argument 'tag'" 错误,这里优先使用位置参数, - 并在必要时从 fields 中移除重复键。 - """ - # 解析位置参数/关键字,位置参数优先 - tag = None - msg = None - if len(args) >= 1: - tag = args[0] - if len(args) >= 2: - msg = args[1] - # 若 kwargs 中包含 'tag'/'msg',且位置参数未提供,则取 kwargs 的值;若位置参数已提供,则删除以避免重复 - if 'tag' in fields: - if tag is None: - tag = fields.pop('tag') - else: - # 删除以避免后续处理将其误当作字段 - fields.pop('tag', None) - if 'msg' in fields: - if msg is None: - msg = fields.pop('msg') - else: - fields.pop('msg', None) - - try: - self._log_seq += 1 - except Exception: - self._log_seq = 1 - - key_map = { - # 通用 - "rid": "运行", - "seq": "序号", - "msg": "说明", - "biaoqian": "标签", - "bq": "标签", - "stage": "阶段", - "seen": "识别", - "next": "下一步", - "ok": "成功", - "text": "文本", - "action": "动作", - "result": "结果", - "mode": "模式", - "reason": "原因", - "wait_seconds": "等待秒", - "wait_s": "等待秒", - "remain_to_join_window_s": "距参与窗口秒", - "remain_wait_s": "剩余等待秒", - # 预约 - "value_yuan": "价值元", - "future": "开奖时间", - "pos_seen": "发现位置", - "qsize": "队列数量", - "max_try": "最大尝试次数", - "cap": "队列上限", - "dropped": "丢弃数量", - "dropped_value_yuan": "丢弃价值元", - "dropped_future": "丢弃开奖时间", - "back_times": "需回退次数", - "room_pos": "当前位置", - "target_future": "【目标】开奖时间", - "target_value_yuan": "【目标】价值元", - "target_content": "【目标】内容", - "queue_brief": "【队列】摘要", - "attempt": "尝试次数", - "room_title": "直播间名(清洗后)", - "room_title_raw": "直播间名原文", - "room_title_expected": "【预期】直播间名", - "room_title_current": "【当前】直播间名", - "room_title_ratio": "直播间名相似度", - "room_title_raw_expected": "【预期】直播间名原文", - "room_title_raw_current": "【当前】直播间名原文", - - # 预约回退校验:匹配调试字段(来自 _match_reservation debug_dict) - "expected_future": "【期望】开奖时间戳", - "actual_future": "【识别】开奖时间戳", - "future_diff_s": "开奖时间差秒", - "expected_value": "【期望】价值元", - "actual_value": "【识别】价值元", - "expected_content": "【期望】内容", - "actual_content": "【识别】内容", - # 新增字段映射 - "content": "内容", - "task_count": "任务数", - "countdown": "倒计时", - "min_participants": "最小参与人数", - "max_participants": "最大参与人数", - "min_value_yuan": "最小价值元", - "diag_text": "诊断文本", - "seconds": "耗时秒", - "enter_reason": "进入原因", - "fudai_x": "福袋X坐标", - "participants": "参与人数", - "copies": "份数", - "value_yuan": "价值元", - "keyword": "关键词", - "x": "X坐标", - "y": "Y坐标", - "clicks": "点击次数", - "abnormal": "异常", - "reasons": "原因", - } - - flat = [] - flat.append("{}={}".format(key_map.get("rid", "运行"), getattr(self, "_run_id", "-"))) - flat.append("{}={}".format(key_map.get("seq", "序号"), getattr(self, "_log_seq", 0))) - if msg: - m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 240: - m = m[:240] + "..." - flat.append("{}={}".format(key_map.get("msg", "说明"), m)) - - for k, v in (fields or {}).items(): - if v is None: - continue - s = str(v) - if s == "": - continue - s = s.replace("\r", " ").replace("\n", " ").strip() - if len(s) > 240: - s = s[:240] + "..." - ck = key_map.get(str(k), None) - if not ck: - # 兜底:避免英文 key 出现在日志里 - ck = "字段_{}".format(str(k)) - flat.append("{}={}".format(ck, s)) - - # 获取时间戳(格式:HH:MM:SS) - try: - timestamp = datetime.now().strftime('%H:%M:%S') - except Exception: - timestamp = "" - - # 构建日志行:格式为 [时间] [标签] 消息 字段... - # 如果消息为空,则只显示字段 - log_parts = [] - if timestamp: - log_parts.append(f"[{timestamp}]") - log_parts.append(f"[{tag}]") - - if msg: - m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 200: - m = m[:200] + "..." - log_parts.append(m) - - # 添加字段(使用中文key,格式化值) - for k, v in (fields or {}).items(): - if v is None: - continue - key_cn = key_map.get(str(k), None) - if not key_cn: - # 兜底:避免英文 key 出现在日志里 - key_cn = "字段_{}".format(str(k)) - - # 格式化值:数字保留适当精度,字符串截断 - if isinstance(v, float): - if abs(v) < 1: - v_str = f"{v:.3f}" - elif abs(v) < 100: - v_str = f"{v:.2f}" - else: - v_str = f"{int(v)}" - elif isinstance(v, (int, bool)): - v_str = str(v) - else: - s = str(v).replace("\r", " ").replace("\n", " ").strip() - if len(s) > 100: - s = s[:100] + "..." - v_str = s - - log_parts.append(f"{key_cn}={v_str}") - - # 构建完整日志行 - log_line = " ".join(log_parts) - - # 日志自动换行:每行最多130字符,超过则换行缩进继续输出 - if len(log_line) <= 130: - print(log_line) - else: - # 超长日志:首行显示时间+标签+消息,后续行显示字段 - parts = [] - # 首行:时间 + 标签 + 消息 - header_parts = [] - if timestamp: - header_parts.append(f"[{timestamp}]") - header_parts.append(f"[{tag}]") - if msg: - m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 200: - m = m[:200] + "..." - header_parts.append(m) - parts.append(" ".join(header_parts)) - - # 字段分行显示 - indent = " " # 2个空格缩进 - current_line = indent - - for k, v in (fields or {}).items(): - if v is None: - continue - key_cn = key_map.get(str(k), None) - if not key_cn: - key_cn = "字段_{}".format(str(k)) - - # 格式化值 - if isinstance(v, float): - if abs(v) < 1: - v_str = f"{v:.3f}" - elif abs(v) < 100: - v_str = f"{v:.2f}" - else: - v_str = f"{int(v)}" - elif isinstance(v, (int, bool)): - v_str = str(v) - else: - s = str(v).replace("\r", " ").replace("\n", " ").strip() - if len(s) > 100: - s = s[:100] + "..." - v_str = s - - field_str = f"{key_cn}={v_str}" - - # 检查是否需要换行(考虑缩进) - if len(current_line) + len(field_str) + 1 > 130: - if current_line.strip(): - parts.append(current_line.strip()) - current_line = indent + field_str - else: - if current_line == indent: - current_line += field_str - else: - current_line += " " + field_str - - if current_line.strip() and current_line != indent: - parts.append(current_line.strip()) - - print("\n".join(parts)) - - # 纯坐标点击所需的内部默认坐标(1080x2400 基准,会自动按分辨率缩放) - self.yanghao_fallback_close_x = 1030 - self.yanghao_fallback_close_y = 120 - self.yanghao_fallback_live_x = 900 - self.yanghao_fallback_live_y = 2280 - self.yanghao_fallback_enter_live_x = 109 - self.yanghao_fallback_enter_live_y = 376 - # 关注标签坐标(用于从推荐页面点击顶部“关注”标签) - # 坐标以 1080x2400 分辨率为基准;你提供的矩形为: - # 左上角 (674, 153),右下角 (749, 185),中心点约为 (712, 169) - self.yanghao_follow_tab_x = 712 # 关注标签中心的 x 坐标(1080x2400 基准) - self.yanghao_follow_tab_y = 169 # 关注标签中心的 y 坐标(1080x2400 基准) - - # 新养号动作:停留期间可按概率点爱心/收藏,停留结束后自动滑动到下一个 - self.yanghao_enable_actions = True - self.yanghao_like_prob = 0.15 - self.yanghao_fav_prob = 0.05 - self.yanghao_after_dwell_swipe_direction = "up" # up=下一个内容, down=上一个内容 - self.yanghao_after_dwell_swipe_distance_px = 900 - self.yanghao_like_keywords = ["赞", "喜欢", "Like"] - self.yanghao_fav_keywords = ["收藏", "加入收藏", "取消收藏", "Favorite"] - - # 爱心/收藏图标检测(更适合图标,避免文案/层级变化影响) - # 坐标以 1080x2400 为基准,会按当前分辨率缩放。 - self.yanghao_like_icon_x = 0 - self.yanghao_like_icon_y = 0 - self.yanghao_fav_icon_x = 0 - self.yanghao_fav_icon_y = 0 - # 仅用于“截图检测ROI”的偏移(不影响点击坐标)。用于微调截图中心。 - self.yanghao_like_roi_offset_x = 0 - self.yanghao_like_roi_offset_y = 0 - self.yanghao_fav_roi_offset_x = 0 - self.yanghao_fav_roi_offset_y = 0 - self.yanghao_icon_roi_size = 180 # 截取检测区域边长(px) - self.yanghao_icon_match_threshold = 0.72 - self.yanghao_like_template_path = os.path.join(os.path.dirname(__file__), "assets", "like.png") - self.yanghao_fav_template_path = os.path.join(os.path.dirname(__file__), "assets", "fav.png") - # 桌面图标模板(用于检测是否回到桌面) - self.desktop_icon_template_path = os.path.join(os.path.dirname(__file__), "assets", "desktop.png") - self.desktop_icon_x = 153 - self.desktop_icon_y = 260 - self.desktop_icon_roi_size = 200 - self.desktop_icon_match_threshold = 0.6 - - # 养号逐步截图(调试用,开启后会比较慢/占空间) - self.yanghao_step_screenshot = False - - # “评论/发弹幕”动作:仅在同时检测到爱心+收藏时,按概率触发 - self.yanghao_comment_prob = 0.0 - self.yanghao_comment_btn_x = 981 - self.yanghao_comment_btn_y = 1399 - self.yanghao_comment_input_x = 250 - self.yanghao_comment_input_y = 2218 - self.yanghao_comment_send_x = 906 - self.yanghao_comment_send_y = 1298 - self.yanghao_comment_close_x = 586 - self.yanghao_comment_close_y = 385 - self.yanghao_comment_texts = [] - - self.auto_join_fansclub = False # 是否自动尝试加入粉丝团(可能触发付费/钻石消耗) - self.fansclub_fail_action = "stay" # 粉丝团门槛无法处理时:stay=停留当前直播间,switch=切换下一个 - self.last_attend_fail_reason = "" # 最近一次参与失败原因 - - # 福袋图标检测提速参数(默认更快;可在 config.json 覆盖) - self.fudai_icon_retry_delay_seconds = 0.6 - self.fudai_icon_max_wait_seconds = 4.0 - # 最多尝试寻找福袋图标次数(默认 5,可由 UI 修改) - self.fudai_find_max_attempts = 5 - # 截图阶段诊断(OCR)节流:避免高频截图时反复 OCR 拖慢 - self.screenshot_diagnose_min_interval_seconds = 8.0 - self._last_diag_ts = 0.0 - self._last_diag_stage = "-" - self._last_diag_seen = "-" - - # 福袋详情异常重试预算:避免 OCR 异常时单次卡太久 - self.fudai_detail_retry_budget_seconds = 10.0 - self.load_config() - - def load_config(self): - """从配置文件中加载数据""" - if os.path.exists(self.config_path): - with open(self.config_path, "r", encoding="utf-8") as file: - config = json.load(file) - self.contains_not_want = config.get("contains_not_want", []) - self.contains_want = config.get("contains_want", []) - try: - self.min_prize_value_yuan = float(config.get("min_prize_value_yuan", 0) or 0) - except (TypeError, ValueError): - self.min_prize_value_yuan = 0.0 - try: - self.min_participants = int(config.get("min_participants", 0) or 0) - except (TypeError, ValueError): - self.min_participants = 0 - try: - self.max_participants = int(config.get("max_participants", 0) or 0) - except (TypeError, ValueError): - self.max_participants = 0 - try: - self.skip_if_countdown_lt_seconds = int(config.get("skip_if_countdown_lt_seconds", 15) or 15) - except (TypeError, ValueError): - self.skip_if_countdown_lt_seconds = 15 - - # 无福袋看门狗(30分钟无福袋回列表重进):默认关闭 - try: - self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", False)) - except Exception: - self.no_fudai_watchdog_enabled = False - - # 福袋图标检测提速参数 - try: - self.fudai_icon_retry_delay_seconds = float(config.get("fudai_icon_retry_delay_seconds", self.fudai_icon_retry_delay_seconds) or self.fudai_icon_retry_delay_seconds) - except (TypeError, ValueError): - pass - if self.fudai_icon_retry_delay_seconds < 0.2: - self.fudai_icon_retry_delay_seconds = 0.2 - if self.fudai_icon_retry_delay_seconds > 5: - self.fudai_icon_retry_delay_seconds = 5.0 - try: - self.fudai_icon_max_wait_seconds = float(config.get("fudai_icon_max_wait_seconds", self.fudai_icon_max_wait_seconds) or self.fudai_icon_max_wait_seconds) - except (TypeError, ValueError): - pass - if self.fudai_icon_max_wait_seconds < 0: - self.fudai_icon_max_wait_seconds = 0.0 - if self.fudai_icon_max_wait_seconds > 30: - self.fudai_icon_max_wait_seconds = 30.0 - try: - self.fudai_find_max_attempts = int(config.get("fudai_find_max_attempts", self.fudai_find_max_attempts) or self.fudai_find_max_attempts) - except (TypeError, ValueError): - pass - if self.fudai_find_max_attempts < 1: - self.fudai_find_max_attempts = 1 - if self.fudai_find_max_attempts > 50: - self.fudai_find_max_attempts = 50 - - # 截图阶段诊断(OCR)节流 - try: - self.screenshot_diagnose_min_interval_seconds = float( - config.get("screenshot_diagnose_min_interval_seconds", self.screenshot_diagnose_min_interval_seconds) - or self.screenshot_diagnose_min_interval_seconds - ) - except (TypeError, ValueError): - pass - if self.screenshot_diagnose_min_interval_seconds < 0: - self.screenshot_diagnose_min_interval_seconds = 0.0 - if self.screenshot_diagnose_min_interval_seconds > 60: - self.screenshot_diagnose_min_interval_seconds = 60.0 - - try: - self.reset_after_swipes_enabled = bool(config.get("reset_after_swipes_enabled", False)) - except Exception: - self.reset_after_swipes_enabled = False - try: - raw_reset_swipes = config.get("reset_after_swipes", 10) - self.reset_after_swipes = int(10 if raw_reset_swipes is None else raw_reset_swipes) - except (TypeError, ValueError): - self.reset_after_swipes = 10 - # 兼容旧配置:若未声明开关但阈值大于0,则自动视为开启 - if not config.get("reset_after_swipes_enabled", None) and self.reset_after_swipes > 0: - self.reset_after_swipes_enabled = True - if self.reset_after_swipes < 1: - self.reset_after_swipes = 1 - - # 高价值福袋预约 - try: - self.high_value_fudai_enabled = bool(config.get("high_value_fudai_enabled", False)) - except Exception: - self.high_value_fudai_enabled = False - try: - self.high_value_fudai_threshold_yuan = float(config.get("high_value_fudai_threshold_yuan", 1000.0) or 1000.0) - except (TypeError, ValueError): - self.high_value_fudai_threshold_yuan = 1000.0 - try: - self.high_value_fudai_join_ahead_seconds = int(config.get("high_value_fudai_join_ahead_seconds", 120) or 120) - except (TypeError, ValueError): - self.high_value_fudai_join_ahead_seconds = 120 - try: - self.high_value_fudai_max_swipe_back = int(config.get("high_value_fudai_max_swipe_back", 60) or 60) - except (TypeError, ValueError): - self.high_value_fudai_max_swipe_back = 60 - - try: - self.high_value_fudai_max_reservations = int(config.get("high_value_fudai_max_reservations", 5) or 5) - except (TypeError, ValueError): - self.high_value_fudai_max_reservations = 5 - if self.high_value_fudai_max_reservations < 1: - self.high_value_fudai_max_reservations = 1 - if self.high_value_fudai_max_reservations > 50: - self.high_value_fudai_max_reservations = 50 - - try: - self.high_value_fudai_after_action = str(config.get("high_value_fudai_after_action", "continue") or "continue").strip().lower() - except Exception: - self.high_value_fudai_after_action = "continue" - if self.high_value_fudai_after_action not in ("stay", "continue"): - self.high_value_fudai_after_action = "continue" - try: - self.high_value_fudai_after_stay_seconds = int(config.get("high_value_fudai_after_stay_seconds", 120) or 120) - except (TypeError, ValueError): - self.high_value_fudai_after_stay_seconds = 120 - if self.high_value_fudai_after_stay_seconds < 0: - self.high_value_fudai_after_stay_seconds = 0 - if self.high_value_fudai_after_stay_seconds > 3600: - self.high_value_fudai_after_stay_seconds = 3600 - - # 高价值直播间回访 - try: - self.high_value_room_revisit_enabled = bool(config.get("high_value_room_revisit_enabled", self.high_value_room_revisit_enabled)) - except Exception: - pass - try: - self.reservation_back_verify_enabled = bool(config.get("reservation_back_verify_enabled", True)) - except Exception: - self.reservation_back_verify_enabled = True - try: - self.reservation_preempt_min_value_yuan = float(config.get("reservation_preempt_min_value_yuan", self.reservation_preempt_min_value_yuan) or self.reservation_preempt_min_value_yuan) - except (TypeError, ValueError): - pass - if self.reservation_preempt_min_value_yuan < 0: - self.reservation_preempt_min_value_yuan = 0.0 - try: - self.poll_before_open_seconds = int(config.get("poll_before_open_seconds", self.poll_before_open_seconds) or self.poll_before_open_seconds) - except (TypeError, ValueError): - pass - if self.poll_before_open_seconds < 0: - self.poll_before_open_seconds = 0 - try: - self.high_value_room_revisit_interval_seconds = float( - config.get("high_value_room_revisit_interval_seconds", self.high_value_room_revisit_interval_seconds) - or self.high_value_room_revisit_interval_seconds - ) - except (TypeError, ValueError): - pass - if self.high_value_room_revisit_interval_seconds < 60: - self.high_value_room_revisit_interval_seconds = 60.0 - if self.high_value_room_revisit_interval_seconds > 1800: - self.high_value_room_revisit_interval_seconds = 1800.0 - - try: - self.high_value_room_revisit_watch_window_seconds = float( - config.get("high_value_room_revisit_watch_window_seconds", self.high_value_room_revisit_watch_window_seconds) - or self.high_value_room_revisit_watch_window_seconds - ) - except (TypeError, ValueError): - pass - if self.high_value_room_revisit_watch_window_seconds < 60: - self.high_value_room_revisit_watch_window_seconds = 60.0 - if self.high_value_room_revisit_watch_window_seconds > 7200: - self.high_value_room_revisit_watch_window_seconds = 7200.0 - - try: - self.high_value_room_revisit_skip_if_reservation_within_seconds = int( - config.get( - "high_value_room_revisit_skip_if_reservation_within_seconds", - self.high_value_room_revisit_skip_if_reservation_within_seconds, - ) - or self.high_value_room_revisit_skip_if_reservation_within_seconds - ) - except (TypeError, ValueError): - pass - if self.high_value_room_revisit_skip_if_reservation_within_seconds < 0: - self.high_value_room_revisit_skip_if_reservation_within_seconds = 0 - if self.high_value_room_revisit_skip_if_reservation_within_seconds > 1800: - self.high_value_room_revisit_skip_if_reservation_within_seconds = 1800 - - # 详情页 OCR 兜底节流 - try: - self.detail_ocr_check_min_interval_seconds = float( - config.get("detail_ocr_check_min_interval_seconds", self.detail_ocr_check_min_interval_seconds) - or self.detail_ocr_check_min_interval_seconds - ) - except (TypeError, ValueError): - pass - if self.detail_ocr_check_min_interval_seconds < 0: - self.detail_ocr_check_min_interval_seconds = 0.0 - if self.detail_ocr_check_min_interval_seconds > 60: - self.detail_ocr_check_min_interval_seconds = 60.0 - - # 福袋详情异常(时间/价值)重开延迟 - try: - self.fudai_abnormal_reopen_delay_seconds = float( - config.get("fudai_abnormal_reopen_delay_seconds", 1.2) or 1.2 - ) - except (TypeError, ValueError): - self.fudai_abnormal_reopen_delay_seconds = 1.2 - if self.fudai_abnormal_reopen_delay_seconds < 0: - self.fudai_abnormal_reopen_delay_seconds = 0.0 - if self.fudai_abnormal_reopen_delay_seconds > 10: - self.fudai_abnormal_reopen_delay_seconds = 10.0 - - # 福袋详情异常重试预算 - try: - self.fudai_detail_retry_budget_seconds = float( - config.get("fudai_detail_retry_budget_seconds", self.fudai_detail_retry_budget_seconds) - or self.fudai_detail_retry_budget_seconds - ) - except (TypeError, ValueError): - pass - if self.fudai_detail_retry_budget_seconds < 0: - self.fudai_detail_retry_budget_seconds = 0.0 - if self.fudai_detail_retry_budget_seconds > 60: - self.fudai_detail_retry_budget_seconds = 60.0 - - # 定时禁抢(默认 2:00-7:00) - try: - self.fudai_quiet_hours_enabled = bool(config.get("fudai_quiet_hours_enabled", True)) - except Exception: - self.fudai_quiet_hours_enabled = True - try: - self.fudai_quiet_start_hour = int(config.get("fudai_quiet_start_hour", 2) or 2) - except (TypeError, ValueError): - self.fudai_quiet_start_hour = 2 - try: - self.fudai_quiet_end_hour = int(config.get("fudai_quiet_end_hour", 7) or 7) - except (TypeError, ValueError): - self.fudai_quiet_end_hour = 7 - - # 只保留推荐页养号:忽略旧字段与流程开关 - try: - self.yanghao_enabled = bool(config.get("yanghao_enabled", True)) - except Exception: - self.yanghao_enabled = True - try: - self.yanghao_recommend_duration_seconds = int(config.get("yanghao_recommend_duration_seconds", 60) or 60) - except (TypeError, ValueError): - self.yanghao_recommend_duration_seconds = 60 - try: - self.yanghao_recommend_interval_seconds = int(config.get("yanghao_recommend_interval_seconds", 0) or 0) - except (TypeError, ValueError): - self.yanghao_recommend_interval_seconds = 0 - # 注意:不再从 config 读取“推荐/直播/进入直播间文本”与“兜底坐标”;统一使用代码内默认坐标。 - - self.yanghao_enable_actions = bool(config.get("yanghao_enable_actions", True)) - try: - self.yanghao_like_prob = float(config.get("yanghao_like_prob", 0.15) or 0.15) - except (TypeError, ValueError): - self.yanghao_like_prob = 0.15 - try: - self.yanghao_fav_prob = float(config.get("yanghao_fav_prob", 0.05) or 0.05) - except (TypeError, ValueError): - self.yanghao_fav_prob = 0.05 - self.yanghao_after_dwell_swipe_direction = str( - config.get("yanghao_after_dwell_swipe_direction", "up") or "up" - ).strip().lower() - try: - self.yanghao_after_dwell_swipe_distance_px = int( - config.get("yanghao_after_dwell_swipe_distance_px", 900) or 900 - ) - except (TypeError, ValueError): - self.yanghao_after_dwell_swipe_distance_px = 900 - - lk = config.get("yanghao_like_keywords", ["赞", "喜欢", "Like"]) or ["赞", "喜欢", "Like"] - fk = config.get("yanghao_fav_keywords", ["收藏", "加入收藏", "取消收藏", "Favorite"]) or ["收藏", "加入收藏", "取消收藏", "Favorite"] - if isinstance(lk, list): - self.yanghao_like_keywords = [str(x) for x in lk if str(x).strip()] - if isinstance(fk, list): - self.yanghao_fav_keywords = [str(x) for x in fk if str(x).strip()] - - # 图标检测配置(可选) - try: - self.yanghao_like_icon_x = int(config.get("yanghao_like_icon_x", 0) or 0) - except (TypeError, ValueError): - self.yanghao_like_icon_x = 0 - try: - self.yanghao_like_icon_y = int(config.get("yanghao_like_icon_y", 0) or 0) - except (TypeError, ValueError): - self.yanghao_like_icon_y = 0 - try: - self.yanghao_fav_icon_x = int(config.get("yanghao_fav_icon_x", 0) or 0) - except (TypeError, ValueError): - self.yanghao_fav_icon_x = 0 - try: - self.yanghao_fav_icon_y = int(config.get("yanghao_fav_icon_y", 0) or 0) - except (TypeError, ValueError): - self.yanghao_fav_icon_y = 0 - - # ROI 偏移(可选) - for k, attr in ( - ("yanghao_like_roi_offset_x", "yanghao_like_roi_offset_x"), - ("yanghao_like_roi_offset_y", "yanghao_like_roi_offset_y"), - ("yanghao_fav_roi_offset_x", "yanghao_fav_roi_offset_x"), - ("yanghao_fav_roi_offset_y", "yanghao_fav_roi_offset_y"), - ): - try: - setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr))) - except (TypeError, ValueError): - pass - try: - self.yanghao_icon_roi_size = int(config.get("yanghao_icon_roi_size", 180) or 180) - except (TypeError, ValueError): - self.yanghao_icon_roi_size = 180 - try: - self.yanghao_icon_match_threshold = float(config.get("yanghao_icon_match_threshold", 0.72) or 0.72) - except (TypeError, ValueError): - self.yanghao_icon_match_threshold = 0.72 - tp_like = str(config.get("yanghao_like_template_path", self.yanghao_like_template_path) or self.yanghao_like_template_path) - tp_fav = str(config.get("yanghao_fav_template_path", self.yanghao_fav_template_path) or self.yanghao_fav_template_path) - base_dir = os.path.dirname(__file__) - if tp_like and (not os.path.isabs(tp_like)): - tp_like = os.path.normpath(os.path.join(base_dir, tp_like)) - if tp_fav and (not os.path.isabs(tp_fav)): - tp_fav = os.path.normpath(os.path.join(base_dir, tp_fav)) - self.yanghao_like_template_path = tp_like - self.yanghao_fav_template_path = tp_fav - - # 逐步截图开关(可选) - try: - self.yanghao_step_screenshot = bool(config.get("yanghao_step_screenshot", False)) - except Exception: - self.yanghao_step_screenshot = False - - # 评论动作配置 - try: - self.yanghao_comment_prob = float(config.get("yanghao_comment_prob", 0.0) or 0.0) - except (TypeError, ValueError): - self.yanghao_comment_prob = 0.0 - for k, attr in ( - ("yanghao_comment_btn_x", "yanghao_comment_btn_x"), - ("yanghao_comment_btn_y", "yanghao_comment_btn_y"), - ("yanghao_comment_input_x", "yanghao_comment_input_x"), - ("yanghao_comment_input_y", "yanghao_comment_input_y"), - ("yanghao_comment_send_x", "yanghao_comment_send_x"), - ("yanghao_comment_send_y", "yanghao_comment_send_y"), - ("yanghao_comment_close_x", "yanghao_comment_close_x"), - ("yanghao_comment_close_y", "yanghao_comment_close_y"), - ): - try: - setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr))) - except (TypeError, ValueError): - pass - - ct = config.get("yanghao_comment_texts", []) or [] - if isinstance(ct, list): - self.yanghao_comment_texts = [str(x).strip() for x in ct if str(x).strip()] - self.auto_join_fansclub = bool(config.get("auto_join_fansclub", False)) - self.fansclub_fail_action = str(config.get("fansclub_fail_action", "stay") or "stay").lower() - - def _maybe_reload_config(self, min_interval_seconds: float = 2.0) -> None: - """运行中定期从 config.json 重新加载配置,便于网页端随时修改。""" - try: - now = time.time() - if (now - float(self._last_config_reload_ts or 0.0)) < float(min_interval_seconds or 0.0): - return - self._last_config_reload_ts = now - self.load_config() - except Exception: - pass - - def _mark_enter_live(self, reason: str = "") -> None: - """标记一次“已进入直播间”,用于统计后续找到福袋图标的耗时。""" - try: - self._enter_live_ts = float(time.time()) - except Exception: - self._enter_live_ts = 0.0 - try: - self._enter_live_reason = str(reason or "") - except Exception: - self._enter_live_reason = "" - self._enter_live_fudai_logged = False - - def _in_quiet_hours(self, hour: int) -> bool: - """判断当前小时是否处于禁抢时段(支持跨天区间)。""" - try: - h = int(hour) - except Exception: - return False - try: - start = int(self.fudai_quiet_start_hour) - end = int(self.fudai_quiet_end_hour) - except Exception: - start, end = 2, 7 - # 归一化 - start = start % 24 - end = end % 24 - if start == end: - return False - if start < end: - return start <= h < end - # 跨天:例如 22-7 - return (h >= start) or (h < end) - - def _save_step_screenshot(self, label: str) -> str | None: - """保存当前屏幕截图为独立文件,便于你逐步核对是否点对了位置。""" - try: - base_dir = os.path.join(os.path.dirname(__file__), "pic") - os.makedirs(base_dir, exist_ok=True) - - ok = self._shot_and_diagnose("养号截图", "保存逐步截图({})".format(label), self.device_id) - if not ok: - return None - src = os.path.join(base_dir, "screenshot.png") - if not os.path.exists(src): - return None - - safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fa5_-]+", "_", str(label or "step")) - label_dir = os.path.join(base_dir, safe) - os.makedirs(label_dir, exist_ok=True) - # 同时保存一份带时间戳的历史截图 + 覆盖 latest.png - ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f") - dst_hist = os.path.join(label_dir, f"{ts}.png") - dst_latest = os.path.join(label_dir, "latest.png") - shutil.copyfile(src, dst_hist) - shutil.copyfile(src, dst_latest) - print(f"[养号] 截图已保存:{dst_hist} (latest已更新)") - return dst_hist - except Exception as e: - print(f"[养号] 截图保存失败:{e}") - return None - - def _scale_from_base(self, x: int, y: int, base_w: int = 1080, base_h: int = 2400) -> tuple[int, int]: - try: - sx = int(int(x) * int(self.resolution_ratio_x) / int(base_w)) - sy = int(int(y) * int(self.resolution_ratio_y) / int(base_h)) - except Exception: - sx, sy = int(x), int(y) - return sx, sy - - def _capture_roi_screenshot(self, label: str, center_x: int, center_y: int, size_px: int) -> str | None: - """截屏并裁剪指定坐标附近 ROI,保存到 pic/