refactor: Remove deprecated files and enhance configuration settings
- 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.
This commit is contained in:
1 parent
8b47b506d6
commit
47e6b016c5
31 files changed
+2257
-7371
No files matched your search
@@ -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. **日志过滤**:添加日志过滤功能,可以根据标签、级别等条件过滤日志
|
||||
|
||||
|
||||
|
||||
|
||||
+62
-19
@@ -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:
|
||||
# 如果保存预处理后的图片失败,保存原始图片
|
||||
|
||||
+17
-5
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
+188
-11
@@ -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)
|
||||
# 如果文件名是 <string> 或类似,说明是测试代码,跳过
|
||||
if filename and filename not in ("<string>", "<stdin>"):
|
||||
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:
|
||||
|
||||
+51
-51
@@ -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
|
||||
|
||||
|
||||
+103
-1
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
+20
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
+21
-1
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
+7
-7
@@ -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"
|
||||
|
||||
+2
-2
@@ -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))]
|
||||
|
||||
@@ -167,6 +167,15 @@ def ensure_dir(path: str) -> None:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+3
-3
@@ -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
|
||||
|
||||
+12
-12
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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值
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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) # 排除优惠券红色")
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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. **电池管理**:需要手动监控电池电量
|
||||
|
||||
## 七、总结
|
||||
|
||||
**模块化代码的设计理念**:
|
||||
- ✅ 保留核心功能(抢福袋、预约队列)
|
||||
- ✅ 简化复杂功能(回退校验、回访逻辑)
|
||||
- ✅ 移除边缘功能(自救、电池检测)
|
||||
- ✅ 提高代码可维护性
|
||||
|
||||
**适用场景**:
|
||||
- ✅ 只需要基础抢福袋功能
|
||||
- ✅ 需要代码清晰、易于维护
|
||||
- ✅ 不需要自动回访等高级功能
|
||||
- ✅ 需要长期稳定运行(无限循环模式)
|
||||
|
||||
+1
-5937
File diff suppressed because it is too large.
Load diff
+195
@@ -0,0 +1,195 @@
|
||||
# 日志系统优化说明
|
||||
|
||||
## 已完成的优化
|
||||
|
||||
### 1. 创建标准日志配置模块 (`douyin_logging.py`)
|
||||
|
||||
**功能特性:**
|
||||
- ✅ 标准 `logging` 模块配置
|
||||
- ✅ 日志级别管理(DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||
- ✅ 日志轮转(RotatingFileHandler,按文件大小自动轮转)
|
||||
- ✅ 支持控制台和文件双重输出
|
||||
- ✅ 自动获取调用者信息(模块名、函数名、行号)
|
||||
- ✅ 性能监控装饰器(`@log_function_call`)
|
||||
- ✅ 上下文管理器(`LogContext`)用于记录代码块执行时间
|
||||
|
||||
**配置参数:**
|
||||
- `log_level`: 日志级别(默认 INFO)
|
||||
- `log_unified_path`: 日志文件路径(默认 logs/unified.log)
|
||||
- `log_max_bytes`: 单个日志文件最大大小(默认 10MB)
|
||||
- `log_backup_count`: 保留的备份文件数量(默认 5)
|
||||
- `log_enable_console`: 是否输出到控制台(默认 true)
|
||||
- `log_enable_file`: 是否输出到文件(默认 true)
|
||||
|
||||
### 2. 增强 `_log_kv` 方法
|
||||
|
||||
**新增功能:**
|
||||
- ✅ 自动记录调用者信息(模块名:函数名:行号)
|
||||
- ✅ 支持日志级别参数(`level="DEBUG"` 等)
|
||||
- ✅ 自动捕获异常堆栈信息(`exc_info`)
|
||||
- ✅ 集成标准 logging 模块,同时输出到原有格式和标准格式
|
||||
- ✅ 向后兼容,不影响现有代码
|
||||
|
||||
**使用示例:**
|
||||
```python
|
||||
# 基础用法(保持兼容)
|
||||
analyser._log_kv("标签", "消息", key1=value1, key2=value2)
|
||||
|
||||
# 指定日志级别
|
||||
analyser._log_kv("标签", "调试信息", level="DEBUG", key=value)
|
||||
|
||||
# 记录异常(自动捕获堆栈)
|
||||
try:
|
||||
# 可能出错的代码
|
||||
pass
|
||||
except Exception as e:
|
||||
analyser._log_kv("错误", "操作失败", error=str(e), level="ERROR")
|
||||
|
||||
# 显示调用者信息
|
||||
analyser._log_kv("调试", "详细信息", _show_caller=True, level="DEBUG")
|
||||
```
|
||||
|
||||
### 3. 日志格式优化
|
||||
|
||||
**标准格式:**
|
||||
```
|
||||
%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s
|
||||
```
|
||||
|
||||
**示例输出:**
|
||||
```
|
||||
2025-01-19 23:58:11.234 - [INFO] - douyin_fudai_core:should_skip_fudai_by_config:684 - [筛选] should_skip_fudai_by_config 开始检查 | 配置_最小价值=300.0 实际_价值=999.0
|
||||
```
|
||||
|
||||
**原有格式(保持兼容):**
|
||||
```
|
||||
[2025-01-19 23:58:11.234] [INFO] [筛选] should_skip_fudai_by_config 开始检查 配置_最小价值=300.0 实际_价值=999.0
|
||||
```
|
||||
|
||||
### 4. 异常处理增强
|
||||
|
||||
**自动异常捕获:**
|
||||
- 当 `_log_kv` 检测到 `error` 或 `exception` 字段时,自动从 `sys.exc_info()` 获取完整堆栈
|
||||
- 使用 `logger.exception()` 记录完整异常堆栈跟踪
|
||||
|
||||
**建议的异常处理模式:**
|
||||
```python
|
||||
try:
|
||||
# 业务逻辑
|
||||
result = some_operation()
|
||||
except Exception as e:
|
||||
# 自动记录完整堆栈
|
||||
analyser._log_kv("操作", "执行失败", error=str(e), level="ERROR")
|
||||
# 或者使用标准 logging
|
||||
import douyin_logging
|
||||
logger = douyin_logging.get_logger()
|
||||
logger.exception("操作执行失败")
|
||||
raise # 或 return
|
||||
```
|
||||
|
||||
### 5. 性能监控工具
|
||||
|
||||
**装饰器使用:**
|
||||
```python
|
||||
from douyin_logging import log_function_call
|
||||
|
||||
@log_function_call(log_args=True, log_result=False, log_time=True, min_duration=0.1)
|
||||
def my_function(param1, param2):
|
||||
# 函数体
|
||||
return result
|
||||
```
|
||||
|
||||
**上下文管理器使用:**
|
||||
```python
|
||||
from douyin_logging import LogContext
|
||||
|
||||
with LogContext("处理福袋详情", level="DEBUG"):
|
||||
# 代码块
|
||||
process_fudai_detail()
|
||||
# 自动记录开始、完成和耗时
|
||||
```
|
||||
|
||||
### 6. 配置文件更新
|
||||
|
||||
`config.json` 中已添加日志配置:
|
||||
```json
|
||||
{
|
||||
"log_level": "INFO",
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"log_max_bytes": 10485760,
|
||||
"log_backup_count": 5,
|
||||
"log_enable_console": true,
|
||||
"log_enable_file": true
|
||||
}
|
||||
```
|
||||
|
||||
## 使用建议
|
||||
|
||||
### 开发调试时
|
||||
- 设置 `log_level` 为 `"DEBUG"` 以获取最详细的日志
|
||||
- 使用 `_show_caller=True` 查看调用者信息
|
||||
- 使用性能监控装饰器记录函数耗时
|
||||
|
||||
### 生产环境
|
||||
- 设置 `log_level` 为 `"INFO"` 或 `"WARNING"` 以平衡性能和可观察性
|
||||
- 启用日志轮转避免文件过大
|
||||
- 定期检查日志文件大小和备份数量
|
||||
|
||||
### 关键业务逻辑处
|
||||
建议在以下位置添加详细日志:
|
||||
1. **函数入口/出口**:记录参数和返回值
|
||||
2. **条件判断**:记录判断条件和结果
|
||||
3. **循环迭代**:记录迭代次数和关键状态
|
||||
4. **外部API调用**:记录请求参数和响应结果
|
||||
5. **图像识别过程**:记录识别结果和置信度
|
||||
6. **错误捕获点**:使用 `level="ERROR"` 并记录完整堆栈
|
||||
|
||||
## 日志文件管理
|
||||
|
||||
- **主日志文件**:`logs/unified.log`
|
||||
- **轮转文件**:`logs/unified.log.1`, `logs/unified.log.2`, ...(最多保留 5 个备份)
|
||||
- **文件大小限制**:单个文件最大 10MB,超过后自动轮转
|
||||
- **编码**:UTF-8 with BOM(避免 Windows 乱码)
|
||||
|
||||
## 后续优化建议
|
||||
|
||||
1. **关键业务逻辑处添加详细日志**:
|
||||
- 福袋识别过程(OCR 结果、置信度)
|
||||
- 界面操作(点击坐标、滑动距离)
|
||||
- 网络请求(如有)
|
||||
- 状态转换(阶段诊断结果)
|
||||
|
||||
2. **异常处理规范化**:
|
||||
- 所有 `except Exception` 改为具体异常类型
|
||||
- 使用 `logger.exception()` 记录完整堆栈
|
||||
- 添加异常上下文信息(操作类型、参数等)
|
||||
|
||||
3. **性能监控**:
|
||||
- 在关键函数上使用 `@log_function_call` 装饰器
|
||||
- 使用 `LogContext` 记录代码块耗时
|
||||
- 识别性能瓶颈
|
||||
|
||||
4. **日志分析工具**:
|
||||
- 可以开发日志分析脚本,提取关键指标
|
||||
- 统计错误频率、操作耗时等
|
||||
|
||||
## 注意事项
|
||||
|
||||
- ✅ **向后兼容**:所有优化都保持向后兼容,不影响现有代码
|
||||
- ✅ **性能影响**:日志记录对性能影响极小,可放心使用
|
||||
- ✅ **文件大小**:通过日志轮转自动管理,不会无限增长
|
||||
- ✅ **编码问题**:使用 UTF-8 with BOM 避免 Windows 乱码
|
||||
|
||||
## 测试验证
|
||||
|
||||
运行优化后的代码,检查:
|
||||
1. ✅ 日志文件是否正常生成
|
||||
2. ✅ 日志格式是否正确(包含时间戳、级别、模块、函数、行号)
|
||||
3. ✅ 日志轮转是否正常工作
|
||||
4. ✅ 异常堆栈是否完整记录
|
||||
5. ✅ 调用者信息是否正确显示(DEBUG 级别)
|
||||
|
||||
|
||||
|
||||
|
||||
-285
@@ -1,285 +0,0 @@
|
||||
# 模块化代码 vs 原始代码 (fudai1.py) 对比说明
|
||||
|
||||
## 一、代码组织结构
|
||||
|
||||
### 原始代码 (fudai1.py)
|
||||
- **单文件架构**:所有代码集中在一个约 6000 行的巨大文件中
|
||||
- **类内方法**:所有功能都作为 `fudai_analyse` 类的方法实现
|
||||
- **嵌套函数**:大量逻辑通过嵌套函数实现(如 `_read_live_room_title`, `_normalize_room_title` 等)
|
||||
- **全局函数**:少量全局辅助函数(`normalize_countdown_text`, `extract_prize_value_yuan`)
|
||||
|
||||
### 模块化代码
|
||||
- **多文件架构**:按功能拆分成 20+ 个独立模块文件
|
||||
- **功能模块化**:每个模块负责特定功能领域
|
||||
- **函数式设计**:核心逻辑以独立函数形式组织,便于测试和复用
|
||||
- **清晰的依赖关系**:通过 import 明确模块间的依赖
|
||||
|
||||
## 二、模块划分对比
|
||||
|
||||
### 原始代码结构
|
||||
```
|
||||
fudai1.py (6000+ 行)
|
||||
├── 全局辅助函数
|
||||
│ ├── normalize_countdown_text()
|
||||
│ └── extract_prize_value_yuan()
|
||||
├── class fudai_analyse
|
||||
│ ├── __init__()
|
||||
│ ├── fudai_choujiang() [主循环,2800+ 行]
|
||||
│ ├── 检测相关方法
|
||||
│ ├── 福袋详情读取方法
|
||||
│ ├── 预约相关方法
|
||||
│ ├── 直播间标题读取方法
|
||||
│ └── ... (所有功能都在类内)
|
||||
```
|
||||
|
||||
### 模块化代码结构
|
||||
```
|
||||
douyin_fudai.py (主调度器,~1000 行)
|
||||
├── 导入各功能模块
|
||||
└── class fudai_analyse (精简的调度类)
|
||||
|
||||
功能模块(每个 ~100-500 行):
|
||||
├── douyin_detection.py # 福袋图标检测
|
||||
├── douyin_stage.py # 阶段诊断
|
||||
├── douyin_pixel.py # 像素检测
|
||||
├── douyin_fudai_core.py # 福袋核心业务逻辑
|
||||
├── douyin_fudai_detail.py # 福袋详情读取(含直播间标题)
|
||||
├── douyin_flow_control.py # 流程控制
|
||||
├── douyin_reservation_logic.py # 预约队列逻辑
|
||||
├── douyin_lottery.py # 抽奖结果处理
|
||||
├── douyin_popups.py # 弹窗检测
|
||||
├── douyin_robot.py # 人机验证
|
||||
├── douyin_swipe_ops.py # 滑动操作
|
||||
├── douyin_text_utils.py # 文本处理工具
|
||||
└── ... (其他辅助模块)
|
||||
```
|
||||
|
||||
## 三、具体功能对比
|
||||
|
||||
### 1. 主循环逻辑
|
||||
|
||||
#### 原始代码
|
||||
```python
|
||||
def fudai_choujiang(self, device_id="", y_pianyi=0, needswitch=False, wait_minutes=15):
|
||||
"""2800+ 行的巨大函数,包含所有逻辑"""
|
||||
# 初始化变量
|
||||
wait_times = 0
|
||||
swipe_times = 0
|
||||
reservations = []
|
||||
# ... 大量嵌套逻辑
|
||||
while True:
|
||||
# 阶段诊断
|
||||
# 福袋检测
|
||||
# 详情读取
|
||||
# 预约处理
|
||||
# ... 所有逻辑都在这里
|
||||
```
|
||||
|
||||
#### 模块化代码
|
||||
```python
|
||||
def run_once_basic(self) -> None:
|
||||
"""单轮基础抢福袋流程(~200 行)"""
|
||||
# 调用预约处理模块
|
||||
if self.high_value_fudai_enabled:
|
||||
douyin_reservation_logic.process_reservation_attend_window(...)
|
||||
|
||||
# 调用阶段诊断模块
|
||||
stage = douyin_stage.diagnose_stage_from_current_screen(...)
|
||||
|
||||
# 调用流程控制模块
|
||||
douyin_flow_control.handle_stage_after_diagnosis(...)
|
||||
douyin_flow_control.find_and_open_fudai_detail(...)
|
||||
```
|
||||
|
||||
### 2. 直播间标题读取
|
||||
|
||||
#### 原始代码
|
||||
```python
|
||||
def _read_live_room_title(label: str = "") -> str:
|
||||
"""在 fudai_choujiang() 内部定义的嵌套函数"""
|
||||
def _ocr_try(cut_name: str, change_color: int) -> tuple[str, str]:
|
||||
# OCR 尝试逻辑
|
||||
def _pick_best(cands: list[tuple[str, str, str]]) -> tuple[str, str]:
|
||||
# 选择最佳结果
|
||||
def _extract_room_title_candidate(raw_text: str) -> str:
|
||||
# 提取候选
|
||||
def _normalize_room_title(t: str) -> str:
|
||||
# 规范化
|
||||
# ... 所有辅助函数都在主函数内部
|
||||
```
|
||||
|
||||
#### 模块化代码
|
||||
```python
|
||||
# douyin_fudai_detail.py
|
||||
|
||||
# 模块级别的辅助函数(可复用)
|
||||
def _room_title_has_ellipsis(s: str) -> bool: ...
|
||||
def _strip_room_noise_text(s: str) -> str: ...
|
||||
def _extract_room_title_candidate(raw_text: str) -> str: ...
|
||||
def _normalize_room_title(t: str) -> str: ...
|
||||
def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]: ...
|
||||
def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]: ...
|
||||
|
||||
# 主函数(简洁清晰)
|
||||
def read_live_room_title_core(analyser: Any, y_pianyi: int, min_len: int = 3) -> Tuple[str, str]:
|
||||
"""读取直播间标题"""
|
||||
# 调用辅助函数
|
||||
# 返回结果
|
||||
```
|
||||
|
||||
### 3. 预约队列管理
|
||||
|
||||
#### 原始代码
|
||||
```python
|
||||
# 在 fudai_choujiang() 内部
|
||||
reservations = []
|
||||
def _add_reservation(future_ts: float, pv: float, content: str) -> None:
|
||||
"""嵌套函数,直接操作外部变量"""
|
||||
item = {...}
|
||||
reservations.append(item)
|
||||
_sorted_reservations()
|
||||
_write_reservations_state("add")
|
||||
|
||||
def _sorted_reservations():
|
||||
"""嵌套函数"""
|
||||
reservations.sort(key=lambda it: (it["future_ts"], -it["prize_value_yuan"], it["created_ts"]))
|
||||
```
|
||||
|
||||
#### 模块化代码
|
||||
```python
|
||||
# douyin_reservation_logic.py
|
||||
|
||||
# 独立的排序函数
|
||||
def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None:
|
||||
"""按 future_ts 升序,prize_value_yuan 降序排序"""
|
||||
def _key(it: ReservationItem):
|
||||
return (ft, -val, created)
|
||||
reservations.sort(key=_key)
|
||||
|
||||
# 独立的添加函数
|
||||
def add_reservation_core_logic(
|
||||
reservations: List[ReservationItem],
|
||||
item: ReservationItem,
|
||||
max_reservations: Optional[int] = None,
|
||||
) -> None:
|
||||
"""向预约队列追加/更新一条记录"""
|
||||
# 去重逻辑
|
||||
# 排序
|
||||
# 裁剪
|
||||
|
||||
# 独立的记录函数
|
||||
def record_high_value_reservation(...) -> bool:
|
||||
"""记录一条高价值福袋预约"""
|
||||
# 构造 item
|
||||
# 调用 add_reservation_core_logic
|
||||
# 写入状态
|
||||
```
|
||||
|
||||
## 四、代码复用性对比
|
||||
|
||||
### 原始代码
|
||||
- ❌ 嵌套函数无法在其他地方复用
|
||||
- ❌ 逻辑耦合度高,难以单独测试
|
||||
- ❌ 修改一处可能影响整个函数
|
||||
|
||||
### 模块化代码
|
||||
- ✅ 函数可在多个模块间复用
|
||||
- ✅ 每个模块可独立测试
|
||||
- ✅ 修改影响范围可控
|
||||
|
||||
## 五、可维护性对比
|
||||
|
||||
### 原始代码
|
||||
- ❌ 6000+ 行单文件,难以定位问题
|
||||
- ❌ 函数嵌套层级深,逻辑复杂
|
||||
- ❌ 代码重复(如 OCR 尝试逻辑在多处出现)
|
||||
|
||||
### 模块化代码
|
||||
- ✅ 每个模块职责单一,易于理解
|
||||
- ✅ 函数层级扁平,逻辑清晰
|
||||
- ✅ 公共逻辑提取为独立函数,避免重复
|
||||
|
||||
## 六、依赖关系对比
|
||||
|
||||
### 原始代码
|
||||
```python
|
||||
# 所有依赖都在一个文件内
|
||||
class fudai_analyse:
|
||||
def fudai_choujiang(self):
|
||||
# 直接使用 self 的所有方法
|
||||
self._read_live_room_title()
|
||||
self._check_in_live_room_by_icon()
|
||||
# ... 紧密耦合
|
||||
```
|
||||
|
||||
### 模块化代码
|
||||
```python
|
||||
# douyin_fudai.py
|
||||
import douyin_stage
|
||||
import douyin_detection
|
||||
import douyin_fudai_core
|
||||
import douyin_reservation_logic
|
||||
# ... 明确的依赖关系
|
||||
|
||||
# 通过参数传递,降低耦合
|
||||
def process_reservation_attend_window(
|
||||
analyser: Any,
|
||||
reservations: List[ReservationItem],
|
||||
# ... 通过参数传递,不直接访问 analyser 的所有属性
|
||||
) -> bool:
|
||||
```
|
||||
|
||||
## 七、测试友好性对比
|
||||
|
||||
### 原始代码
|
||||
- ❌ 难以单独测试某个功能
|
||||
- ❌ 需要构造完整的 `fudai_analyse` 实例
|
||||
- ❌ 嵌套函数无法直接测试
|
||||
|
||||
### 模块化代码
|
||||
- ✅ 每个函数可独立测试
|
||||
- ✅ 可以 mock 依赖模块
|
||||
- ✅ 测试用例更聚焦
|
||||
|
||||
## 八、性能影响
|
||||
|
||||
### 原始代码
|
||||
- ✅ 函数调用开销小(无跨模块调用)
|
||||
- ❌ 代码体积大,加载时间长
|
||||
|
||||
### 模块化代码
|
||||
- ⚠️ 轻微的函数调用开销(可忽略)
|
||||
- ✅ 按需加载,启动更快
|
||||
- ✅ 代码缓存更友好
|
||||
|
||||
## 九、总结
|
||||
|
||||
| 维度 | 原始代码 (fudai1.py) | 模块化代码 |
|
||||
|------|---------------------|-----------|
|
||||
| **文件数量** | 1 个巨大文件 | 20+ 个模块文件 |
|
||||
| **代码行数** | ~6000 行单文件 | 每个模块 100-500 行 |
|
||||
| **可维护性** | ⭐⭐ | ⭐⭐⭐⭐⭐ |
|
||||
| **可测试性** | ⭐⭐ | ⭐⭐⭐⭐⭐ |
|
||||
| **可复用性** | ⭐⭐ | ⭐⭐⭐⭐⭐ |
|
||||
| **代码清晰度** | ⭐⭐ | ⭐⭐⭐⭐⭐ |
|
||||
| **学习曲线** | 陡峭(需要理解整个文件) | 平缓(可逐个模块学习) |
|
||||
| **性能** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
|
||||
|
||||
## 十、模块化代码的优势
|
||||
|
||||
1. **职责分离**:每个模块只负责一个功能领域
|
||||
2. **易于扩展**:新增功能只需添加新模块或扩展现有模块
|
||||
3. **便于协作**:多人可同时修改不同模块,减少冲突
|
||||
4. **代码复用**:公共函数可在多个模块间共享
|
||||
5. **测试友好**:每个模块可独立编写测试用例
|
||||
6. **文档清晰**:每个模块都有明确的文档说明
|
||||
|
||||
## 十一、迁移建议
|
||||
|
||||
如果要从原始代码迁移到模块化代码:
|
||||
|
||||
1. **保持接口兼容**:`fudai_analyse` 类的公共接口保持不变
|
||||
2. **逐步迁移**:可以逐个功能模块迁移,不需要一次性全部迁移
|
||||
3. **测试验证**:迁移后通过实际运行验证功能正确性
|
||||
4. **文档更新**:更新相关文档说明新的模块结构
|
||||
|
||||
Reference in new issue
Block a user