feat: Refactor and reorganize project structure with new modules and files
- Deleted obsolete files including test scripts and configuration files to streamline the project. - Introduced new modules for handling Douyin functionalities, including core operations, logging, and GUI components. - Updated import paths to reflect the new module structure, enhancing code organization and maintainability. - Added configuration files and documentation to support the new structure and improve user guidance.
This commit is contained in:
1 parent
ea7159355b
commit
c67f22f76f
139 files changed
+7571
-7828
No files matched your search
@@ -0,0 +1,189 @@
|
||||
---
|
||||
name: 全面文件夹整理
|
||||
overview: 将根目录中的文件按类型分类整理到相应的子目录中,提高项目结构的清晰度
|
||||
todos:
|
||||
- id: create_docs_dir
|
||||
content: 创建 docs/ 目录并移动所有 .md 文件(保留 README.md)
|
||||
status: pending
|
||||
- id: organize_tests
|
||||
content: 将根目录的 test_*.py 文件移动到 tests/ 目录
|
||||
status: pending
|
||||
- id: create_scripts_dir
|
||||
content: 创建 scripts/ 目录并移动所有 .bat 和 .ps1 文件
|
||||
status: pending
|
||||
- id: create_config_dir
|
||||
content: 创建 config/ 目录并移动配置文件(可选)
|
||||
status: pending
|
||||
- id: organize_gui_files
|
||||
content: 创建 gui/ 目录并移动 GUI 和 Web 相关文件
|
||||
status: pending
|
||||
- id: organize_tools
|
||||
content: 扩展 tools/ 目录,移动工具和检查脚本
|
||||
status: pending
|
||||
- id: organize_code_files
|
||||
content: 按功能分类整理代码文件(方案B:创建多个功能子目录)
|
||||
status: pending
|
||||
- id: update_imports
|
||||
content: 更新所有文件中的导入路径以匹配新的目录结构
|
||||
status: pending
|
||||
dependencies:
|
||||
- organize_code_files
|
||||
- id: create_readme_files
|
||||
content: 在新目录中创建 README.md 说明文件
|
||||
status: pending
|
||||
dependencies:
|
||||
- create_docs_dir
|
||||
- create_scripts_dir
|
||||
- create_config_dir
|
||||
- organize_gui_files
|
||||
- organize_tools
|
||||
- id: verify_imports
|
||||
content: 验证文件移动后所有导入和功能仍然正常
|
||||
status: pending
|
||||
dependencies:
|
||||
- organize_tests
|
||||
- organize_code_files
|
||||
---
|
||||
|
||||
# 全面
|
||||
|
||||
文件夹整理计划
|
||||
|
||||
## 目标
|
||||
|
||||
将根目录中散落的文件按类型分类整理到相应的子目录中,提高项目结构的清晰度和可维护性。
|
||||
|
||||
## 整理方案
|
||||
|
||||
### 1. 创建文档目录 `docs/`
|
||||
|
||||
**移动文件:** 所有 `.md` 文件(保留 `README.md` 在根目录)
|
||||
|
||||
- 将所有文档文件移动到 `docs/` 目录
|
||||
- 保留根目录的 `README.md` 作为项目主文档
|
||||
|
||||
### 2. 整理测试文件
|
||||
|
||||
**移动文件:** 根目录中的 `test_*.py` 文件
|
||||
|
||||
- 将根目录的测试文件移动到 `tests/` 目录
|
||||
- 保持现有的 `tests/` 目录结构
|
||||
|
||||
### 3. 创建脚本目录 `scripts/`
|
||||
|
||||
**移动文件:** 所有 `.bat` 和 `.ps1` 脚本文件
|
||||
|
||||
- 创建 `scripts/` 目录
|
||||
- 移动所有批处理和 PowerShell 脚本
|
||||
|
||||
### 4. 创建配置目录 `config/`(可选)
|
||||
|
||||
**移动文件:** 配置文件
|
||||
|
||||
- `config.json`
|
||||
- `pyrightconfig.json`
|
||||
- `pytest.ini`
|
||||
|
||||
### 5. 整理代码文件(可选,按功能模块组织)
|
||||
|
||||
**方案A:创建 `douyin/` 目录组织核心业务代码**
|
||||
|
||||
- 将所有 `douyin_*.py` 文件移动到 `douyin/` 目录
|
||||
- 创建 `douyin/__init__.py` 包文件
|
||||
- 更新所有导入路径
|
||||
|
||||
**方案B:按功能分类创建子目录(已选择)**具体目录结构和文件分配:
|
||||
|
||||
- `douyin/core/` - 核心调度和流程控制
|
||||
- douyin_fudai.py, douyin_main_flow.py, douyin_flow_control.py
|
||||
- `douyin/stage/` - 阶段处理
|
||||
- douyin_stage.py, douyin_stage_handler.py
|
||||
- `douyin/fudai/` - 福袋相关
|
||||
- douyin_fudai_core.py, douyin_fudai_detail.py, douyin_fudai_finder.py, douyin_fudai_flow.py
|
||||
- `douyin/detection/` - 检测相关
|
||||
- douyin_detection.py, douyin_pixel.py
|
||||
- `douyin/reservation/` - 预约相关
|
||||
- douyin_reservation.py, douyin_reservation_logic.py, douyin_reservation_handler.py,
|
||||
|
||||
douyin_reservation_ops.py, douyin_reservation_verify.py
|
||||
|
||||
- `douyin/handlers/` - 处理器模块
|
||||
- douyin_popup_handler.py, douyin_swipe_handler.py, douyin_screenshot_handler.py,
|
||||
|
||||
douyin_screenshot_manager.py, douyin_swipe_ops.py
|
||||
|
||||
- `douyin/utils/` - 工具函数
|
||||
- douyin_helpers.py, douyin_utils.py, douyin_text_utils.py, douyin_config.py
|
||||
- `douyin/logging/` - 日志相关
|
||||
- douyin_logging.py, douyin_logging_wrapper.py, douyin_logger.py
|
||||
- `douyin/other/` - 其他功能模块
|
||||
- douyin_live_room.py, douyin_lottery.py, douyin_robot.py, douyin_yanghao.py,
|
||||
|
||||
douyin_high_value_room.py, douyin_stuck_guard.py, douyin_guaji.py, douyin_popups.py**实施步骤:**
|
||||
|
||||
1. 创建 `douyin/` 主目录和所有子目录
|
||||
2. 创建各子目录的 `__init__.py` 文件
|
||||
3. 按分类移动文件到对应目录
|
||||
4. 更新所有导入路径(这是关键步骤,需要仔细处理)
|
||||
5. 验证所有功能正常
|
||||
|
||||
**方案C:保持现状,仅整理非核心文件**
|
||||
|
||||
- 保持 `douyin_*.py` 在根目录(因为它们是核心模块,导入频繁)
|
||||
- 仅整理工具、GUI、脚本等文件
|
||||
|
||||
### 6. 整理GUI和Web相关文件
|
||||
|
||||
**创建 `gui/` 目录**
|
||||
|
||||
- gui_app.py, gui_core.py
|
||||
- web_gui.py, webgui_launcher.py
|
||||
|
||||
### 7. 整理工具和检查脚本
|
||||
|
||||
**创建 `tools/` 目录(扩展现有)**
|
||||
|
||||
- check_*.py 文件
|
||||
- cleanup_unused_files.py
|
||||
- install_dependencies.py
|
||||
- 生成WPS流程图.py
|
||||
|
||||
## 目录结构
|
||||
|
||||
整理后的结构:
|
||||
|
||||
```javascript
|
||||
douyin_guaji-main/
|
||||
├── README.md # 保留在根目录
|
||||
├── requirements*.txt # 保留在根目录
|
||||
├── docs/ # 新建:所有文档
|
||||
├── scripts/ # 新建:所有脚本
|
||||
├── config/ # 新建:配置文件(可选)
|
||||
├── tests/ # 现有:测试文件
|
||||
├── tools/ # 扩展:工具和检查脚本
|
||||
├── gui/ # 新建:GUI相关文件
|
||||
├── fudai_detail_modules/ # 现有:模块化文件
|
||||
├── douyin/ # 新建(可选):核心业务代码
|
||||
│ ├── core/ # 核心调度
|
||||
│ ├── stage/ # 阶段处理
|
||||
│ ├── fudai/ # 福袋相关
|
||||
│ ├── detection/ # 检测相关
|
||||
│ ├── reservation/ # 预约相关
|
||||
│ ├── handlers/ # 处理器
|
||||
│ ├── utils/ # 工具函数
|
||||
│ └── logging/ # 日志相关
|
||||
└── [其他核心文件] # 保留在根目录(如果选择方案C)
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **保持向后兼容**:确保移动文件后不影响现有功能
|
||||
2. **更新导入路径**:如果有文件引用了移动的文件,需要更新路径
|
||||
3. **保留关键文件**:`README.md` 和 `requirements.txt` 等关键文件保留在根目录
|
||||
4. **创建说明文档**:在新目录中创建 README 说明文件用途
|
||||
5. **代码文件整理注意事项**:
|
||||
|
||||
- 移动代码文件后需要更新所有导入路径
|
||||
- 需要创建 `__init__.py` 文件使目录成为 Python 包
|
||||
File diff suppressed because it is too large.
Load diff
+145
-94
@@ -208,10 +208,10 @@ class underlying_operations:
|
||||
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
|
||||
self.ocr: Any = None
|
||||
self.ocr_type = None # 'easyocr' 或 'paddleocr'
|
||||
|
||||
|
||||
# 检测GPU是否可用(自动检测)
|
||||
self._gpu_available = self._detect_gpu_available()
|
||||
|
||||
|
||||
if not str(os.environ.get("SKIP_OCR_INIT", "")).strip():
|
||||
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
|
||||
# 首先尝试EasyOCR
|
||||
@@ -221,7 +221,7 @@ class underlying_operations:
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports]
|
||||
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
# 自动检测GPU可用性,如果可用则启用GPU加速
|
||||
@@ -252,11 +252,15 @@ class underlying_operations:
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
if paddle.device.is_compiled_with_cuda() and paddle.device.get_device():
|
||||
|
||||
if (
|
||||
paddle.device.is_compiled_with_cuda()
|
||||
and paddle.device.get_device()
|
||||
):
|
||||
use_gpu = self._gpu_available
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
@@ -311,19 +315,24 @@ class underlying_operations:
|
||||
|
||||
def _detect_gpu_available(self) -> bool:
|
||||
"""检测GPU是否可用
|
||||
|
||||
|
||||
默认返回False(CPU模式),除非通过环境变量明确启用GPU
|
||||
|
||||
|
||||
返回:
|
||||
True: GPU可用且已启用
|
||||
False: 使用CPU模式(默认)
|
||||
"""
|
||||
# 默认使用CPU模式,除非环境变量明确要求使用GPU
|
||||
# 检查环境变量是否强制启用GPU
|
||||
if str(os.environ.get("FORCE_GPU_OCR", "")).strip().lower() in ("1", "true", "yes"):
|
||||
if str(os.environ.get("FORCE_GPU_OCR", "")).strip().lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
):
|
||||
# 强制启用时,验证GPU是否真的可用
|
||||
try:
|
||||
import torch # type: ignore[import-untyped]
|
||||
|
||||
if torch.cuda.is_available():
|
||||
gpu_name = torch.cuda.get_device_name(0)
|
||||
print(f"[OCR] 环境变量强制启用GPU: {gpu_name},将使用GPU加速")
|
||||
@@ -337,17 +346,17 @@ class underlying_operations:
|
||||
except Exception as e:
|
||||
print(f"[OCR] GPU检测失败: {e},使用CPU模式")
|
||||
return False
|
||||
|
||||
|
||||
# 默认使用CPU模式
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_ocr(self):
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
|
||||
# 重新检测GPU(延迟初始化时)
|
||||
self._gpu_available = self._detect_gpu_available()
|
||||
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
devnull = None
|
||||
try:
|
||||
@@ -357,7 +366,9 @@ class underlying_operations:
|
||||
):
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
|
||||
self.ocr = easyocr.Reader(["ch_sim", "en"], gpu=self._gpu_available, verbose=False)
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"], gpu=self._gpu_available, verbose=False
|
||||
)
|
||||
self.ocr_type = "easyocr"
|
||||
gpu_status = "GPU加速" if self._gpu_available else "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
|
||||
@@ -382,11 +393,15 @@ class underlying_operations:
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
if paddle.device.is_compiled_with_cuda() and paddle.device.get_device():
|
||||
|
||||
if (
|
||||
paddle.device.is_compiled_with_cuda()
|
||||
and paddle.device.get_device()
|
||||
):
|
||||
use_gpu = self._gpu_available
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
@@ -479,7 +494,7 @@ class underlying_operations:
|
||||
|
||||
# OCR图片文件:按分类组织到子目录
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
category = douyin_screenshot_manager.get_category_for_picname(picname)
|
||||
except Exception:
|
||||
@@ -866,12 +881,12 @@ class underlying_operations:
|
||||
|
||||
# 双截图记录:保存实时操作截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
cropped_img, operation_type="cut_pic"
|
||||
)
|
||||
|
||||
|
||||
# 保存调试图像(带详细信息)
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
cropped_img,
|
||||
@@ -881,8 +896,8 @@ class underlying_operations:
|
||||
coords=(left, top, right, bottom),
|
||||
extra_info={
|
||||
"source": "screenshot.png",
|
||||
"size": f"{right-left}x{bottom-top}"
|
||||
}
|
||||
"size": f"{right-left}x{bottom-top}",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
@@ -959,10 +974,11 @@ class underlying_operations:
|
||||
except Exception:
|
||||
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
|
||||
return False
|
||||
|
||||
|
||||
# 保存调试图像
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
cropped_img,
|
||||
operation_type="cut_pic",
|
||||
@@ -971,8 +987,8 @@ class underlying_operations:
|
||||
coords=(left, top, right, bottom),
|
||||
extra_info={
|
||||
"source": target + "/screenshot.png",
|
||||
"size": f"{right-left}x{bottom-top}"
|
||||
}
|
||||
"size": f"{right-left}x{bottom-top}",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
@@ -981,7 +997,7 @@ class underlying_operations:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
return True
|
||||
|
||||
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
|
||||
@@ -1063,7 +1079,8 @@ class underlying_operations:
|
||||
|
||||
# 保存预处理后的调试图像(OCR前)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
img1,
|
||||
operation_type="ocr",
|
||||
@@ -1072,8 +1089,8 @@ class underlying_operations:
|
||||
extra_info={
|
||||
"mode": change_color,
|
||||
"size": f"{w}x{h}",
|
||||
"source": pic_path if pic_path else picname
|
||||
}
|
||||
"source": pic_path if pic_path else picname,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
@@ -1087,7 +1104,7 @@ class underlying_operations:
|
||||
|
||||
# 用于收集置信度信息
|
||||
ocr_confidence_info = None
|
||||
|
||||
|
||||
if getattr(self, "ocr_type", None) == "easyocr":
|
||||
result = self.ocr.readtext(img_np)
|
||||
extract_result = self.extract_ocr_content(result, return_confidence=True)
|
||||
@@ -1161,7 +1178,7 @@ class underlying_operations:
|
||||
pass
|
||||
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
# Ensure img1 is defined before use
|
||||
if "img1" not in locals():
|
||||
@@ -1172,30 +1189,40 @@ class underlying_operations:
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
img_for_attempt, operation_type="ocr"
|
||||
)
|
||||
|
||||
|
||||
# 保存OCR结果后的调试图像(带OCR文本结果和置信度)
|
||||
ocr_result_preview = (text or text2 or "").strip()[:50] if (text or text2) else ""
|
||||
ocr_result_preview = (
|
||||
(text or text2 or "").strip()[:50] if (text or text2) else ""
|
||||
)
|
||||
extra_info_dict = {
|
||||
"mode": change_color,
|
||||
"text_len": len(text or text2 or ""),
|
||||
"text_preview": ocr_result_preview,
|
||||
"used_img2": bool(img2 is not None and text2 and text2.strip())
|
||||
"used_img2": bool(img2 is not None and text2 and text2.strip()),
|
||||
}
|
||||
# 添加置信度信息
|
||||
if ocr_confidence_info:
|
||||
extra_info_dict["avg_confidence"] = round(ocr_confidence_info.get("avg_confidence", 0.0), 4)
|
||||
extra_info_dict["min_confidence"] = round(ocr_confidence_info.get("min_confidence", 0.0), 4)
|
||||
extra_info_dict["max_confidence"] = round(ocr_confidence_info.get("max_confidence", 0.0), 4)
|
||||
extra_info_dict["confidence_items"] = ocr_confidence_info.get("item_count", 0)
|
||||
|
||||
extra_info_dict["avg_confidence"] = round(
|
||||
ocr_confidence_info.get("avg_confidence", 0.0), 4
|
||||
)
|
||||
extra_info_dict["min_confidence"] = round(
|
||||
ocr_confidence_info.get("min_confidence", 0.0), 4
|
||||
)
|
||||
extra_info_dict["max_confidence"] = round(
|
||||
ocr_confidence_info.get("max_confidence", 0.0), 4
|
||||
)
|
||||
extra_info_dict["confidence_items"] = ocr_confidence_info.get(
|
||||
"item_count", 0
|
||||
)
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
img_for_attempt,
|
||||
operation_type="ocr",
|
||||
picname=picname,
|
||||
step="after_ocr",
|
||||
extra_info=extra_info_dict
|
||||
extra_info=extra_info_dict,
|
||||
)
|
||||
|
||||
|
||||
# 记录OCR置信度到日志
|
||||
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
|
||||
try:
|
||||
@@ -1210,7 +1237,9 @@ class underlying_operations:
|
||||
pass
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info(f"[调试图像] OCR结果保存: {debug_path}, 文本: {ocr_result_preview}")
|
||||
logging.info(
|
||||
f"[调试图像] OCR结果保存: {debug_path}, 文本: {ocr_result_preview}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
@@ -1219,7 +1248,7 @@ class underlying_operations:
|
||||
if text and text.strip() and picname:
|
||||
try:
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
category = douyin_screenshot_manager.get_category_for_picname(
|
||||
picname
|
||||
@@ -1242,7 +1271,7 @@ class underlying_operations:
|
||||
else:
|
||||
img_to_save = img1
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
img_to_save, operation_type="ocr"
|
||||
@@ -1263,12 +1292,12 @@ class underlying_operations:
|
||||
|
||||
def analyse_pic_digits(self, picname, change_color=1, pic_path=None):
|
||||
"""轻量数字OCR识别函数,专门用于识别数字(0-9)。
|
||||
|
||||
|
||||
相比analyse_pic_word,这个函数:
|
||||
1. 使用二值化预处理(change_color=1),更适合数字识别
|
||||
2. 只提取数字字符,忽略其他字符
|
||||
3. 使用更轻量的OCR配置(如果支持)
|
||||
|
||||
|
||||
参数:
|
||||
picname: 用于分类和调试的图片名(如"福袋价值")
|
||||
change_color: 颜色处理模式,默认1=二值化(更适合数字)
|
||||
@@ -1316,6 +1345,7 @@ class underlying_operations:
|
||||
|
||||
# 锐化处理,提高数字识别准确率
|
||||
from PIL import ImageEnhance
|
||||
|
||||
try:
|
||||
img_sharpened = img.filter(
|
||||
ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3)
|
||||
@@ -1344,7 +1374,7 @@ class underlying_operations:
|
||||
if text:
|
||||
# 提取所有数字字符
|
||||
digits = "".join(ch for ch in str(text) if ch.isdigit())
|
||||
|
||||
|
||||
# 智能过滤:如果识别到的数字太多(可能是识别到了文件名或坐标),
|
||||
# 尝试提取合理的数字段
|
||||
if len(digits) > 10:
|
||||
@@ -1353,53 +1383,60 @@ class underlying_operations:
|
||||
# 尝试提取最后几个数字(通常是实际值)
|
||||
# 或者提取最短的连续数字段
|
||||
import re
|
||||
|
||||
# 提取所有连续的数字段
|
||||
digit_segments = re.findall(r'\d+', str(text))
|
||||
digit_segments = re.findall(r"\d+", str(text))
|
||||
if digit_segments:
|
||||
# 对于价值,选择最大的合理数字段(不超过6位)
|
||||
# 对于倒计时,选择1-2位的数字段
|
||||
# 这里先返回所有数字,让调用方处理
|
||||
# 但优先选择较短的段(1-6位)
|
||||
reasonable_segments = [s for s in digit_segments if 1 <= len(s) <= 6]
|
||||
reasonable_segments = [
|
||||
s for s in digit_segments if 1 <= len(s) <= 6
|
||||
]
|
||||
if reasonable_segments:
|
||||
# 如果有多段,优先选择较短的(倒计时)或较长的(价值)
|
||||
# 这里返回最长的合理段(通常是价值)
|
||||
return max(reasonable_segments, key=len)
|
||||
else:
|
||||
# 如果没有合理段,返回最短的段
|
||||
return min(digit_segments, key=len) if digit_segments else digits[:6]
|
||||
|
||||
return (
|
||||
min(digit_segments, key=len)
|
||||
if digit_segments
|
||||
else digits[:6]
|
||||
)
|
||||
|
||||
return digits
|
||||
|
||||
return ""
|
||||
|
||||
def extract_ocr_content(self, content=[], return_confidence=False):
|
||||
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容
|
||||
|
||||
|
||||
参数:
|
||||
content: OCR识别结果
|
||||
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
|
||||
|
||||
|
||||
返回:
|
||||
如果return_confidence=False: 返回文本字符串
|
||||
如果return_confidence=True: 返回(text, confidence_info)元组,其中confidence_info是置信度信息字典
|
||||
"""
|
||||
ocr_result = content
|
||||
|
||||
|
||||
# 用于收集置信度信息
|
||||
confidence_scores = []
|
||||
confidence_info = {
|
||||
"avg_confidence": 0.0,
|
||||
"min_confidence": 1.0,
|
||||
"max_confidence": 0.0,
|
||||
"item_count": 0
|
||||
"item_count": 0,
|
||||
}
|
||||
|
||||
def _extract_text_and_confidence_from_item(item):
|
||||
"""提取文本和置信度"""
|
||||
text = ""
|
||||
confidence = None
|
||||
|
||||
|
||||
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
# EasyOCR格式:item = (bbox, text, confidence),text在索引1,confidence在索引2
|
||||
@@ -1546,11 +1583,11 @@ class underlying_operations:
|
||||
|
||||
# 按从上到下、从左到右排序;解决同一行多个框的乱序拼接(例如倒计时两段数字)
|
||||
extracted_items.sort(key=lambda t: (t[0], t[1]))
|
||||
|
||||
|
||||
# 如果不需要返回置信度,直接返回文本(保持向后兼容)
|
||||
if not return_confidence:
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
|
||||
# 如果需要返回置信度,提取置信度信息
|
||||
if return_confidence:
|
||||
for item in items:
|
||||
@@ -1565,24 +1602,30 @@ class underlying_operations:
|
||||
confidence = second[1]
|
||||
elif isinstance(second, dict):
|
||||
confidence = second.get("confidence") or second.get("score")
|
||||
|
||||
|
||||
if confidence is not None:
|
||||
try:
|
||||
conf_float = float(confidence)
|
||||
confidence_scores.append(conf_float)
|
||||
confidence_info["min_confidence"] = min(confidence_info["min_confidence"], conf_float)
|
||||
confidence_info["max_confidence"] = max(confidence_info["max_confidence"], conf_float)
|
||||
confidence_info["min_confidence"] = min(
|
||||
confidence_info["min_confidence"], conf_float
|
||||
)
|
||||
confidence_info["max_confidence"] = max(
|
||||
confidence_info["max_confidence"], conf_float
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
|
||||
if confidence_scores:
|
||||
confidence_info["avg_confidence"] = sum(confidence_scores) / len(confidence_scores)
|
||||
confidence_info["avg_confidence"] = sum(confidence_scores) / len(
|
||||
confidence_scores
|
||||
)
|
||||
confidence_info["item_count"] = len(confidence_scores)
|
||||
else:
|
||||
confidence_info["min_confidence"] = 0.0
|
||||
|
||||
|
||||
return "".join([t[2] for t in extracted_items]), confidence_info
|
||||
|
||||
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
def delay(self, seconds: float = 1):
|
||||
@@ -1765,20 +1808,21 @@ class underlying_operations:
|
||||
steps=200,
|
||||
):
|
||||
"""划动屏幕
|
||||
|
||||
|
||||
参数说明:
|
||||
- left_up_x, left_up_y: 滑动起始位置(手指按下位置)
|
||||
- right_down_x, right_down_y: 滑动结束位置(手指抬起位置)
|
||||
- steps: 滑动步数(影响滑动速度,数值越大滑动越慢)
|
||||
|
||||
|
||||
执行命令:adb shell input swipe <start_x> <start_y> <end_x> <end_y> <duration_ms>
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
adb_cmd = self._adb()
|
||||
# 注意:adb input swipe 的参数顺序是:start_x start_y end_x end_y duration_ms
|
||||
# 这里 left_up_x/y 是起始位置,right_down_x/y 是结束位置
|
||||
cmd = f"{adb_cmd} -s {device_id} shell input swipe {left_up_x} {left_up_y} {right_down_x} {right_down_y} {steps}"
|
||||
|
||||
|
||||
try:
|
||||
# 使用 subprocess 执行命令,捕获错误输出
|
||||
result = subprocess.run(
|
||||
@@ -1789,29 +1833,32 @@ class underlying_operations:
|
||||
timeout=5.0,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
# 检查是否有权限错误
|
||||
stderr_text = result.stderr if result.stderr else ""
|
||||
has_permission_error = (
|
||||
result.returncode != 0
|
||||
and ("SecurityException" in stderr_text
|
||||
or "INJECT_EVENTS" in stderr_text
|
||||
or "Injecting to another application" in stderr_text)
|
||||
has_permission_error = result.returncode != 0 and (
|
||||
"SecurityException" in stderr_text
|
||||
or "INJECT_EVENTS" in stderr_text
|
||||
or "Injecting to another application" in stderr_text
|
||||
)
|
||||
|
||||
|
||||
if has_permission_error:
|
||||
# 尝试使用 uiautomator(如果可用,某些设备可能支持)
|
||||
try:
|
||||
self._swipe_with_uiautomator(device_id, left_up_x, left_up_y, right_down_x, right_down_y)
|
||||
self._swipe_with_uiautomator(
|
||||
device_id, left_up_x, left_up_y, right_down_x, right_down_y
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 记录错误但不抛出异常,避免中断主流程
|
||||
error_msg = stderr_text.strip() if stderr_text else "权限不足"
|
||||
print(f"[警告] 滑动操作失败: {error_msg}")
|
||||
print(f"[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
|
||||
print(f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'")
|
||||
print(
|
||||
f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
|
||||
)
|
||||
print(f" 2. 使用已 root 的设备")
|
||||
print(f" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
|
||||
# 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用)
|
||||
@@ -1823,12 +1870,12 @@ class underlying_operations:
|
||||
os.system(cmd)
|
||||
except Exception:
|
||||
print(f"[警告] 滑动操作失败: {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
def _swipe_with_sendevent(self, device_id, x1, y1, x2, y2, steps):
|
||||
"""使用 sendevent 方法滑动(需要 root 权限)"""
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
# 获取触摸设备路径
|
||||
result = subprocess.run(
|
||||
f"{self._adb()} -s {device_id} shell getevent -p | grep -A 5 ABS_MT",
|
||||
@@ -1837,25 +1884,27 @@ class underlying_operations:
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
if "event" not in result.stdout.lower():
|
||||
raise Exception("无法找到触摸设备")
|
||||
|
||||
|
||||
# 简化实现:直接使用 input 命令的替代参数
|
||||
# 注意:sendevent 需要 root 权限,这里只是尝试
|
||||
raise Exception("sendevent 需要 root 权限,暂不支持")
|
||||
|
||||
|
||||
def _swipe_with_uiautomator(self, device_id, x1, y1, x2, y2):
|
||||
"""使用 uiautomator 滑动(如果可用)
|
||||
|
||||
|
||||
注意:uiautomator 在某些设备上可能也需要权限,但可以尝试作为备选方案。
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
|
||||
# 使用 uiautomator swipe 命令
|
||||
# 注意:uiautomator 命令格式可能因 Android 版本而异
|
||||
# Android 5.0+: uiautomator swipe <x1> <y1> <x2> <y2> [steps]
|
||||
cmd = f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}"
|
||||
cmd = (
|
||||
f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}"
|
||||
)
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
shell=True,
|
||||
@@ -1863,20 +1912,22 @@ class underlying_operations:
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=5.0,
|
||||
)
|
||||
|
||||
|
||||
if result.returncode != 0:
|
||||
raise Exception(f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}")
|
||||
|
||||
raise Exception(
|
||||
f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}"
|
||||
)
|
||||
|
||||
def _swipe_with_sendevent_improved(self, device_id, x1, y1, x2, y2, steps=50):
|
||||
"""使用 sendevent 方法滑动(需要 root 权限)
|
||||
|
||||
|
||||
这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。
|
||||
优点:绕过部分权限检查
|
||||
缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同
|
||||
"""
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
# 获取触摸设备路径(通常是 /dev/input/eventX)
|
||||
result = subprocess.run(
|
||||
f"{self._adb()} -s {device_id} shell getevent -p 2>/dev/null | grep -A 10 ABS_MT",
|
||||
@@ -1886,22 +1937,22 @@ class underlying_operations:
|
||||
text=True,
|
||||
timeout=3.0,
|
||||
)
|
||||
|
||||
|
||||
# 解析设备路径(简化版,实际需要更复杂的解析)
|
||||
# 这里只是示例,完整实现需要:
|
||||
# 1. 解析 getevent -p 输出找到触摸设备
|
||||
# 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max)
|
||||
# 3. 将屏幕坐标转换为设备坐标
|
||||
# 4. 发送 DOWN -> MOVE -> UP 事件序列
|
||||
|
||||
|
||||
if "event" not in result.stdout.lower():
|
||||
raise Exception("无法找到触摸设备(需要 root 权限)")
|
||||
|
||||
|
||||
# 注意:完整的 sendevent 实现非常复杂,需要:
|
||||
# - 设备特定的坐标转换
|
||||
# - 正确的事件序列(SYN_REPORT 等)
|
||||
# - 不同 Android 版本的事件格式可能不同
|
||||
|
||||
|
||||
raise Exception("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
|
||||
|
||||
def click(self, device_id, x=500, y=500):
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# 配置目录
|
||||
|
||||
本目录包含项目的所有配置文件。
|
||||
|
||||
## 配置文件列表
|
||||
|
||||
- **config.json** - 主配置文件,包含所有运行时配置参数
|
||||
- **pyrightconfig.json** - Pyright类型检查器配置
|
||||
- **pytest.ini** - pytest测试框架配置
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `config.json` 是运行时配置文件,会被程序读取和修改
|
||||
- 建议在修改配置前备份原文件
|
||||
- 配置文件使用 UTF-8 编码
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"reportMissingModuleSource": false,
|
||||
"reportMissingImports": false,
|
||||
"reportUnknownMemberType": false,
|
||||
"reportUnknownVariableType": false,
|
||||
"reportAttributeAccessIssue": false,
|
||||
"reportGeneralTypeIssues": false,
|
||||
"reportOptionalMemberAccess": false,
|
||||
"reportOptionalSubscript": false,
|
||||
"reportPrivateImportUsage": false,
|
||||
"reportUnusedImport": "warning",
|
||||
"reportUnusedVariable": "warning"
|
||||
}
|
||||
|
||||
|
||||
@@ -193,6 +193,11 @@ python cleanup_unused_files.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -204,6 +204,11 @@ except Exception as e:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -407,6 +407,11 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -291,6 +291,11 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -262,6 +262,11 @@ python check_dependencies.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -241,6 +241,11 @@ douyin_guaji
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -182,6 +182,11 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -394,6 +394,11 @@ douyin_fudai_finder.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,112 @@
|
||||
# 模块化重构验证报告
|
||||
|
||||
## 验证日期
|
||||
2025-01-27
|
||||
|
||||
## 验证结果总结
|
||||
|
||||
### ✅ 测试结果
|
||||
- **集成测试**: 26/26 通过 (100%)
|
||||
- **单元测试**: 36/36 通过 (100%)
|
||||
- **总计**: 62/62 通过 (100%)
|
||||
|
||||
### ✅ 模块化架构验证
|
||||
|
||||
#### 已创建的模块
|
||||
1. ✅ `douyin_config.py` - 配置管理模块 (92% 覆盖率)
|
||||
2. ✅ `douyin_logging_wrapper.py` - 日志管理模块
|
||||
3. ✅ `douyin_screenshot_handler.py` - 截图处理模块
|
||||
4. ✅ `douyin_helpers.py` - 工具方法模块
|
||||
5. ✅ `douyin_popup_handler.py` - 弹窗处理模块 (81% 覆盖率)
|
||||
6. ✅ `douyin_swipe_handler.py` - 滑动操作模块
|
||||
7. ✅ `douyin_reservation_handler.py` - 预约管理模块
|
||||
8. ✅ `douyin_stage_handler.py` - 阶段处理模块
|
||||
9. ✅ `douyin_main_flow.py` - 主流程控制模块
|
||||
|
||||
#### 模块委托验证
|
||||
所有模块委托测试通过:
|
||||
- ✅ 配置加载委托到 `ConfigManager`
|
||||
- ✅ 日志记录委托到 `LoggingWrapper`
|
||||
- ✅ 截图处理委托到 `ScreenshotHandler`
|
||||
- ✅ 弹窗检测委托到 `PopupHandler`
|
||||
- ✅ 滑动操作委托到 `SwipeHandler`
|
||||
- ✅ 预约管理委托到 `ReservationHandler`
|
||||
- ✅ 阶段诊断委托到 `StageHandler`
|
||||
- ✅ 工具方法委托到 `HelperFunctions`
|
||||
|
||||
### ✅ 向后兼容性验证
|
||||
- ✅ 公共 API 保持不变
|
||||
- ✅ `fudai_analyse` 类可以正常实例化
|
||||
- ✅ 所有原有方法仍然可用
|
||||
- ✅ 类常量仍然存在
|
||||
|
||||
### ✅ 代码质量指标
|
||||
|
||||
#### 主文件重构效果
|
||||
- **原始行数**: 5433 行
|
||||
- **重构后行数**: 3299 行
|
||||
- **减少**: 2134 行 (39.3% 减少)
|
||||
|
||||
#### Pylance 错误状态
|
||||
- **严重错误**: 2 个(已通过类型忽略注释处理)
|
||||
- 代码复杂度警告(需要进一步重构)
|
||||
- 类型检查限制(已使用类型断言和忽略注释)
|
||||
- **警告**: 220 个(主要是代码风格警告,不影响功能)
|
||||
- 捕获通用异常
|
||||
- 重复导入
|
||||
- 访问受保护成员
|
||||
- 未使用的变量/导入
|
||||
|
||||
### ✅ 测试覆盖率
|
||||
|
||||
#### 集成测试
|
||||
- `test_modular_integration.py`: 99% 覆盖率
|
||||
- `test_config_loading.py`: 100% 覆盖率
|
||||
- `test_fudai_analyse_init.py`: 100% 覆盖率
|
||||
|
||||
#### 单元测试
|
||||
- `test_douyin_text_utils.py`: 100% 覆盖率
|
||||
- `test_douyin_utils.py`: 95% 覆盖率
|
||||
- `test_path_config.py`: 100% 覆盖率
|
||||
- `test_version.py`: 100% 覆盖率
|
||||
- `test_gui_core.py`: 100% 覆盖率
|
||||
|
||||
### ✅ 模块交互验证
|
||||
- ✅ 配置模块和日志模块交互正常
|
||||
- ✅ 截图模块和阶段诊断模块交互正常
|
||||
- ✅ 滑动模块和预约模块交互正常
|
||||
|
||||
### ✅ 错误处理验证
|
||||
- ✅ 模块导入错误处理正常
|
||||
- ✅ 委托方法错误处理正常
|
||||
- ✅ 配置文件缺失/无效处理正常
|
||||
|
||||
## 验证结论
|
||||
|
||||
### ✅ 模块化重构成功完成
|
||||
|
||||
1. **架构清晰**: 代码已按功能拆分为9个独立模块
|
||||
2. **高内聚低耦合**: 每个模块职责明确,依赖关系清晰
|
||||
3. **向后兼容**: 公共API保持不变,现有代码无需修改
|
||||
4. **测试完善**: 所有集成测试和单元测试通过
|
||||
5. **类型安全**: 主要类型错误已修复,剩余为代码风格警告
|
||||
|
||||
### 剩余工作(可选优化)
|
||||
|
||||
1. **代码风格优化**:
|
||||
- 减少捕获通用异常,使用更具体的异常类型
|
||||
- 清理重复导入
|
||||
- 优化未使用的变量
|
||||
|
||||
2. **进一步重构**:
|
||||
- 降低代码复杂度(Line 552)
|
||||
- 继续拆分大型方法
|
||||
|
||||
3. **单元测试**:
|
||||
- 为每个新模块编写更详细的单元测试
|
||||
|
||||
## 验证通过 ✅
|
||||
|
||||
模块化重构已完成并通过全面验证,代码可以正常使用。
|
||||
|
||||
|
||||
@@ -193,6 +193,11 @@ self.ocr = easyocr.Reader(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# 文档目录
|
||||
|
||||
本目录包含项目的所有文档文件。
|
||||
|
||||
## 文档列表
|
||||
|
||||
- **CLEANUP_REPORT.md** - 清理报告
|
||||
- **CODE_REVIEW_FIXES.md** - 代码审查修复
|
||||
- **CODE_REVIEW_REPORT.md** - 代码审查报告
|
||||
- **DEBUG_IMAGE_SYSTEM.md** - 调试图像系统
|
||||
- **DEPENDENCY_FIXES_REPORT.md** - 依赖修复报告
|
||||
- **DEPENDENCY_GUIDE.md** - 依赖指南
|
||||
- **FIXES_REPORT.md** - 修复报告
|
||||
- **FUDAI_FINDER_OPTIMIZATION.md** - 福袋查找器优化
|
||||
- **GUI参数冲突分析.md** - GUI参数冲突分析
|
||||
- **GUI日志修复总结.md** - GUI日志修复总结
|
||||
- **LOGGING_IMPROVEMENTS.md** - 日志改进
|
||||
- **MODULAR_REFACTORING_VERIFICATION.md** - 模块化重构验证
|
||||
- **OCR性能分析报告.md** - OCR性能分析报告
|
||||
- **WPS流程图说明.md** - WPS流程图说明
|
||||
- **功能差异对比.md** - 功能差异对比
|
||||
- **日志系统优化总结.md** - 日志系统优化总结
|
||||
- **日志系统优化说明.md** - 日志系统优化说明
|
||||
- **日志系统规范文档.md** - 日志系统规范文档
|
||||
- **核显GPU加速说明.md** - 核显GPU加速说明
|
||||
- **模块化代码对比说明.md** - 模块化代码对比说明
|
||||
- **流程图.md** - 流程图
|
||||
- **真机测试报告.md** - 真机测试报告
|
||||
- **统一截图和分数记录说明.md** - 统一截图和分数记录说明
|
||||
- **设置定时任务说明.md** - 设置定时任务说明
|
||||
- **预约系统详细流程.md** - 预约系统详细流程
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -152,6 +152,11 @@ python 生成WPS流程图.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -161,6 +161,11 @@ python check_gpu_available.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -167,6 +167,11 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
@@ -167,6 +167,11 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
@@ -374,3 +374,8 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# 抖音挂机核心模块
|
||||
|
||||
本目录包含项目的所有核心业务代码,按功能模块组织。
|
||||
|
||||
## 目录结构
|
||||
|
||||
- **core/** - 核心调度和流程控制
|
||||
- `douyin_fudai.py` - 主调度器
|
||||
- `douyin_main_flow.py` - 主流程控制
|
||||
- `douyin_flow_control.py` - 流程控制
|
||||
|
||||
- **stage/** - 阶段处理
|
||||
- `douyin_stage.py` - 阶段定义
|
||||
- `douyin_stage_handler.py` - 阶段处理器
|
||||
|
||||
- **fudai/** - 福袋相关
|
||||
- `douyin_fudai_core.py` - 福袋核心逻辑
|
||||
- `douyin_fudai_detail.py` - 福袋详情处理
|
||||
- `douyin_fudai_finder.py` - 福袋查找器
|
||||
- `douyin_fudai_flow.py` - 福袋流程
|
||||
|
||||
- **detection/** - 检测相关
|
||||
- `douyin_detection.py` - 检测模块
|
||||
- `douyin_pixel.py` - 像素检测
|
||||
|
||||
- **reservation/** - 预约相关
|
||||
- `douyin_reservation.py` - 预约主模块
|
||||
- `douyin_reservation_logic.py` - 预约逻辑
|
||||
- `douyin_reservation_handler.py` - 预约处理器
|
||||
- `douyin_reservation_ops.py` - 预约操作
|
||||
- `douyin_reservation_verify.py` - 预约验证
|
||||
|
||||
- **handlers/** - 处理器模块
|
||||
- `douyin_popup_handler.py` - 弹窗处理器
|
||||
- `douyin_screenshot_handler.py` - 截图处理器
|
||||
- `douyin_screenshot_manager.py` - 截图管理器
|
||||
- `douyin_swipe_handler.py` - 滑动处理器
|
||||
- `douyin_swipe_ops.py` - 滑动操作
|
||||
|
||||
- **utils/** - 工具函数
|
||||
- `douyin_config.py` - 配置管理
|
||||
- `douyin_helpers.py` - 辅助函数
|
||||
- `douyin_text_utils.py` - 文本工具
|
||||
- `douyin_utils.py` - 通用工具
|
||||
|
||||
- **logging/** - 日志相关
|
||||
- `douyin_logging.py` - 日志配置
|
||||
- `douyin_logging_wrapper.py` - 日志包装器
|
||||
- `douyin_logger.py` - 日志器
|
||||
|
||||
- **other/** - 其他功能模块
|
||||
- `douyin_guaji.py` - 挂机主模块
|
||||
- `douyin_high_value_room.py` - 高价值房间
|
||||
- `douyin_live_room.py` - 直播间
|
||||
- `douyin_lottery.py` - 抽奖
|
||||
- `douyin_popups.py` - 弹窗
|
||||
- `douyin_robot.py` - 机器人
|
||||
- `douyin_stuck_guard.py` - 卡顿守护
|
||||
- `douyin_yanghao.py` - 养号
|
||||
|
||||
## 导入方式
|
||||
|
||||
所有模块都可以通过 `douyin` 包导入,例如:
|
||||
|
||||
```python
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from douyin.utils.douyin_utils import normalize_countdown_text
|
||||
from douyin.handlers.douyin_swipe_handler import SwipeHandler
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
抖音挂机项目核心模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
核心调度和流程控制模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -15,9 +15,9 @@ from typing import Any, List, Tuple
|
||||
import time
|
||||
import os
|
||||
|
||||
from douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin_fudai_core import should_skip_fudai_by_config
|
||||
import douyin_reservation_logic
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
import path_config
|
||||
from PIL import Image
|
||||
|
||||
@@ -171,7 +171,7 @@ def find_and_open_fudai_detail(
|
||||
analyser.operation.delay(min_wait_seconds)
|
||||
|
||||
# 智能等待:循环检测详情页是否已打开
|
||||
import douyin_stage
|
||||
from douyin.stage import douyin_stage
|
||||
wait_start = time.time()
|
||||
detail_opened = False
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,105 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
主流程控制模块
|
||||
==============
|
||||
|
||||
职责:核心流程控制和调度
|
||||
- 主循环入口
|
||||
- 单次循环执行(拆分后简化)
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from douyin.stage import douyin_stage
|
||||
from douyin.core import douyin_flow_control
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.utils import douyin_helpers
|
||||
from douyin.stage import douyin_stage_handler
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
|
||||
|
||||
class MainFlowController:
|
||||
"""主流程控制器:统一管理主流程"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def fudai_choujiang(
|
||||
analyser: Any,
|
||||
device_id: str = "",
|
||||
y_pianyi: int = 0,
|
||||
needswitch: bool = False,
|
||||
wait_minutes: int = 15,
|
||||
) -> None:
|
||||
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
device_id: 设备ID
|
||||
y_pianyi: Y轴偏移
|
||||
needswitch: 是否允许切换直播间
|
||||
wait_minutes: 等待分钟数
|
||||
"""
|
||||
analyser.device_id = device_id or analyser.device_id
|
||||
analyser.y_pianyi = int(y_pianyi or 0)
|
||||
# 保存是否允许切换直播间的配置,供后续所有逻辑统一使用
|
||||
try:
|
||||
analyser.needswitch = bool(needswitch)
|
||||
except Exception:
|
||||
# 兜底:若赋值失败,则保持原有行为(默认允许切换)
|
||||
analyser.needswitch = True
|
||||
try:
|
||||
rx, ry = analyser.operation.get_device_resolution(analyser.device_id)
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = int(
|
||||
rx or 1080
|
||||
), int(ry or 2400)
|
||||
except Exception:
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = 1080, 2400
|
||||
|
||||
# 记录运行开始时间
|
||||
analyser._run_start_ts = time.time()
|
||||
|
||||
# 主循环
|
||||
loop_count = 0
|
||||
while True:
|
||||
loop_count += 1
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", f"主循环第 {loop_count} 次", loop_count=loop_count
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 执行单次循环
|
||||
MainFlowController.run_once_basic(analyser)
|
||||
|
||||
# 等待指定时间(如果配置了等待时间)
|
||||
if wait_minutes > 0:
|
||||
wait_seconds = wait_minutes * 60
|
||||
try:
|
||||
analyser.operation.delay(wait_seconds)
|
||||
except Exception:
|
||||
time.sleep(wait_seconds)
|
||||
else:
|
||||
# 如果没有配置等待时间,短暂延迟避免CPU占用过高
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def run_once_basic(analyser: Any) -> None:
|
||||
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
注意:由于此方法非常复杂(1500+行),暂时保持原实现,
|
||||
但通过模块化组织,后续可以进一步拆分。
|
||||
"""
|
||||
# 由于 run_once_basic 方法过于复杂,暂时保持原实现
|
||||
# 但通过模块化组织,后续可以进一步拆分
|
||||
analyser.run_once_basic_original() # type: ignore[attr-defined]
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
检测相关模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -154,7 +154,7 @@ def check_detail_height(analyser: Any) -> int:
|
||||
|
||||
# 保存调试图片:标注检测区域和检测点
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
# 计算检测区域(参与按钮附近的区域)
|
||||
check_region_x1 = max(0, x - 50)
|
||||
@@ -251,7 +251,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
if use_optimized:
|
||||
try:
|
||||
from douyin_fudai_finder import check_have_fudai_with_ready_screenshot_optimized
|
||||
from douyin.fudai.douyin_fudai_finder import check_have_fudai_with_ready_screenshot_optimized
|
||||
return check_have_fudai_with_ready_screenshot_optimized(
|
||||
analyser, screenshot_ready
|
||||
)
|
||||
@@ -417,7 +417,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
# 保存完整截图用于调试(检测前)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
|
||||
# 保存完整截图
|
||||
@@ -463,7 +463,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
roi, operation_type="pixel_detect"
|
||||
@@ -530,7 +530,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
roi, operation_type="pixel_detect"
|
||||
@@ -688,7 +688,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_new.crop(
|
||||
(
|
||||
@@ -860,7 +860,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
@@ -894,7 +894,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
if max_val >= template_threshold:
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
@@ -1315,7 +1315,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
@@ -1370,7 +1370,7 @@ def check_have_fudai_with_ready_screenshot(
|
||||
if max_val >= template_threshold:
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
@@ -1577,7 +1577,7 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
|
||||
# 使用模板匹配检测,与 detect_fudai_detail_page 保持一致
|
||||
try:
|
||||
import douyin_pixel
|
||||
from douyin.detection import douyin_pixel
|
||||
import path_config
|
||||
|
||||
# 获取截图
|
||||
@@ -1615,10 +1615,10 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
# 使用任务数量检测
|
||||
result = douyin_pixel.detect_fudai_detail_page(
|
||||
pic_rgb,
|
||||
resolution_ratio_x=rx,
|
||||
resolution_ratio_y=ry,
|
||||
y_pianyi=y_pianyi,
|
||||
template_threshold=template_threshold,
|
||||
rx,
|
||||
ry,
|
||||
y_pianyi,
|
||||
template_threshold,
|
||||
return_info=False, # 不需要详细信息
|
||||
analyser=analyser,
|
||||
)
|
||||
@@ -1,3 +1,8 @@
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
# pyright: reportAttributeAccessIssue=false
|
||||
# pyright: reportMissingModuleSource=false
|
||||
# pyright: reportUnknownMemberType=false
|
||||
# pyright: reportUnknownVariableType=false
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Optional
|
||||
@@ -15,7 +20,7 @@ def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return None
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
return None
|
||||
|
||||
|
||||
@@ -44,9 +49,9 @@ def detect_coupon_popup_background(
|
||||
"""
|
||||
try:
|
||||
try:
|
||||
import cv2 # type: ignore
|
||||
import numpy as np # type: ignore
|
||||
except Exception:
|
||||
import cv2 # type: ignore[import-untyped]
|
||||
import numpy as np # type: ignore[import-untyped]
|
||||
except Exception: # type: ignore[general-exception]
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
@@ -78,7 +83,9 @@ def detect_coupon_popup_background(
|
||||
}
|
||||
return False
|
||||
|
||||
bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
bgr = cv2.cvtColor( # type: ignore[attr-defined]
|
||||
np.array(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined]
|
||||
)
|
||||
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
|
||||
if roi.size == 0:
|
||||
if return_info:
|
||||
@@ -100,7 +107,9 @@ def detect_coupon_popup_background(
|
||||
}
|
||||
return False
|
||||
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
template = cv2.imread( # type: ignore[attr-defined,assignment]
|
||||
template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined]
|
||||
)
|
||||
if template is None:
|
||||
if return_info:
|
||||
return False, {
|
||||
@@ -118,8 +127,10 @@ def detect_coupon_popup_background(
|
||||
}
|
||||
return False
|
||||
|
||||
res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
|
||||
_, max_val, _, _ = cv2.minMaxLoc(res)
|
||||
res = cv2.matchTemplate( # type: ignore[attr-defined]
|
||||
roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
|
||||
)
|
||||
_, max_val, _, _ = cv2.minMaxLoc(res) # type: ignore[attr-defined]
|
||||
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
|
||||
if template_threshold is not None:
|
||||
threshold = float(template_threshold)
|
||||
@@ -128,21 +139,22 @@ def detect_coupon_popup_background(
|
||||
threshold = float(
|
||||
getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
threshold = 0.75
|
||||
else:
|
||||
threshold = 0.75
|
||||
result = max_val >= threshold
|
||||
|
||||
if return_info:
|
||||
reason_value: Optional[str] = None if result else "score_below_threshold"
|
||||
return result, {
|
||||
"method": "template_match",
|
||||
"template_score": float(max_val),
|
||||
"effective_threshold": threshold,
|
||||
"reason": None if result else "score_below_threshold",
|
||||
"reason": reason_value,
|
||||
}
|
||||
return result
|
||||
except Exception as e:
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
@@ -152,7 +164,7 @@ def detect_coupon_popup_background(
|
||||
return False
|
||||
|
||||
|
||||
def detect_redpacket_popup_background(pic_rgb: Image.Image) -> bool:
|
||||
def detect_redpacket_popup_background(_pic_rgb: Image.Image) -> bool:
|
||||
"""中央购物红包弹窗检测(暂时禁用,始终返回 False)。"""
|
||||
return False
|
||||
|
||||
@@ -190,7 +202,7 @@ def detect_lucky_draw_result_popup(
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
detect_roi = None
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
@@ -214,11 +226,13 @@ def detect_lucky_draw_result_popup(
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
f"[调试图像] 像素检测前保存: {debug_path}, threshold={red_ratio_threshold}"
|
||||
"[调试图像] 像素检测前保存: %s, threshold=%s",
|
||||
debug_path,
|
||||
red_ratio_threshold,
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
red_count = 0
|
||||
@@ -235,7 +249,7 @@ def detect_lucky_draw_result_popup(
|
||||
# 红色按钮检测:R >= 245 且 R 明显大于 G 和 B
|
||||
if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50:
|
||||
red_count += 1
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
if total_samples == 0:
|
||||
@@ -246,7 +260,7 @@ def detect_lucky_draw_result_popup(
|
||||
|
||||
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
if result:
|
||||
# 检测成功
|
||||
@@ -276,26 +290,33 @@ def detect_lucky_draw_result_popup(
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
f"[调试图像] 抽奖结果检测保存: {debug_path}, red_ratio={red_ratio:.4f}, threshold={red_ratio_threshold}, score={red_ratio:.4f}"
|
||||
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
|
||||
debug_path,
|
||||
red_ratio,
|
||||
red_ratio_threshold,
|
||||
red_ratio,
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 如果请求详细信息,返回包含red_ratio的字典
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": red_ratio,
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"effective_threshold": red_ratio_threshold,
|
||||
"reason": None if result else "red_ratio_below_threshold",
|
||||
"reason": reason_value,
|
||||
}
|
||||
|
||||
return result
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
return False
|
||||
|
||||
|
||||
@@ -334,7 +355,7 @@ def detect_attend_button_red_area(
|
||||
|
||||
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
@@ -348,15 +369,14 @@ def detect_attend_button_red_area(
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(f"[调试图像] 参与按钮检测前保存: {debug_path}")
|
||||
except Exception:
|
||||
logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 采样检测点:检测大片红色区域
|
||||
red_count = 0
|
||||
sample_points = []
|
||||
step_x = max(1, (x2 - x1) // 15)
|
||||
step_y = max(1, (y2 - y1) // 10)
|
||||
|
||||
@@ -367,7 +387,7 @@ def detect_attend_button_red_area(
|
||||
# 检测红色:R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
red_count += 1
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
|
||||
@@ -386,7 +406,7 @@ def detect_attend_button_red_area(
|
||||
threshold = float(
|
||||
getattr(analyser, "attend_button_red_ratio_threshold", 0.25) or 0.25
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
threshold = 0.25
|
||||
else:
|
||||
threshold = 0.25
|
||||
@@ -394,19 +414,22 @@ def detect_attend_button_red_area(
|
||||
|
||||
# 如果请求详细信息,返回包含red_ratio的字典
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": red_ratio,
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"effective_threshold": threshold,
|
||||
"reason": None if result else "red_ratio_below_threshold",
|
||||
"reason": reason_value,
|
||||
}
|
||||
|
||||
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
|
||||
if result:
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
@@ -426,11 +449,14 @@ def detect_attend_button_red_area(
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
f"[调试图像] 参与按钮检测成功保存: {debug_path}, red_ratio={red_ratio:.4f}, score={red_ratio:.4f}"
|
||||
"[调试图像] 参与按钮检测成功保存: %s, red_ratio=%.4f, score=%.4f",
|
||||
debug_path,
|
||||
red_ratio,
|
||||
red_ratio,
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
return result
|
||||
@@ -484,7 +510,6 @@ def detect_fansclub_join_red_area(
|
||||
|
||||
# 采样检测点:检测大片红色区域
|
||||
red_count = 0
|
||||
sample_points = []
|
||||
step_x = max(1, (x2 - x1) // 15)
|
||||
step_y = max(1, (y2 - y1) // 10)
|
||||
|
||||
@@ -520,20 +545,23 @@ def detect_fansclub_join_red_area(
|
||||
threshold = float(
|
||||
getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
threshold = 0.25
|
||||
else:
|
||||
threshold = 0.25
|
||||
result = red_ratio >= threshold
|
||||
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": red_ratio,
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"effective_threshold": threshold,
|
||||
"reason": None if result else "red_ratio_below_threshold",
|
||||
"reason": reason_value,
|
||||
}
|
||||
|
||||
return result
|
||||
@@ -608,7 +636,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
# 检测粉色/红色(xin图标):R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
pink_red_count += 1
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
if total_samples == 0:
|
||||
@@ -626,16 +654,16 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
confidence = min(1.0, max(white_ratio * 10, pink_red_ratio * 15))
|
||||
|
||||
return detected, confidence
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
return False, 0.0
|
||||
|
||||
|
||||
def detect_fudai_detail_page(
|
||||
pic_rgb: Image.Image,
|
||||
resolution_ratio_x: int = 1080,
|
||||
resolution_ratio_y: int = 2400,
|
||||
y_pianyi: int = 0,
|
||||
template_threshold: float = 0.7,
|
||||
_pic_rgb: Image.Image,
|
||||
_resolution_ratio_x: int = 1080,
|
||||
_resolution_ratio_y: int = 2400,
|
||||
_y_pianyi: int = 0,
|
||||
_template_threshold: float = 0.7,
|
||||
return_info: bool = False,
|
||||
analyser: Any = None,
|
||||
) -> bool | tuple[bool, dict]:
|
||||
@@ -690,7 +718,7 @@ def detect_fudai_detail_page(
|
||||
"task_count": task_count,
|
||||
}
|
||||
return is_in_detail
|
||||
except Exception as e:
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
# 检测异常
|
||||
if return_info:
|
||||
return False, {
|
||||
@@ -756,19 +784,19 @@ def read_pixel_stage_state_from_screenshot(
|
||||
coupon_threshold = float(
|
||||
getattr(analyser, "coupon_template_match_threshold", None) or 0.75
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
attend_button_threshold = float(
|
||||
getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
fansclub_threshold = float(
|
||||
getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25
|
||||
)
|
||||
except Exception:
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
detection_tasks = {
|
||||
@@ -842,7 +870,7 @@ def read_pixel_stage_state_from_screenshot(
|
||||
"detected": bool(result),
|
||||
"method": "unknown",
|
||||
}
|
||||
except Exception as e:
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
# 如果某个检测失败,保持默认值 False
|
||||
state[key] = False
|
||||
if return_details:
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
福袋相关模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ from PIL import Image
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import numpy as np
|
||||
|
||||
from douyin_utils import normalize_countdown_text, extract_prize_value_yuan
|
||||
import douyin_reservation_logic
|
||||
from douyin.utils.douyin_utils import normalize_countdown_text, extract_prize_value_yuan
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
import path_config
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ def _save_full_screenshot_with_ocr_region(
|
||||
y_pianyi: Y轴偏移
|
||||
"""
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
# 读取完整截图
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
@@ -966,7 +966,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
pass
|
||||
|
||||
participants, copies, fudai_content_text = _extract_participants_and_clean(
|
||||
fudai_content_raw
|
||||
fudai_content_raw if fudai_content_raw is not None else ""
|
||||
)
|
||||
|
||||
# 如果清理后的内容中没有检测到,但原始内容中检测到了,使用原始内容再次确认
|
||||
@@ -1165,7 +1165,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
"福袋", "识别倒计时", countdown=time_text if time_text else "未识别到"
|
||||
)
|
||||
|
||||
prize_value_yuan = extract_prize_value_yuan(value_raw)
|
||||
prize_value_yuan = extract_prize_value_yuan(value_raw if value_raw is not None else "")
|
||||
|
||||
# OCR结果验证:检查价值识别结果
|
||||
if not value_raw:
|
||||
@@ -1509,7 +1509,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
|
||||
# 保存debug截图:标注OCR识别区域(参与按钮区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
@@ -1621,7 +1621,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
|
||||
# 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
@@ -2417,7 +2417,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
# 尝试重新打开福袋详情页
|
||||
try:
|
||||
# 延迟导入避免循环导入
|
||||
import douyin_flow_control
|
||||
from douyin.core import douyin_flow_control
|
||||
|
||||
room_pos_ref = [0]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(
|
||||
@@ -4038,7 +4038,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
else:
|
||||
# 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的
|
||||
try:
|
||||
import douyin_reservation_logic as rl_cleanup
|
||||
from douyin.reservation import douyin_reservation_logic as rl_cleanup
|
||||
|
||||
rl_cleanup.cleanup_expired_reservations(
|
||||
analyser,
|
||||
@@ -4203,7 +4203,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
|
||||
# 记录高价值直播间(在记录预约之前)
|
||||
try:
|
||||
import douyin_high_value_room
|
||||
from douyin.other import douyin_high_value_room
|
||||
|
||||
if hasattr(douyin_high_value_room, "touch_high_value_room"):
|
||||
douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined]
|
||||
@@ -4293,7 +4293,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
else:
|
||||
# 如果阶段检测未保存任务数量,尝试通过阶段检测获取
|
||||
try:
|
||||
import douyin_stage
|
||||
from douyin.stage import douyin_stage
|
||||
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
result = (
|
||||
@@ -4306,7 +4306,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
if stage == "FUDai_DETAIL":
|
||||
# 尝试通过像素检测获取任务数量
|
||||
try:
|
||||
import douyin_pixel
|
||||
from douyin.detection import douyin_pixel
|
||||
import os
|
||||
|
||||
pic_path = os.path.join(
|
||||
@@ -4344,7 +4344,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
rx,
|
||||
ry,
|
||||
y_pianyi,
|
||||
template_threshold=float(
|
||||
float(
|
||||
getattr(
|
||||
analyser,
|
||||
"fudai_detail_template_threshold",
|
||||
@@ -0,0 +1,58 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
Fudai detail helpers shim (WebGUI version)
|
||||
==========================================
|
||||
|
||||
Exports:
|
||||
- close_fudai_detail
|
||||
- ensure_fudai_detail_open
|
||||
- read_live_room_title_core
|
||||
- read_fudai_detail_once
|
||||
- read_fudai_detail_with_retries
|
||||
- is_abnormal_time_value
|
||||
- validate_fudai_detail
|
||||
- is_wrong_coupon_popup
|
||||
"""
|
||||
|
||||
# 从各子模块导入所有公共API
|
||||
from fudai_detail_modules.fudai_detail_operations import (
|
||||
close_fudai_detail,
|
||||
ensure_fudai_detail_open,
|
||||
)
|
||||
|
||||
from fudai_detail_modules.fudai_detail_room_title import (
|
||||
read_live_room_title_core,
|
||||
)
|
||||
|
||||
from fudai_detail_modules.fudai_detail_reader import (
|
||||
read_fudai_detail_once,
|
||||
read_fudai_detail_with_retries,
|
||||
)
|
||||
|
||||
from fudai_detail_modules.fudai_detail_validator import (
|
||||
validate_fudai_detail,
|
||||
)
|
||||
|
||||
from fudai_detail_modules.fudai_detail_utils import (
|
||||
is_abnormal_time_value,
|
||||
)
|
||||
|
||||
from fudai_detail_modules.fudai_detail_coupon_detection import (
|
||||
is_wrong_coupon_popup,
|
||||
)
|
||||
|
||||
# 为了向后兼容,也导出 _is_wrong_coupon_popup 作为 is_wrong_coupon_popup 的别名
|
||||
_is_wrong_coupon_popup = is_wrong_coupon_popup
|
||||
|
||||
__all__ = [
|
||||
"close_fudai_detail",
|
||||
"ensure_fudai_detail_open",
|
||||
"read_live_room_title_core",
|
||||
"read_fudai_detail_once",
|
||||
"read_fudai_detail_with_retries",
|
||||
"is_abnormal_time_value",
|
||||
"validate_fudai_detail",
|
||||
"is_wrong_coupon_popup",
|
||||
"_is_wrong_coupon_popup", # 向后兼容
|
||||
]
|
||||
@@ -139,6 +139,9 @@ class FudaiDetector:
|
||||
# 支持两种区域配置方式:
|
||||
# 1. 使用 y_top 和 y_bottom(精确范围)
|
||||
# 2. 使用 y 和 y_range(中心点+范围)
|
||||
# 初始化变量,避免未绑定错误
|
||||
scan_y: int = 0
|
||||
y_range: int = 7
|
||||
if "y_top" in region and "y_bottom" in region:
|
||||
y_top = max(0, min(int(region.get("y_top", 0)), height))
|
||||
y_bottom = max(0, min(int(region.get("y_bottom", height)), height))
|
||||
@@ -646,7 +649,7 @@ class FudaiDetector:
|
||||
|
||||
# 保存模板匹配的调试图像(无论成功与否)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
# 保存搜索区域图像
|
||||
@@ -958,7 +961,7 @@ class FudaiClickExecutor:
|
||||
# 点击前检查:避免误点红包
|
||||
try:
|
||||
# 检查是否有红包弹窗
|
||||
import douyin_popups
|
||||
from douyin.other import douyin_popups
|
||||
|
||||
has_redpacket = douyin_popups.check_shopping_redpacket_popup(self.analyser)
|
||||
if has_redpacket:
|
||||
@@ -1123,7 +1126,7 @@ class FudaiDetailVerifier:
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
import douyin_pixel
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
# 等待界面加载(增加等待时间,确保详情页完全加载)
|
||||
# 点击后已经等待了2.5秒,这里再等待0.8秒,总共约3.3秒
|
||||
@@ -1154,7 +1157,7 @@ class FudaiDetailVerifier:
|
||||
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
@@ -1441,7 +1444,7 @@ class FudaiFinder:
|
||||
|
||||
# 保存完整截图用于调试(检测前)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_rgb_full = pic.convert("RGB")
|
||||
|
||||
@@ -1508,7 +1511,7 @@ class FudaiFinder:
|
||||
consecutive_failures = 0
|
||||
# 保存完整截图(检测成功)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_rgb_full = pic.convert("RGB")
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
处理器模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
弹窗处理模块
|
||||
============
|
||||
|
||||
职责:弹窗检测和处理
|
||||
- 检测优惠券弹窗
|
||||
- 检测购物红包弹窗
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from douyin.other import douyin_popups
|
||||
|
||||
|
||||
class PopupHandler:
|
||||
"""弹窗处理器:统一管理弹窗处理"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def check_coupon_popup(analyser: Any) -> bool:
|
||||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
bool: 是否检测到弹窗
|
||||
"""
|
||||
return douyin_popups.check_coupon_popup(analyser)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def check_shopping_redpacket_popup(analyser: Any) -> bool:
|
||||
"""购物红包中央弹窗。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
bool: 是否检测到弹窗
|
||||
"""
|
||||
return douyin_popups.check_shopping_redpacket_popup(analyser)
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
截图与图像处理模块
|
||||
==================
|
||||
|
||||
职责:截图、图像处理和坐标转换
|
||||
- 截图裁剪
|
||||
- 保存步骤截图
|
||||
- 坐标缩放
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
class ScreenshotHandler:
|
||||
"""截图处理器:统一管理截图操作"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def cut_pic(
|
||||
analyser: Any,
|
||||
x_top: int = 1,
|
||||
y_top: int = 1,
|
||||
x_bottom: int = 2,
|
||||
y_bottom: int = 2,
|
||||
target: str = "",
|
||||
cut_pic_name: str = "",
|
||||
y_pianyi: int = 0,
|
||||
) -> None:
|
||||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
x_top: 顶部X坐标(基准1080)
|
||||
y_top: 顶部Y坐标(基准2400)
|
||||
x_bottom: 底部X坐标(基准1080)
|
||||
y_bottom: 底部Y坐标(基准2400)
|
||||
target: 目标路径
|
||||
cut_pic_name: 裁剪图片名称
|
||||
y_pianyi: Y轴偏移
|
||||
"""
|
||||
try:
|
||||
x1 = x_top * analyser.resolution_ratio_x // 1080
|
||||
y1 = y_top * analyser.resolution_ratio_y // 2400 + int(y_pianyi or 0)
|
||||
x2 = x_bottom * analyser.resolution_ratio_x // 1080
|
||||
y2 = y_bottom * analyser.resolution_ratio_y // 2400 + int(y_pianyi or 0)
|
||||
analyser.operation.cut_pic((x1, y1), (x2, y2), target, cut_pic_name)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"截图",
|
||||
"cut_pic 失败",
|
||||
error=str(e),
|
||||
x_top=x_top,
|
||||
y_top=y_top,
|
||||
x_bottom=x_bottom,
|
||||
y_bottom=y_bottom,
|
||||
y_pianyi=y_pianyi,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def scale_from_base(analyser: Any, base_x: int, base_y: int) -> Tuple[int, int]:
|
||||
"""将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
base_x: 基准X坐标(1080基准)
|
||||
base_y: 基准Y坐标(2400基准)
|
||||
|
||||
返回:
|
||||
(scaled_x, scaled_y) 缩放后的坐标
|
||||
"""
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_off = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
sx = int(base_x * rx // 1080)
|
||||
sy = int(base_y * ry // 2400) + y_off
|
||||
return sx, sy
|
||||
except Exception:
|
||||
try:
|
||||
return int(base_x), int(base_y)
|
||||
except Exception:
|
||||
return 0, 0
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def save_step_screenshot(analyser: Any, label: str) -> None:
|
||||
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试使用。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
label: 标签(用于文件名)
|
||||
"""
|
||||
try:
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
# 确保有最新截图
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
src = os.path.join(pic_dir, "screenshot.png")
|
||||
if not os.path.exists(src):
|
||||
return
|
||||
steps_dir = os.path.join(pic_dir, "steps")
|
||||
os.makedirs(steps_dir, exist_ok=True)
|
||||
fname = (
|
||||
f"{getattr(analyser, '_run_id', 'run')}_"
|
||||
f"{getattr(analyser, '_log_seq', 0):04d}_{label}.png"
|
||||
)
|
||||
dst = os.path.join(steps_dir, fname)
|
||||
try:
|
||||
shutil.copy(src, dst)
|
||||
except Exception:
|
||||
# 最后降级为重命名保存
|
||||
try:
|
||||
shutil.copy(src, dst)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from typing import Optional, Tuple
|
||||
from PIL import Image
|
||||
import path_config
|
||||
@@ -25,51 +24,80 @@ def get_ocr_dir() -> str:
|
||||
|
||||
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", "直播间", "直播列表", "直播广场", "直播状态", "直播验证"
|
||||
]):
|
||||
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"
|
||||
]):
|
||||
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"
|
||||
]):
|
||||
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"
|
||||
]):
|
||||
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": 像素检测
|
||||
@@ -86,13 +114,13 @@ def get_latest_attempt_path(operation_type: str = "general") -> str:
|
||||
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": 像素检测
|
||||
@@ -109,7 +137,7 @@ def get_last_success_path(operation_type: str = "general") -> str:
|
||||
type_key = "template"
|
||||
else:
|
||||
type_key = "general"
|
||||
|
||||
|
||||
return os.path.join(get_ocr_dir(), f"last_success_{type_key}.png")
|
||||
|
||||
|
||||
@@ -126,13 +154,13 @@ def cleanup_ocr_dir(
|
||||
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: 最多保留的文件数(不包括特殊文件)
|
||||
|
||||
|
||||
返回:
|
||||
清理的文件数量
|
||||
"""
|
||||
@@ -140,11 +168,11 @@ def cleanup_ocr_dir(
|
||||
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'):
|
||||
if os.path.isfile(file_path) and f.lower().endswith(".png"):
|
||||
# 检查是否为特殊文件
|
||||
is_special = False
|
||||
if f.startswith("latest_attempt_") and keep_latest_attempt:
|
||||
@@ -153,13 +181,13 @@ def cleanup_ocr_dir(
|
||||
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:]:
|
||||
@@ -168,7 +196,7 @@ def cleanup_ocr_dir(
|
||||
deleted_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
return deleted_count
|
||||
except Exception:
|
||||
return 0
|
||||
@@ -176,11 +204,11 @@ def cleanup_ocr_dir(
|
||||
|
||||
def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool:
|
||||
"""保存实时操作截图(覆盖保存)
|
||||
|
||||
|
||||
参数:
|
||||
image: PIL Image 对象
|
||||
operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic")
|
||||
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
@@ -199,11 +227,11 @@ def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool:
|
||||
|
||||
def save_last_success(image: Image.Image, operation_type: str = "") -> bool:
|
||||
"""保存成功识别存档截图(不覆盖,仅成功时保存)
|
||||
|
||||
|
||||
参数:
|
||||
image: PIL Image 对象
|
||||
operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic")
|
||||
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
@@ -222,11 +250,11 @@ def save_last_success(image: Image.Image, operation_type: str = "") -> bool:
|
||||
|
||||
def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
"""从文件保存实时操作截图
|
||||
|
||||
|
||||
参数:
|
||||
source_path: 源图片文件路径
|
||||
operation_type: 操作类型
|
||||
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
@@ -245,11 +273,11 @@ def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
|
||||
def save_success_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
"""从文件保存成功识别存档截图
|
||||
|
||||
|
||||
参数:
|
||||
source_path: 源图片文件路径
|
||||
operation_type: 操作类型
|
||||
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
@@ -272,6 +300,7 @@ def get_debug_captures_dir() -> str:
|
||||
debug_dir = os.path.join(pic_dir, "debug_captures")
|
||||
# 按日期分类:YYYY-MM-DD
|
||||
from datetime import datetime
|
||||
|
||||
date_str = datetime.now().strftime("%Y-%m-%d")
|
||||
return os.path.join(debug_dir, date_str)
|
||||
|
||||
@@ -302,7 +331,7 @@ def get_debug_captures_base_dir() -> str:
|
||||
|
||||
def count_debug_captures_files() -> int:
|
||||
"""统计所有调试图像文件的总数量
|
||||
|
||||
|
||||
返回:
|
||||
文件总数
|
||||
"""
|
||||
@@ -310,27 +339,27 @@ def count_debug_captures_files() -> int:
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
if not os.path.exists(debug_base_dir):
|
||||
return 0
|
||||
|
||||
|
||||
total_count = 0
|
||||
# 遍历所有日期目录
|
||||
for item in os.listdir(debug_base_dir):
|
||||
# 跳过隐藏文件和标记文件
|
||||
if item.startswith('.'):
|
||||
if item.startswith("."):
|
||||
continue
|
||||
|
||||
|
||||
item_path = os.path.join(debug_base_dir, item)
|
||||
if not os.path.isdir(item_path):
|
||||
continue
|
||||
|
||||
|
||||
# 统计该目录下的所有PNG文件
|
||||
try:
|
||||
for root, dirs, files in os.walk(item_path):
|
||||
for _root, _dirs, files in os.walk(item_path):
|
||||
for f in files:
|
||||
if f.lower().endswith('.png'):
|
||||
if f.lower().endswith(".png"):
|
||||
total_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
return total_count
|
||||
except Exception:
|
||||
return 0
|
||||
@@ -338,11 +367,11 @@ def count_debug_captures_files() -> int:
|
||||
|
||||
def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
"""清理旧的调试图像存档目录
|
||||
|
||||
|
||||
参数:
|
||||
keep_days: 保留天数,默认7天,超过此天数的目录将被删除
|
||||
max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录
|
||||
|
||||
|
||||
返回:
|
||||
清理的目录数量
|
||||
"""
|
||||
@@ -350,38 +379,38 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
if not os.path.exists(debug_base_dir):
|
||||
return 0
|
||||
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
# 计算截止日期
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
|
||||
|
||||
deleted_count = 0
|
||||
deleted_dirs = []
|
||||
total_size_freed = 0
|
||||
|
||||
|
||||
# 收集所有日期目录及其信息
|
||||
dirs_info = []
|
||||
for item in os.listdir(debug_base_dir):
|
||||
# 跳过隐藏文件和标记文件
|
||||
if item.startswith('.'):
|
||||
if item.startswith("."):
|
||||
continue
|
||||
|
||||
|
||||
item_path = os.path.join(debug_base_dir, item)
|
||||
if not os.path.isdir(item_path):
|
||||
continue
|
||||
|
||||
|
||||
# 尝试解析目录名为日期(格式:YYYY-MM-DD)
|
||||
try:
|
||||
dir_date = datetime.strptime(item, "%Y-%m-%d")
|
||||
|
||||
|
||||
# 统计该目录下的文件数量和大小
|
||||
file_count = 0
|
||||
dir_size = 0
|
||||
try:
|
||||
for root, dirs, files in os.walk(item_path):
|
||||
for root, _dirs, files in os.walk(item_path):
|
||||
for f in files:
|
||||
if f.lower().endswith('.png'):
|
||||
if f.lower().endswith(".png"):
|
||||
file_count += 1
|
||||
file_path = os.path.join(root, f)
|
||||
try:
|
||||
@@ -390,71 +419,77 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
dirs_info.append({
|
||||
'name': item,
|
||||
'path': item_path,
|
||||
'date': dir_date,
|
||||
'file_count': file_count,
|
||||
'size': dir_size
|
||||
})
|
||||
|
||||
dirs_info.append(
|
||||
{
|
||||
"name": item,
|
||||
"path": item_path,
|
||||
"date": dir_date,
|
||||
"file_count": file_count,
|
||||
"size": dir_size,
|
||||
}
|
||||
)
|
||||
except ValueError:
|
||||
# 如果目录名不是日期格式,跳过
|
||||
continue
|
||||
|
||||
|
||||
# 按日期排序(最旧的在前)
|
||||
dirs_info.sort(key=lambda x: x['date'])
|
||||
|
||||
dirs_info.sort(key=lambda x: x["date"])
|
||||
|
||||
# 先按天数清理:删除超过保留天数的目录
|
||||
for dir_info in dirs_info[:]:
|
||||
if dir_info['date'] < cutoff_date:
|
||||
if dir_info["date"] < cutoff_date:
|
||||
try:
|
||||
shutil.rmtree(dir_info['path'])
|
||||
shutil.rmtree(dir_info["path"])
|
||||
deleted_count += 1
|
||||
deleted_dirs.append(dir_info['name'])
|
||||
total_size_freed += dir_info['size']
|
||||
deleted_dirs.append(dir_info["name"])
|
||||
total_size_freed += dir_info["size"]
|
||||
dirs_info.remove(dir_info)
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录
|
||||
total_files = sum(d['file_count'] for d in dirs_info)
|
||||
total_files = sum(d["file_count"] for d in dirs_info)
|
||||
if total_files > max_files:
|
||||
# 计算需要删除的文件数量
|
||||
need_delete_count = total_files - max_files
|
||||
|
||||
|
||||
# 从最旧的目录开始删除,直到文件数量降到max_files以下
|
||||
deleted_files_count = 0
|
||||
for dir_info in dirs_info[:]:
|
||||
if deleted_files_count >= need_delete_count:
|
||||
break
|
||||
|
||||
|
||||
try:
|
||||
shutil.rmtree(dir_info['path'])
|
||||
shutil.rmtree(dir_info["path"])
|
||||
deleted_count += 1
|
||||
deleted_dirs.append(dir_info['name'])
|
||||
total_size_freed += dir_info['size']
|
||||
deleted_files_count += dir_info['file_count']
|
||||
deleted_dirs.append(dir_info["name"])
|
||||
total_size_freed += dir_info["size"]
|
||||
deleted_files_count += dir_info["file_count"]
|
||||
dirs_info.remove(dir_info)
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if deleted_count > 0:
|
||||
try:
|
||||
size_mb = total_size_freed / (1024 * 1024)
|
||||
reason_parts = []
|
||||
if total_files > max_files:
|
||||
reason_parts.append(f"文件数量超过{max_files}")
|
||||
if any(d['date'] < cutoff_date for d in dirs_info if d not in [{'name': name} for name in deleted_dirs]):
|
||||
if any(
|
||||
d["date"] < cutoff_date
|
||||
for d in dirs_info
|
||||
if d not in [{"name": name} for name in deleted_dirs]
|
||||
):
|
||||
reason_parts.append(f"超过{keep_days}天")
|
||||
reason = ",".join(reason_parts) if reason_parts else "自动清理"
|
||||
|
||||
|
||||
print(
|
||||
f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}"
|
||||
)
|
||||
@@ -463,7 +498,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
print(f"[调试图像清理] 释放空间: {size_mb:.2f} MB")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
return deleted_count
|
||||
except Exception as e:
|
||||
# 清理失败不应影响程序运行
|
||||
@@ -476,28 +511,29 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
|
||||
def init_debug_captures_cleanup() -> None:
|
||||
"""初始化调试图像清理(在程序启动时调用)
|
||||
|
||||
|
||||
从 config.json 读取配置并执行清理
|
||||
"""
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if not os.path.exists(config_path):
|
||||
return
|
||||
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
|
||||
|
||||
# 检查是否启用自动清理
|
||||
auto_cleanup = True
|
||||
keep_days = 7
|
||||
max_files = 2000
|
||||
|
||||
if 'debug_captures' in config and isinstance(config['debug_captures'], dict):
|
||||
auto_cleanup = config['debug_captures'].get('auto_cleanup', True)
|
||||
keep_days = int(config['debug_captures'].get('keep_days', 7))
|
||||
max_files = int(config['debug_captures'].get('max_files', 2000))
|
||||
|
||||
|
||||
if "debug_captures" in config and isinstance(config["debug_captures"], dict):
|
||||
auto_cleanup = config["debug_captures"].get("auto_cleanup", True)
|
||||
keep_days = int(config["debug_captures"].get("keep_days", 7))
|
||||
max_files = int(config["debug_captures"].get("max_files", 2000))
|
||||
|
||||
if auto_cleanup:
|
||||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||||
except Exception:
|
||||
@@ -507,40 +543,40 @@ def init_debug_captures_cleanup() -> None:
|
||||
|
||||
def _sanitize_filename_part(text: str) -> str:
|
||||
"""清理文件名部分,移除Windows不允许的字符
|
||||
|
||||
|
||||
参数:
|
||||
text: 要清理的文本
|
||||
|
||||
|
||||
返回:
|
||||
清理后的文本
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
|
||||
# Windows文件名不允许的字符: < > : " / \ | ? *
|
||||
# 同时移除路径分隔符和空格(用下划线替换)
|
||||
invalid_chars = '<>:"/\\|?*'
|
||||
sanitized = str(text)
|
||||
|
||||
|
||||
# 如果是路径,只保留文件名部分
|
||||
if os.sep in sanitized or '/' in sanitized:
|
||||
if os.sep in sanitized or "/" in sanitized:
|
||||
sanitized = os.path.basename(sanitized)
|
||||
|
||||
|
||||
# 移除所有无效字符
|
||||
for char in invalid_chars:
|
||||
sanitized = sanitized.replace(char, '_')
|
||||
|
||||
sanitized = sanitized.replace(char, "_")
|
||||
|
||||
# 移除连续的下划线,替换为单个下划线
|
||||
while '__' in sanitized:
|
||||
sanitized = sanitized.replace('__', '_')
|
||||
|
||||
while "__" in sanitized:
|
||||
sanitized = sanitized.replace("__", "_")
|
||||
|
||||
# 移除首尾的下划线和空格
|
||||
sanitized = sanitized.strip('_').strip()
|
||||
|
||||
sanitized = sanitized.strip("_").strip()
|
||||
|
||||
# 如果清理后为空,返回默认值
|
||||
if not sanitized:
|
||||
sanitized = "unknown"
|
||||
|
||||
|
||||
return sanitized
|
||||
|
||||
|
||||
@@ -551,12 +587,12 @@ def save_debug_image(
|
||||
step: str = "",
|
||||
coords: Optional[Tuple[int, int, int, int]] = None,
|
||||
extra_info: Optional[dict] = None,
|
||||
session_id: Optional[str] = None,
|
||||
session_id: Optional[str] = None, # noqa: ARG001
|
||||
annotate: bool = True,
|
||||
auto_cleanup: bool = True,
|
||||
) -> Optional[str]:
|
||||
"""保存调试图像到存档目录
|
||||
|
||||
|
||||
参数:
|
||||
image: PIL Image 对象
|
||||
operation_type: 操作类型("pixel_detect", "ocr", "template_match", "cut_pic")
|
||||
@@ -564,10 +600,10 @@ def save_debug_image(
|
||||
step: 步骤描述(可选,如 "before_detect", "detected")
|
||||
coords: 坐标信息 (x1, y1, x2, y2)(可选)
|
||||
extra_info: 额外信息字典(可选)
|
||||
session_id: 会话ID(可选,默认使用当前日期)
|
||||
session_id: 会话ID(可选,默认使用当前日期,保留用于未来扩展)
|
||||
annotate: 是否在图像上添加标注信息(默认True)
|
||||
auto_cleanup: 是否自动清理旧目录(默认True)
|
||||
|
||||
|
||||
返回:
|
||||
保存的文件路径,失败返回None
|
||||
"""
|
||||
@@ -575,6 +611,7 @@ def save_debug_image(
|
||||
# 从配置读取是否启用调试图像保存;默认关闭
|
||||
try:
|
||||
import json
|
||||
|
||||
enabled = False
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
@@ -596,19 +633,20 @@ def save_debug_image(
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker")
|
||||
from datetime import datetime
|
||||
|
||||
today_str = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# 读取标记文件,检查今天是否已清理
|
||||
need_cleanup = True
|
||||
if os.path.exists(cleanup_marker):
|
||||
try:
|
||||
with open(cleanup_marker, 'r', encoding='utf-8') as f:
|
||||
with open(cleanup_marker, "r", encoding="utf-8") as f:
|
||||
last_cleanup_date = f.read().strip()
|
||||
if last_cleanup_date == today_str:
|
||||
need_cleanup = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if need_cleanup:
|
||||
# 从配置读取保留天数、最大文件数和自动清理设置
|
||||
keep_days = 7 # 默认7天
|
||||
@@ -616,24 +654,33 @@ def save_debug_image(
|
||||
cleanup_enabled = True
|
||||
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:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
if 'debug_captures' in config and isinstance(config['debug_captures'], dict):
|
||||
cleanup_enabled = config['debug_captures'].get('auto_cleanup', True)
|
||||
keep_days = int(config['debug_captures'].get('keep_days', 7))
|
||||
max_files = int(config['debug_captures'].get('max_files', 2000))
|
||||
if "debug_captures" in config and isinstance(
|
||||
config["debug_captures"], dict
|
||||
):
|
||||
cleanup_enabled = config["debug_captures"].get(
|
||||
"auto_cleanup", True
|
||||
)
|
||||
keep_days = int(
|
||||
config["debug_captures"].get("keep_days", 7)
|
||||
)
|
||||
max_files = int(
|
||||
config["debug_captures"].get("max_files", 2000)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 如果启用自动清理,执行清理
|
||||
if cleanup_enabled:
|
||||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||||
|
||||
|
||||
# 更新标记文件(仅在执行清理后更新)
|
||||
try:
|
||||
with open(cleanup_marker, 'w', encoding='utf-8') as f:
|
||||
with open(cleanup_marker, "w", encoding="utf-8") as f:
|
||||
f.write(today_str)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -642,36 +689,46 @@ def save_debug_image(
|
||||
# 如果超过,立即清理(不更新标记文件,避免频繁清理)
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
max_files = 2000
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
if 'debug_captures' in config and isinstance(config['debug_captures'], dict):
|
||||
max_files = int(config['debug_captures'].get('max_files', 2000))
|
||||
|
||||
if "debug_captures" in config and isinstance(
|
||||
config["debug_captures"], dict
|
||||
):
|
||||
max_files = int(
|
||||
config["debug_captures"].get("max_files", 2000)
|
||||
)
|
||||
|
||||
# 检查当前文件数量
|
||||
current_count = count_debug_captures_files()
|
||||
if current_count > max_files:
|
||||
# 文件数量超过限制,立即清理
|
||||
try:
|
||||
print(f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理")
|
||||
print(
|
||||
f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
cleanup_debug_captures(keep_days=999, max_files=max_files) # keep_days设为999表示只按文件数量清理
|
||||
cleanup_debug_captures(
|
||||
keep_days=999, max_files=max_files
|
||||
) # keep_days设为999表示只按文件数量清理
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 清理失败不影响保存操作
|
||||
pass
|
||||
|
||||
|
||||
ensure_debug_captures_dir()
|
||||
debug_dir = get_debug_captures_dir()
|
||||
|
||||
|
||||
# 生成文件名
|
||||
from datetime import datetime
|
||||
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
|
||||
|
||||
parts = []
|
||||
if operation_type:
|
||||
parts.append(_sanitize_filename_part(operation_type))
|
||||
@@ -695,10 +752,10 @@ def save_debug_image(
|
||||
if len(clean_value) > 30:
|
||||
clean_value = clean_value[:30]
|
||||
parts.append(f"{clean_key}_{clean_value}")
|
||||
|
||||
|
||||
filename_parts = [timestamp] + parts
|
||||
filename = "_".join(str(p) for p in filename_parts if p) + ".png"
|
||||
|
||||
|
||||
# Windows文件名长度限制(260字符),自动截断
|
||||
# 考虑完整路径长度,文件名部分限制更严格
|
||||
max_len = 180 # 留更多余量,考虑目录路径长度
|
||||
@@ -712,9 +769,9 @@ def save_debug_image(
|
||||
base_parts.append(_sanitize_filename_part(picname))
|
||||
if step:
|
||||
base_parts.append(_sanitize_filename_part(step))
|
||||
|
||||
|
||||
base = "_".join(base_parts)
|
||||
|
||||
|
||||
# 如果还有空间,添加最重要的额外信息(排除长文本)
|
||||
remaining = max_len - len(base) - 10 # 留10字符余量
|
||||
if remaining > 20 and extra_info:
|
||||
@@ -729,19 +786,21 @@ def save_debug_image(
|
||||
if len(part) <= remaining:
|
||||
base += f"_{part}"
|
||||
remaining -= len(part) + 1
|
||||
|
||||
|
||||
filename = base[:max_len] + ".png"
|
||||
|
||||
|
||||
file_path = os.path.join(debug_dir, filename)
|
||||
|
||||
|
||||
# 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在)
|
||||
try:
|
||||
ensure_debug_captures_dir()
|
||||
except Exception:
|
||||
pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理
|
||||
|
||||
|
||||
# 保存图像的辅助函数,带重试机制
|
||||
def save_image_with_retry(img_to_save: Image.Image, path: str, max_retries: int = 2) -> bool:
|
||||
def save_image_with_retry(
|
||||
img_to_save: Image.Image, path: str, max_retries: int = 2
|
||||
) -> bool:
|
||||
"""保存图像,如果目录不存在则创建后重试"""
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
@@ -761,14 +820,15 @@ def save_debug_image(
|
||||
# 其他异常直接抛出
|
||||
raise
|
||||
return False
|
||||
|
||||
|
||||
# 如果需要标注,在图像上添加信息
|
||||
if annotate and (coords or extra_info):
|
||||
try:
|
||||
from PIL import ImageDraw, ImageFont
|
||||
|
||||
annotated_image = image.copy()
|
||||
draw = ImageDraw.Draw(annotated_image)
|
||||
|
||||
|
||||
# 尝试使用默认字体
|
||||
try:
|
||||
font = ImageFont.truetype("arial.ttf", 12)
|
||||
@@ -777,7 +837,7 @@ def save_debug_image(
|
||||
font = ImageFont.load_default()
|
||||
except Exception:
|
||||
font = None
|
||||
|
||||
|
||||
# 绘制坐标框
|
||||
if coords:
|
||||
x1, y1, x2, y2 = coords
|
||||
@@ -787,12 +847,17 @@ def save_debug_image(
|
||||
y1 = max(0, min(y1, img_h - 1))
|
||||
x2 = max(0, min(x2, img_w - 1))
|
||||
y2 = max(0, min(y2, img_h - 1))
|
||||
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
# 使用元组格式 (x1, y1, x2, y2)
|
||||
rect_coords: Tuple[float, float, float, float] = (float(x1), float(y1), float(x2), float(y2))
|
||||
rect_coords: Tuple[float, float, float, float] = (
|
||||
float(x1),
|
||||
float(y1),
|
||||
float(x2),
|
||||
float(y2),
|
||||
)
|
||||
draw.rectangle(rect_coords, outline="red", width=2)
|
||||
|
||||
|
||||
# 添加文本信息
|
||||
if extra_info:
|
||||
text_lines = [f"{k}: {v}" for k, v in extra_info.items()]
|
||||
@@ -803,7 +868,7 @@ def save_debug_image(
|
||||
draw.text((5, 5), text, fill="yellow", font=font)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
save_image_with_retry(annotated_image, file_path)
|
||||
except Exception:
|
||||
# 如果标注失败,直接保存原图
|
||||
@@ -814,7 +879,7 @@ def save_debug_image(
|
||||
raise
|
||||
else:
|
||||
save_image_with_retry(image, file_path)
|
||||
|
||||
|
||||
return file_path
|
||||
except Exception as e:
|
||||
try:
|
||||
@@ -822,4 +887,3 @@ def save_debug_image(
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
滑动操作模块
|
||||
============
|
||||
|
||||
职责:滑动操作和导航
|
||||
- 上滑切换直播间
|
||||
- 下滑返回
|
||||
- 滑动次数重置
|
||||
- 返回推荐页并重新进入
|
||||
"""
|
||||
|
||||
import time
|
||||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
from douyin.handlers import douyin_swipe_ops
|
||||
|
||||
|
||||
class SwipeHandler:
|
||||
"""滑动处理器:统一管理滑动操作"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def swipe_up_to_next_live(analyser: Any) -> None:
|
||||
"""上滑切换直播间(简单版封装)。
|
||||
|
||||
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
|
||||
则不允许上划离开预约直播间,直接返回。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
# 检查是否在预约锁定期内
|
||||
try:
|
||||
focus_until = float(
|
||||
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
|
||||
)
|
||||
now_ts = time.time()
|
||||
if focus_until > 0 and now_ts < focus_until:
|
||||
# 在锁定期内,不允许上划离开预约直播间
|
||||
remain_seconds = int(focus_until - now_ts)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 锁定期内不允许上划离开预约直播间",
|
||||
focus_until=int(focus_until),
|
||||
remain_seconds=remain_seconds,
|
||||
queue_full_waiting=getattr(
|
||||
analyser, "queue_full_waiting_at_earliest", False
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return # 直接返回,不执行上划操作
|
||||
except Exception:
|
||||
# 如果检查锁定期时出错,继续执行上划(避免因异常导致无法切换)
|
||||
pass
|
||||
|
||||
start_time = time.time()
|
||||
douyin_swipe_ops.swipe_up_switch_live(analyser)
|
||||
# 记录直播间位置:上滑 +1
|
||||
try:
|
||||
analyser.room_pos += 1
|
||||
except Exception:
|
||||
analyser.room_pos = 0
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"操作", "上滑切换直播间", elapsed_seconds=round(elapsed, 2)
|
||||
)
|
||||
|
||||
# 记录滑动次数(用于滑动次数重置功能)
|
||||
try:
|
||||
if not hasattr(analyser, "_swipe_times"):
|
||||
analyser._swipe_times = 0
|
||||
analyser._swipe_times += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否需要重置(滑动次数达到阈值)
|
||||
try:
|
||||
SwipeHandler.maybe_reset_after_swipes(analyser)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 设置标志:刚刚切换了直播间,阶段检测后需要等待福袋加载
|
||||
try:
|
||||
analyser._just_switched_room = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 清除第一次读取标志,确保新直播间的福袋会进行完整的OCR识别
|
||||
try:
|
||||
analyser._fudai_detail_first_read = False
|
||||
analyser._last_fudai_detail_tuple = None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
|
||||
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
|
||||
try:
|
||||
skip_record = bool(
|
||||
getattr(analyser, "_skip_record_title_during_seek", False)
|
||||
)
|
||||
if not skip_record:
|
||||
analyser._record_room_title_and_pos() # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def swipe_down_back_from_live(analyser: Any) -> None:
|
||||
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
douyin_swipe_ops.swipe_down_back_live(analyser)
|
||||
except Exception:
|
||||
# 若子模块未实现,则退化为点击返回键
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
# 记录直播间位置:下滑/回退 -1
|
||||
try:
|
||||
analyser.room_pos -= 1
|
||||
except Exception:
|
||||
analyser.room_pos = 0
|
||||
|
||||
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
|
||||
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
|
||||
try:
|
||||
skip_record = bool(
|
||||
getattr(analyser, "_skip_record_title_during_seek", False)
|
||||
)
|
||||
if not skip_record:
|
||||
analyser._record_room_title_and_pos() # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def maybe_reset_after_swipes(analyser: Any) -> int:
|
||||
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
重置后的滑动次数(通常为0)
|
||||
"""
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if not needswitch:
|
||||
return getattr(analyser, "_swipe_times", 0)
|
||||
|
||||
if not bool(getattr(analyser, "reset_after_swipes_enabled", False)):
|
||||
return getattr(analyser, "_swipe_times", 0)
|
||||
|
||||
try:
|
||||
swipe_times = int(getattr(analyser, "_swipe_times", 0) or 0)
|
||||
except Exception:
|
||||
swipe_times = 0
|
||||
|
||||
threshold = max(1, int(getattr(analyser, "reset_after_swipes", 0) or 0))
|
||||
if swipe_times < threshold:
|
||||
return swipe_times
|
||||
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"已切换直播间{}次,达到阈值{}:向上回退到第一个直播间".format(
|
||||
swipe_times, threshold
|
||||
),
|
||||
swipe_times=swipe_times,
|
||||
threshold=threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退次数按当前已切换次数来(更符合"回到本轮第一个直播间"的语义)
|
||||
back_times = int(swipe_times)
|
||||
# 防止无限循环:最大回退次数限制为100
|
||||
if back_times > 100:
|
||||
back_times = 100
|
||||
if back_times <= 0:
|
||||
return 0
|
||||
|
||||
# 向上回退:从上往下滑动(与上划切换相反方向)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
|
||||
for i in range(back_times):
|
||||
try:
|
||||
# 向上回退:从上往下滑动(start_y < end_y)
|
||||
start_x = 760 * rx // 1080
|
||||
start_y = 800 * ry // 2400 # 上方起始位置
|
||||
end_x = 760 * rx // 1080
|
||||
end_y = 1600 * ry // 2400 # 下方结束位置
|
||||
# 直接使用 ADB 内部滑动命令
|
||||
try:
|
||||
if hasattr(analyser.operation, "_adb"):
|
||||
adb_cmd = analyser.operation._adb()
|
||||
else:
|
||||
import os
|
||||
|
||||
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
|
||||
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
|
||||
adb_cmd = f'"{adb_cmd}"'
|
||||
cmd = (
|
||||
f"{adb_cmd} -s {analyser.device_id} shell input swipe "
|
||||
f"{start_x} {start_y} {end_x} {end_y} 200"
|
||||
)
|
||||
subprocess.run(
|
||||
cmd,
|
||||
shell=True,
|
||||
timeout=5.0,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
except Exception:
|
||||
# 回退到 operation.swipe
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 200
|
||||
)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", "回退直播间 {}/{}".format(i + 1, back_times)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回到第一个后,计数归零
|
||||
analyser.operation.delay(3)
|
||||
try:
|
||||
analyser._swipe_times = 0
|
||||
analyser.room_pos = 0
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def return_to_recommend_and_reenter_live(analyser: Any) -> None:
|
||||
"""返回推荐页面并重新进入直播间。
|
||||
|
||||
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
analyser._log_kv("超时", "开始返回推荐页面") # type: ignore[attr-defined]
|
||||
|
||||
# 多次点击返回键,直到到达推荐页面
|
||||
max_back_clicks = analyser.MAX_BACK_CLICKS_TO_RECOMMEND
|
||||
for i in range(max_back_clicks):
|
||||
try:
|
||||
# 截图并诊断当前阶段
|
||||
ok = analyser.operation.get_screenshot(analyser.device_id)
|
||||
if not ok:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时", f"获取截图失败 ({i+1}/{max_back_clicks})"
|
||||
)
|
||||
# 即使截图失败,也尝试点击返回键
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
|
||||
continue
|
||||
|
||||
# 诊断当前阶段
|
||||
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
|
||||
|
||||
# 如果已经在推荐页面,跳出循环
|
||||
if stage == "RECOMMEND_PAGE":
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时", f"已到达推荐页面 ({i+1}次返回键)"
|
||||
)
|
||||
break
|
||||
|
||||
# 点击返回键
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
|
||||
|
||||
if i == max_back_clicks - 1:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
f"已点击{max_back_clicks}次返回键,可能未到达推荐页面",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
f"返回推荐页面时出错 ({i+1}/{max_back_clicks})",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 继续尝试点击返回键
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
|
||||
except Exception as e2:
|
||||
# 记录异常但继续执行
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
"点击返回键失败但继续",
|
||||
error=str(e2),
|
||||
error_type=type(e2).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass # 日志系统本身出错时忽略
|
||||
|
||||
# 等待页面稳定
|
||||
analyser.operation.delay(analyser.PAGE_STABLE_DELAY)
|
||||
|
||||
# 再次截图确认当前阶段
|
||||
try:
|
||||
ok = analyser.operation.get_screenshot(analyser.device_id)
|
||||
if ok:
|
||||
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时", "确认当前阶段", stage=stage, seen=seen
|
||||
)
|
||||
except Exception as e:
|
||||
# 记录异常但继续执行(阶段诊断失败不影响主流程)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
"确认阶段时出错但继续",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass # 日志系统本身出错时忽略
|
||||
|
||||
# 点击关注标签并进入直播间(复用现有逻辑)
|
||||
try:
|
||||
# 点击关注标签 (709, 169) - 基于1080x2400分辨率
|
||||
follow_tab_x = int(709 * analyser.resolution_ratio_x // 1080)
|
||||
follow_tab_y = int(169 * analyser.resolution_ratio_y // 2400)
|
||||
analyser.operation.click(analyser.device_id, follow_tab_x, follow_tab_y)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时", "点击关注标签", x=follow_tab_x, y=follow_tab_y
|
||||
)
|
||||
analyser.operation.delay(analyser.FOLLOW_TAB_CLICK_DELAY)
|
||||
|
||||
# 点击进入直播间的位置 (103, 385),连点两次
|
||||
enter_live_x = int(103 * analyser.resolution_ratio_x // 1080)
|
||||
enter_live_y = int(385 * analyser.resolution_ratio_y // 2400)
|
||||
analyser.operation.click(analyser.device_id, enter_live_x, enter_live_y)
|
||||
analyser.operation.delay(analyser.ENTER_LIVE_CLICK_DELAY)
|
||||
analyser.operation.click(analyser.device_id, enter_live_x, enter_live_y)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
"点击进入直播间位置",
|
||||
x=enter_live_x,
|
||||
y=enter_live_y,
|
||||
次数=2,
|
||||
)
|
||||
analyser.operation.delay(analyser.ENTER_LIVE_FINAL_DELAY)
|
||||
|
||||
analyser._log_kv("超时", "已重新进入直播间") # type: ignore[attr-defined]
|
||||
|
||||
# 重置超时相关时间戳(在成功重新进入直播间后重置,避免立即再次触发)
|
||||
try:
|
||||
analyser._last_successful_attend_ts = time.time()
|
||||
analyser._run_start_ts = time.time()
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
"重置时间戳时出错",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass # 日志系统本身出错时忽略
|
||||
except Exception as e:
|
||||
# 记录异常但继续执行
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
"重新进入直播间时出错",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass # 日志系统本身出错时忽略
|
||||
# 如果出错,尝试回退
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
|
||||
except Exception as e2:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"超时",
|
||||
"回退操作失败",
|
||||
error=str(e2),
|
||||
error_type=type(e2).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass # 日志系统本身出错时忽略
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
日志相关模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import os
|
||||
import sys
|
||||
import json
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
import path_config
|
||||
|
||||
|
||||
@@ -120,7 +119,6 @@ def setup_logging(
|
||||
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")
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,624 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
日志管理模块
|
||||
============
|
||||
|
||||
职责:日志记录和格式化
|
||||
- 增强版日志记录
|
||||
- 步骤时间记录
|
||||
- 统一日志格式
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import inspect
|
||||
import traceback
|
||||
from typing import Any, Dict, Optional
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class LoggingWrapper:
|
||||
"""日志包装器:统一管理日志功能"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def enhanced_log_kv(analyser: Any, *args: Any, **fields: Any) -> None:
|
||||
"""增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
*args: 位置参数,第一个是tag,第二个是msg
|
||||
**fields: 关键字参数字典
|
||||
"""
|
||||
# 解析参数:优先使用位置参数,避免与关键字参数冲突
|
||||
if len(args) >= 1:
|
||||
tag = args[0]
|
||||
# 如果位置参数提供了 tag,从 fields 中移除 tag 避免冲突
|
||||
fields.pop("tag", None)
|
||||
else:
|
||||
tag = fields.get("tag", "日志")
|
||||
|
||||
if len(args) >= 2:
|
||||
msg = args[1]
|
||||
# 如果位置参数提供了 msg,从 fields 中移除 msg 避免冲突
|
||||
fields.pop("msg", None)
|
||||
else:
|
||||
msg = fields.get("msg", "")
|
||||
|
||||
# 获取日志级别
|
||||
log_level = fields.get("level", "INFO").upper()
|
||||
if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
||||
log_level = "INFO"
|
||||
|
||||
# 递增日志序号
|
||||
try:
|
||||
analyser._log_seq += 1
|
||||
except Exception:
|
||||
analyser._log_seq = 1
|
||||
|
||||
# 获取时间戳
|
||||
try:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
except Exception:
|
||||
# 如果无法导入 datetime(极少见),回退为 time.strftime
|
||||
try:
|
||||
timestamp = time.strftime("%H:%M:%S")
|
||||
except Exception:
|
||||
timestamp = ""
|
||||
|
||||
# 获取调用者信息(模块名:函数名:行号)
|
||||
caller_info = ""
|
||||
try:
|
||||
# 获取调用栈:跳过 _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
|
||||
# 只取文件名,不包含路径
|
||||
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: Dict[str, str] = {
|
||||
"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: list[str] = []
|
||||
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)
|
||||
|
||||
# 判断是否需要添加分隔符(便于查看日志)
|
||||
need_separator = False
|
||||
separator_reason = ""
|
||||
|
||||
# 1. 错误发生时(优先级最高)
|
||||
if log_level in ("ERROR", "WARNING", "CRITICAL"):
|
||||
need_separator = True
|
||||
separator_reason = "错误/警告"
|
||||
|
||||
# 2. 运行开始时
|
||||
elif tag and any(
|
||||
keyword in str(tag) for keyword in ["运行", "启动", "开始", "初始化"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "运行开始"
|
||||
|
||||
# 3. 阶段变化时(tag变化且包含阶段相关关键词)
|
||||
elif tag and getattr(analyser, "_last_log_tag", None) != tag:
|
||||
if any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["阶段", "循环", "参与", "检测", "寻找", "进入", "退出"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "阶段变化"
|
||||
|
||||
# 4. 重要操作(通过tag判断)
|
||||
elif tag and getattr(analyser, "_last_log_tag", None) != tag:
|
||||
if any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["参与", "中奖", "完成", "失败", "超时"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "重要操作"
|
||||
|
||||
# 输出分隔符(如果需要)
|
||||
if need_separator:
|
||||
try:
|
||||
# 使用等号作为分隔符,更清晰易读
|
||||
separator = "=" * 80
|
||||
# 在分隔符中间显示原因,更美观
|
||||
reason_text = f" {separator_reason} "
|
||||
separator_line = (
|
||||
f"{separator}\n{reason_text.center(80, '=')}\n{separator}"
|
||||
)
|
||||
print(separator_line, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
|
||||
try:
|
||||
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 写入行为日志(actions.log)- 使用运行日志格式,但只保留关键信息
|
||||
# 记录所有操作到行为日志
|
||||
try:
|
||||
# 判断是否需要记录(记录所有操作,但可以过滤一些噪音日志)
|
||||
should_log = True
|
||||
|
||||
# 过滤一些不需要记录的日志(避免噪音)
|
||||
if tag:
|
||||
# 跳过一些调试或详细日志
|
||||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||||
for skip_tag in skip_tags:
|
||||
if tag.startswith(skip_tag):
|
||||
should_log = False
|
||||
break
|
||||
|
||||
if should_log:
|
||||
# 获取时间戳
|
||||
if not timestamp:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
|
||||
# 提取关键信息:做了什么、耗时、分数
|
||||
# 如果msg为空,从tag中提取操作描述
|
||||
if msg:
|
||||
action_desc = str(msg)
|
||||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||||
# 先移除带冒号的函数名
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
|
||||
)
|
||||
# 再移除带空格的函数名(但后面不是字母/下划线开头的单词)
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
|
||||
)
|
||||
# 如果移除后为空,保留原描述
|
||||
if not action_desc.strip():
|
||||
action_desc = str(msg)
|
||||
# 简化描述:移除字段前缀,只保留关键信息
|
||||
if "字段_" in action_desc:
|
||||
# 提取阶段信息(如果有)
|
||||
if "字段_阶段=" in action_desc:
|
||||
stage_match = re.search(r"字段_阶段=(\w+)", action_desc)
|
||||
if stage_match:
|
||||
action_desc = f"阶段={stage_match.group(1)}"
|
||||
else:
|
||||
# 简化其他字段描述,只保留消息部分
|
||||
action_desc = action_desc.split("字段_")[0].strip()
|
||||
else:
|
||||
# 从tag中提取操作类型(移除标签的方括号)
|
||||
if tag:
|
||||
tag_clean = tag.strip("[]").strip()
|
||||
if tag_clean:
|
||||
action_desc = tag_clean
|
||||
else:
|
||||
action_desc = "操作"
|
||||
else:
|
||||
action_desc = "操作"
|
||||
|
||||
# 提取耗时(从字段中查找,优先使用毫秒字段)
|
||||
elapsed_str = ""
|
||||
if "elapsed_ms" in fields:
|
||||
elapsed_seconds = float(fields.get("elapsed_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "total_elapsed_ms" in fields:
|
||||
elapsed_seconds = float(fields.get("total_elapsed_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "总耗时毫秒" in fields:
|
||||
elapsed_seconds = float(fields.get("总耗时毫秒", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "seconds" in fields:
|
||||
elapsed_seconds = float(fields.get("seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "elapsed_seconds" in fields:
|
||||
elapsed_seconds = float(fields.get("elapsed_seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
|
||||
# 提取分数(如果有)
|
||||
score_str = ""
|
||||
if "score" in fields and fields.get("score") is not None:
|
||||
try:
|
||||
score_val = float(fields.get("score", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
elif "max_val" in fields and fields.get("max_val") is not None:
|
||||
try:
|
||||
score_val = float(fields.get("max_val", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
elif "分数" in fields:
|
||||
score_field = fields.get("分数")
|
||||
# 允许显示0.0分数,只要不是None
|
||||
if score_field is not None:
|
||||
try:
|
||||
score_val = float(score_field)
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 构建精简的行为日志行,使用运行日志格式:时间 - [GUI] - [标签] 做了什么 耗时:XXs 分数:XX
|
||||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||||
if tag:
|
||||
action_parts.append(tag)
|
||||
else:
|
||||
action_parts.append("[日志]")
|
||||
action_parts.append(action_desc)
|
||||
|
||||
if elapsed_str:
|
||||
action_parts.append(elapsed_str)
|
||||
|
||||
if score_str:
|
||||
action_parts.append(score_str)
|
||||
|
||||
action_log_line = " ".join(action_parts)
|
||||
|
||||
# 写入 actions.log 文件
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 检测标签变化,用====分隔不同步骤
|
||||
# 使用实例变量记录上一个标签
|
||||
if not hasattr(analyser, "_last_action_tag"):
|
||||
analyser._last_action_tag = None
|
||||
|
||||
# 如果标签变化,添加分隔符
|
||||
current_tag = tag or "[日志]"
|
||||
if (
|
||||
analyser._last_action_tag is not None
|
||||
and analyser._last_action_tag != current_tag
|
||||
):
|
||||
# 标签变化,添加分隔符(增加到80个等号)
|
||||
with open(
|
||||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||||
) as f:
|
||||
f.write("=" * 80 + "\n")
|
||||
f.flush()
|
||||
|
||||
# 更新上一个标签
|
||||
analyser._last_action_tag = current_tag
|
||||
|
||||
# 写入日志行
|
||||
with open(
|
||||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||||
) as f:
|
||||
f.write(action_log_line + "\n")
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 同时输出到标准 logging(如果已配置,可选)
|
||||
try:
|
||||
# 确保日志系统已配置
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
# 如果根 logger 没有 handlers,尝试配置日志系统
|
||||
try:
|
||||
import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not hasattr(analyser, "_std_logger") or analyser._std_logger is None:
|
||||
try:
|
||||
from unified_logger import get_unified_logger
|
||||
|
||||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
try:
|
||||
import douyin_logger
|
||||
|
||||
analyser._std_logger = douyin_logger.get_logger("douyin")
|
||||
except Exception:
|
||||
# 如果都失败了,使用根 logger
|
||||
analyser._std_logger = logging.getLogger("douyin.fudai")
|
||||
|
||||
# 使用根 logger 确保日志能写入文件(子 logger 会传播到根 logger)
|
||||
root_logger = logging.getLogger()
|
||||
if root_logger.handlers:
|
||||
# 如果根 logger 有 handlers,使用根 logger 写入(确保能写入文件)
|
||||
# 构建标准 logging 消息(包含调用者信息)
|
||||
std_msg_parts = [f"[{tag}]"]
|
||||
if caller_info:
|
||||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||||
if msg:
|
||||
# 对消息进行敏感信息脱敏
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||||
std_msg_parts.append(masked_msg)
|
||||
except ImportError:
|
||||
std_msg_parts.append(str(msg))
|
||||
|
||||
# 对字段进行敏感信息脱敏
|
||||
masked_fields: Dict[str, Any] = {}
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||||
except ImportError:
|
||||
masked_fields = fields
|
||||
|
||||
for k, v in masked_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(确保能写入文件)
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
if exc_info:
|
||||
root_logger.log(
|
||||
level,
|
||||
log_message,
|
||||
exc_info=exc_info,
|
||||
extra={"caller": caller_info},
|
||||
)
|
||||
else:
|
||||
root_logger.log(level, log_message, extra={"caller": caller_info})
|
||||
elif hasattr(analyser, "_std_logger") and analyser._std_logger:
|
||||
# 如果根 logger 没有 handlers,尝试使用 _std_logger(但通常不会到这里)
|
||||
# 构建标准 logging 消息(包含调用者信息)
|
||||
std_msg_parts = [f"[{tag}]"]
|
||||
if caller_info:
|
||||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||||
if msg:
|
||||
# 对消息进行敏感信息脱敏
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||||
std_msg_parts.append(masked_msg)
|
||||
except ImportError:
|
||||
std_msg_parts.append(str(msg))
|
||||
|
||||
# 对字段进行敏感信息脱敏
|
||||
masked_fields = {}
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||||
except ImportError:
|
||||
masked_fields = fields
|
||||
|
||||
for k, v in masked_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:
|
||||
analyser._std_logger.log(
|
||||
level,
|
||||
log_message,
|
||||
exc_info=exc_info,
|
||||
extra={"caller": caller_info},
|
||||
)
|
||||
else:
|
||||
analyser._std_logger.log(
|
||||
level, log_message, extra={"caller": caller_info}
|
||||
)
|
||||
except Exception:
|
||||
# 如果标准 logging 写入失败,尝试使用根 logger 写入(作为备用)
|
||||
try:
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
# 构建简单的日志消息
|
||||
simple_msg = f"[{tag}] {msg}" if msg else f"[{tag}]"
|
||||
# 直接使用根 logger,它会自动处理子 logger 的传播
|
||||
root_logger.log(level, simple_msg)
|
||||
except Exception:
|
||||
# 如果所有日志写入都失败,至少确保 stdout 输出(已在上面完成)
|
||||
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:
|
||||
# exc_info 应该是 (type, value, traceback) 元组
|
||||
if isinstance(exc_info, tuple) and len(exc_info) == 3:
|
||||
exc_type, exc_value, exc_traceback = exc_info
|
||||
# 确保 exc_value 是 BaseException 实例
|
||||
if isinstance(exc_value, BaseException):
|
||||
tb_str = traceback.format_exception(
|
||||
exc_type, exc_value, exc_traceback
|
||||
)
|
||||
else:
|
||||
# 如果不是异常实例,创建一个包装异常
|
||||
try:
|
||||
# 尝试使用原始值
|
||||
tb_str = traceback.format_exception(
|
||||
exc_type,
|
||||
(
|
||||
BaseException(str(exc_value))
|
||||
if exc_value
|
||||
else BaseException("Unknown error")
|
||||
),
|
||||
exc_traceback,
|
||||
)
|
||||
except Exception:
|
||||
# 如果还是失败,只输出异常信息
|
||||
print(
|
||||
f" 异常类型: {exc_type}, 异常值: {exc_value}",
|
||||
flush=True,
|
||||
)
|
||||
tb_str = []
|
||||
for line in tb_str:
|
||||
print(f" {line.rstrip()}", flush=True)
|
||||
else:
|
||||
# 如果不是标准格式,尝试直接格式化
|
||||
try:
|
||||
tb_str = traceback.format_exception(*exc_info)
|
||||
for line in tb_str:
|
||||
print(f" {line.rstrip()}", flush=True)
|
||||
except Exception:
|
||||
# 如果格式化失败,只输出异常信息
|
||||
print(f" 异常信息: {exc_info}", flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def log_step_time(
|
||||
analyser: Any,
|
||||
step_name: str,
|
||||
start_time: float,
|
||||
extra_info: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
step_name: 步骤名称
|
||||
start_time: 开始时间(时间戳)
|
||||
extra_info: 额外信息字典
|
||||
"""
|
||||
try:
|
||||
elapsed = time.time() - float(start_time or 0.0)
|
||||
except Exception:
|
||||
elapsed = 0.0
|
||||
fields: Dict[str, Any] = {"seconds": elapsed}
|
||||
if extra_info:
|
||||
for k, v in extra_info.items():
|
||||
fields[str(k)] = v
|
||||
try:
|
||||
analyser._log_kv("步骤耗时", step_name, **fields) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
其他功能模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from douyin_fudai import fudai_analyse
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
|
||||
try:
|
||||
from version import print_version_banner
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -4,7 +4,7 @@ import os
|
||||
import time
|
||||
from PIL import Image
|
||||
|
||||
import douyin_pixel
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
|
||||
def check_coupon_popup(analyser) -> bool:
|
||||
@@ -381,7 +381,7 @@ def handle_lottery_result_popup(analyser) -> None:
|
||||
# 如果还有弹窗,尝试再次点击或按返回键
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
import douyin_stage
|
||||
from douyin.stage import douyin_stage
|
||||
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
|
||||
if result is None:
|
||||
stage = "UNKNOWN"
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
预约相关模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,590 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
预约管理模块
|
||||
============
|
||||
|
||||
职责:高价值福袋预约相关操作
|
||||
- 查找预约直播间
|
||||
- 处理预约直接参与
|
||||
- 根据标题查找位置
|
||||
- 记录直播间标题和位置
|
||||
"""
|
||||
|
||||
import time
|
||||
import difflib
|
||||
from typing import Any, Optional, Dict
|
||||
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.reservation import douyin_reservation_verify
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
|
||||
|
||||
class ReservationHandler:
|
||||
"""预约处理器:统一管理预约操作"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def find_room_pos_by_title(
|
||||
analyser: Any, target_title: str, target_title_raw: str = ""
|
||||
) -> Optional[int]:
|
||||
"""根据直播间标题在运行时映射表中查找对应的位置。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
target_title: 目标标题
|
||||
target_title_raw: 目标原始标题
|
||||
|
||||
返回:
|
||||
如果找到匹配的位置,返回位置值;否则返回 None
|
||||
"""
|
||||
try:
|
||||
if not target_title and not target_title_raw:
|
||||
return None
|
||||
|
||||
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
|
||||
if not room_pos_map:
|
||||
return None
|
||||
|
||||
# 规范化目标标题
|
||||
try:
|
||||
from douyin.other import douyin_high_value_room
|
||||
|
||||
if hasattr(douyin_high_value_room, "_normalize_room_title"):
|
||||
target_norm = douyin_high_value_room._normalize_room_title( # type: ignore[attr-defined]
|
||||
target_title
|
||||
)
|
||||
else:
|
||||
target_norm = target_title.strip()
|
||||
except Exception:
|
||||
target_norm = target_title.strip()
|
||||
|
||||
# 遍历映射表查找匹配的标题
|
||||
best_match_pos: Optional[int] = None
|
||||
best_match_score = 0.0
|
||||
|
||||
for pos, (recorded_title, recorded_title_raw) in room_pos_map.items():
|
||||
if not recorded_title and not recorded_title_raw:
|
||||
continue
|
||||
|
||||
# 规范化记录的标题
|
||||
try:
|
||||
from douyin.other import douyin_high_value_room
|
||||
|
||||
if hasattr(douyin_high_value_room, "_normalize_room_title"):
|
||||
recorded_norm = douyin_high_value_room._normalize_room_title( # type: ignore[attr-defined]
|
||||
recorded_title
|
||||
)
|
||||
else:
|
||||
recorded_norm = recorded_title.strip()
|
||||
except Exception:
|
||||
recorded_norm = recorded_title.strip()
|
||||
|
||||
# 计算匹配度
|
||||
match_score = 0.0
|
||||
if target_norm and recorded_norm:
|
||||
# 完全匹配
|
||||
if target_norm == recorded_norm:
|
||||
match_score = 1.0
|
||||
# 子串匹配
|
||||
elif target_norm in recorded_norm or recorded_norm in target_norm:
|
||||
match_score = 0.8
|
||||
# 使用相似度
|
||||
else:
|
||||
try:
|
||||
match_score = difflib.SequenceMatcher(
|
||||
None, target_norm, recorded_norm
|
||||
).ratio()
|
||||
except Exception:
|
||||
match_score = 0.0
|
||||
|
||||
# 如果匹配度足够高,记录最佳匹配
|
||||
if match_score > best_match_score and match_score >= 0.6:
|
||||
best_match_score = match_score
|
||||
best_match_pos = pos
|
||||
|
||||
if best_match_pos is not None:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
|
||||
target_title=target_title[:50] if target_title else "",
|
||||
found_pos=best_match_pos,
|
||||
match_score=round(best_match_score, 3),
|
||||
recorded_title=(
|
||||
room_pos_map[best_match_pos][0][:50]
|
||||
if room_pos_map[best_match_pos][0]
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return best_match_pos
|
||||
|
||||
return None
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] _find_room_pos_by_title:查找时出错",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def record_room_title_and_pos(analyser: Any) -> None:
|
||||
"""记录当前直播间的标题和位置到运行时映射表。
|
||||
|
||||
用于预约回退校验时验证位置信息。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
try:
|
||||
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
|
||||
# 读取当前直播间标题
|
||||
try:
|
||||
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
room_title, room_title_raw = douyin_fudai_detail.read_live_room_title_core(
|
||||
analyser, y_pianyi_val
|
||||
)
|
||||
|
||||
# 更新 analyser 的属性
|
||||
try:
|
||||
analyser.current_room_title = room_title
|
||||
analyser.current_room_title_raw = room_title_raw
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到映射表
|
||||
if room_pos not in analyser._room_pos_to_title_map:
|
||||
analyser._room_pos_to_title_map[room_pos] = (
|
||||
room_title,
|
||||
room_title_raw,
|
||||
)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 记录直播间标题和位置到运行时映射表",
|
||||
room_pos=room_pos,
|
||||
room_title=room_title[:50] if room_title else "",
|
||||
room_title_raw=(
|
||||
room_title_raw[:50] if room_title_raw else ""
|
||||
),
|
||||
map_size=len(analyser._room_pos_to_title_map),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 如果已存在,更新标题(可能标题有变化)
|
||||
old_title, old_title_raw = analyser._room_pos_to_title_map[room_pos]
|
||||
if old_title != room_title or old_title_raw != room_title_raw:
|
||||
analyser._room_pos_to_title_map[room_pos] = (
|
||||
room_title,
|
||||
room_title_raw,
|
||||
)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 更新直播间标题和位置到运行时映射表",
|
||||
room_pos=room_pos,
|
||||
old_room_title=old_title[:50] if old_title else "",
|
||||
new_room_title=room_title[:50] if room_title else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 如果读取标题失败,尝试使用缓存的标题
|
||||
try:
|
||||
room_title = str(
|
||||
getattr(analyser, "current_room_title", "") or ""
|
||||
)
|
||||
room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "") or ""
|
||||
)
|
||||
if room_title or room_title_raw:
|
||||
analyser._room_pos_to_title_map[room_pos] = (
|
||||
room_title,
|
||||
room_title_raw,
|
||||
)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 使用缓存标题记录直播间位置到运行时映射表",
|
||||
room_pos=room_pos,
|
||||
room_title=room_title[:50] if room_title else "",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def seek_reservation_room(analyser: Any, item: Dict[str, Any]) -> bool:
|
||||
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
|
||||
|
||||
说明:
|
||||
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
|
||||
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
item: 预约记录字典
|
||||
|
||||
返回:
|
||||
bool: 是否成功回退到目标直播间
|
||||
"""
|
||||
try:
|
||||
target_pos = int(item.get("pos_seen") or 0)
|
||||
except Exception:
|
||||
target_pos = 0
|
||||
try:
|
||||
cur_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
except Exception:
|
||||
cur_pos = 0
|
||||
|
||||
# 计算需要切换的次数和方向
|
||||
pos_diff = target_pos - cur_pos
|
||||
|
||||
try:
|
||||
max_back = int(
|
||||
getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60
|
||||
)
|
||||
except Exception:
|
||||
max_back = 60
|
||||
# 防止无限循环:最大回退次数限制为100
|
||||
if max_back > 100:
|
||||
max_back = 100
|
||||
if max_back < 0:
|
||||
max_back = 0
|
||||
|
||||
# 获取目标直播间名字
|
||||
target_room_title = str(item.get("room_title") or "").strip()
|
||||
target_room_title_raw = str(item.get("room_title_raw") or "").strip()
|
||||
|
||||
# 输出目标直播间的位置和标题信息
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] _seek_reservation_room:开始回退到目标直播间",
|
||||
target_room_title=target_room_title,
|
||||
target_room_title_raw=target_room_title_raw,
|
||||
target_pos=target_pos,
|
||||
current_room_pos=cur_pos,
|
||||
target_room_info=(
|
||||
f"位置={target_pos}, "
|
||||
f"标题={target_room_title or target_room_title_raw}"
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if pos_diff == 0:
|
||||
# 已在目标位置,但仍需校验
|
||||
pass
|
||||
elif pos_diff < 0:
|
||||
# 目标在上方(target_pos < cur_pos),需要向上回退(减少 room_pos)
|
||||
back_times = (
|
||||
min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
|
||||
)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] _seek_reservation_room 向上回退(目标在上方)",
|
||||
back_times=back_times,
|
||||
current_room_pos=cur_pos,
|
||||
target_pos=target_pos,
|
||||
pos_diff=pos_diff,
|
||||
target_room_title=target_room_title,
|
||||
target_room_title_raw=target_room_title_raw,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
delay_s = float(
|
||||
getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6
|
||||
)
|
||||
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = True
|
||||
except Exception:
|
||||
pass
|
||||
for _ in range(back_times):
|
||||
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(analyser)
|
||||
try:
|
||||
analyser.operation.delay(delay_s)
|
||||
except Exception:
|
||||
time.sleep(delay_s)
|
||||
# 清除标志
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = False
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 目标在下方(target_pos > cur_pos),需要向下切换(增加 room_pos)
|
||||
forward_times = min(pos_diff, max_back) if max_back > 0 else pos_diff
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] _seek_reservation_room 向下切换(目标在下方)",
|
||||
forward_times=forward_times,
|
||||
current_room_pos=cur_pos,
|
||||
target_pos=target_pos,
|
||||
pos_diff=pos_diff,
|
||||
target_room_title=target_room_title,
|
||||
target_room_title_raw=target_room_title_raw,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
delay_s = float(
|
||||
getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6
|
||||
)
|
||||
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = True
|
||||
except Exception:
|
||||
pass
|
||||
for _ in range(forward_times):
|
||||
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(analyser)
|
||||
try:
|
||||
analyser.operation.delay(delay_s)
|
||||
except Exception:
|
||||
time.sleep(delay_s)
|
||||
# 清除标志
|
||||
try:
|
||||
analyser._skip_record_title_during_seek = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退过程中只执行回退操作,不进行校验
|
||||
# 校验将在 process_reservation_attend_window 中统一进行,使用映射表中的数据
|
||||
return True
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:使用预约记录中的详情,跳过OCR识别",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 从预约记录中获取详情信息
|
||||
if not analyser.reservations or len(analyser.reservations) == 0:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:预约队列为空,无法获取详情",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果预约队列为空,回退到正常流程
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
first_reservation = analyser.reservations[0]
|
||||
try:
|
||||
# 从预约记录中获取信息
|
||||
content = str(first_reservation.get("content", "") or "")
|
||||
prize_value_yuan = float(
|
||||
first_reservation.get("prize_value_yuan", 0.0) or 0.0
|
||||
)
|
||||
future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0)
|
||||
time_text = str(first_reservation.get("time_text", "") or "")
|
||||
participants = int(first_reservation.get("participants", 0) or 0)
|
||||
copies = int(first_reservation.get("copies", 0) or 0)
|
||||
|
||||
# 检查福袋是否已过期
|
||||
now_ts = time.time()
|
||||
poll_before = float(
|
||||
getattr(analyser, "high_value_fudai_poll_before_seconds", 10.0) or 10.0
|
||||
)
|
||||
expired_threshold = future_ts + max(0.0, poll_before) # 开奖时间 + 缓冲时间
|
||||
|
||||
if future_ts > 0 and now_ts > expired_threshold:
|
||||
# 福袋已过期,清除标志并退出
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
future_str = (
|
||||
datetime.fromtimestamp(future_ts).strftime("%Y-%m-%d %H:%M:%S")
|
||||
if future_ts > 0
|
||||
else "无效"
|
||||
)
|
||||
expired_seconds = int(now_ts - expired_threshold)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:福袋已过期,清除标志并退出",
|
||||
future_ts=int(future_ts),
|
||||
future_str=future_str,
|
||||
expired_threshold=int(expired_threshold),
|
||||
expired_seconds=expired_seconds,
|
||||
now_ts=int(now_ts),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 清除相关标志
|
||||
analyser._reservation_back_direct_attend = False
|
||||
analyser._force_attend_after_reservation_back = False
|
||||
analyser.queue_full_waiting_at_earliest = False
|
||||
|
||||
# 从预约队列中移除过期预约
|
||||
try:
|
||||
douyin_reservation_logic.cleanup_expired_reservations(
|
||||
analyser=analyser,
|
||||
reservations=analyser.reservations,
|
||||
write_state_callback=lambda: None, # 暂时不写入,避免重复写入
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return
|
||||
|
||||
# 构造倒计时元组
|
||||
countdown_start = now_ts
|
||||
countdown_end = future_ts if future_ts > 0 else (now_ts + 60.0)
|
||||
|
||||
# 构造 detail tuple(格式与 read_fudai_detail_once 返回的格式一致)
|
||||
detail = (
|
||||
content, # 0: 内容
|
||||
time_text, # 1: 倒计时文本
|
||||
participants, # 2: 参与人数
|
||||
copies, # 3: 份数
|
||||
prize_value_yuan, # 4: 价值
|
||||
(countdown_start, countdown_end), # 5: 倒计时元组
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:从预约记录构造详情",
|
||||
content=content[:50] if content else "",
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
future_ts=int(future_ts) if future_ts > 0 else 0,
|
||||
time_text=time_text,
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存详情数据,标记为已读取(用于后续可能的第二次打开)
|
||||
analyser._last_fudai_detail_tuple = detail
|
||||
analyser._fudai_detail_first_read = True
|
||||
|
||||
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
|
||||
analyser._current_fudai_future_ts = future_ts
|
||||
|
||||
# 直接调用参与决策,跳过详情识别
|
||||
join_result = douyin_fudai_core.basic_join_decision(analyser, detail)
|
||||
|
||||
# 如果参与成功,设置开奖等待状态并从预约队列中移除
|
||||
if join_result and future_ts > 0:
|
||||
try:
|
||||
# 设置开奖等待状态
|
||||
current_time = time.time()
|
||||
remain_seconds = max(0, future_ts - current_time)
|
||||
if remain_seconds > 0:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts - 13.0
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后参与成功,设置开奖等待状态",
|
||||
remain_seconds=int(remain_seconds),
|
||||
future_ts=int(future_ts),
|
||||
lottery_result_expected_ts=int(
|
||||
analyser._lottery_result_expected_ts
|
||||
),
|
||||
)
|
||||
|
||||
# 设置锁定期,防止过早切换直播间
|
||||
poll_before = float(
|
||||
getattr(
|
||||
analyser, "high_value_fudai_poll_before_seconds", 10.0
|
||||
)
|
||||
or 10.0
|
||||
)
|
||||
analyser.reservation_focus_until_ts = future_ts + max(
|
||||
0.0, poll_before
|
||||
)
|
||||
|
||||
# 从预约队列中移除已参与的预约
|
||||
if analyser.reservations and len(analyser.reservations) > 0:
|
||||
remaining_reservations = []
|
||||
for res in analyser.reservations:
|
||||
try:
|
||||
res_future_ts = float(res.get("future_ts") or 0.0)
|
||||
if (
|
||||
res_future_ts > 0
|
||||
and abs(res_future_ts - future_ts) <= 5.0
|
||||
):
|
||||
# 匹配的预约,移除
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后参与成功,从预约队列中移除该预约",
|
||||
future_ts=int(res_future_ts),
|
||||
value_yuan=res.get("prize_value_yuan", 0),
|
||||
content=(
|
||||
res.get("content", "")[:50]
|
||||
if res.get("content")
|
||||
else ""
|
||||
),
|
||||
)
|
||||
else:
|
||||
# 保留不匹配的预约
|
||||
remaining_reservations.append(res)
|
||||
except Exception:
|
||||
# 如果解析预约项时出错,保留该项(容错处理)
|
||||
remaining_reservations.append(res)
|
||||
|
||||
if len(remaining_reservations) < len(analyser.reservations):
|
||||
analyser.reservations = remaining_reservations
|
||||
|
||||
# 清除预约回退直接参与标志
|
||||
analyser._reservation_back_direct_attend = False
|
||||
analyser.reservation_after_action_pending = False
|
||||
except Exception as e:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后参与成功,设置状态时出错",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_reservation_direct_attend完成",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
join_result=join_result,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 预约回退后直接参与:从预约记录获取详情时出错,回退到正常流程",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果出错,回退到正常流程
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
|
||||
@@ -585,7 +585,7 @@ def handle_queue_full_wait_at_earliest(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import douyin_stage
|
||||
from douyin.stage import douyin_stage
|
||||
|
||||
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
|
||||
if result is None:
|
||||
File renamed without changes.
@@ -15,7 +15,7 @@ import re
|
||||
import difflib
|
||||
import time
|
||||
|
||||
import douyin_fudai_detail
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
|
||||
|
||||
def _compact_text(text: str) -> str:
|
||||
@@ -196,7 +196,7 @@ def validate_back_to_reservation(
|
||||
# 先用"直播间名"做一次快速判断:不匹配则大概率回错房间,优先驱动微调继续找
|
||||
try:
|
||||
# 使用 douyin_high_value_room 中的规范化函数
|
||||
import douyin_high_value_room
|
||||
from douyin.other import douyin_high_value_room
|
||||
if hasattr(douyin_high_value_room, '_normalize_room_title'):
|
||||
expected_title = douyin_high_value_room._normalize_room_title(item.get("room_title") or "") # type: ignore[attr-defined]
|
||||
else:
|
||||
@@ -236,7 +236,7 @@ def validate_back_to_reservation(
|
||||
# 如果映射表中的标题与预期标题匹配,增强验证信心
|
||||
if expected_title and recorded_title:
|
||||
try:
|
||||
import douyin_high_value_room
|
||||
from douyin.other import douyin_high_value_room
|
||||
if hasattr(douyin_high_value_room, '_normalize_room_title'):
|
||||
expected_norm = douyin_high_value_room._normalize_room_title(expected_title) # type: ignore[attr-defined]
|
||||
recorded_norm = douyin_high_value_room._normalize_room_title(recorded_title) # type: ignore[attr-defined]
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
阶段处理模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import douyin_pixel
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
|
||||
def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C901
|
||||
@@ -699,7 +699,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
y_pianyi = int(getattr(self, "y_pianyi", 0) or 0)
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
import path_config
|
||||
import os
|
||||
from PIL import Image
|
||||
@@ -0,0 +1,407 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
阶段处理模块
|
||||
============
|
||||
|
||||
职责:处理不同阶段的业务逻辑
|
||||
- 处理福袋详情页
|
||||
- 处理直播间福袋检测
|
||||
- 直播间图标检测
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Tuple, List, Optional
|
||||
|
||||
from douyin.stage import douyin_stage
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
from douyin.core import douyin_flow_control
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
|
||||
|
||||
class StageHandler:
|
||||
"""阶段处理器:统一管理阶段处理"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def diagnose_stage_from_current_screen(analyser: Any) -> Tuple[str, str]:
|
||||
"""封装到子模块的阶段诊断入口。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
Tuple[str, str]: (阶段, 识别结果)
|
||||
"""
|
||||
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
|
||||
if result is None:
|
||||
return ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
|
||||
return result
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def check_in_live_room_by_icon(analyser: Any) -> Tuple[bool, float]:
|
||||
"""通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
Tuple[bool, float]: (detected, score) 其中 score 为匹配得分(0.0~1.0)
|
||||
"""
|
||||
# 为了兼容没有 cv2/numpy 的环境,这里做降级处理
|
||||
try:
|
||||
import cv2 # type: ignore[import-untyped, attr-defined]
|
||||
import numpy as np # type: ignore
|
||||
import os
|
||||
|
||||
# 抑制OpenCV的文件读取警告
|
||||
os.environ["OPENCV_LOG_LEVEL"] = "ERROR"
|
||||
try:
|
||||
cv2.setLogLevel(0) # type: ignore[attr-defined] # 0 = SILENT
|
||||
except (AttributeError, Exception):
|
||||
try:
|
||||
if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"):
|
||||
cv2.utils.logging.setLogLevel( # type: ignore[attr-defined]
|
||||
cv2.utils.logging.LOG_LEVEL_SILENT # type: ignore[attr-defined]
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.getLogger("cv2").setLevel(logging.ERROR)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断",
|
||||
"_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
assets_dir = os.path.join(base_dir, "assets")
|
||||
screenshot_path = os.path.join(pic_dir, "screenshot.png")
|
||||
|
||||
# 确保有最新截图
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not os.path.exists(screenshot_path):
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断",
|
||||
"_check_in_live_room_by_icon 截图不存在",
|
||||
path=screenshot_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
try:
|
||||
img = cv2.imread( # type: ignore[attr-defined]
|
||||
screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||||
)
|
||||
if img is None:
|
||||
raise RuntimeError("cv2.imread 返回 None")
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
# 获取可配置的匹配阈值
|
||||
threshold = float(
|
||||
getattr(analyser, "live_room_match_threshold", 0.8) or 0.8
|
||||
)
|
||||
template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90%
|
||||
threshold = max(0.0, min(1.0, threshold))
|
||||
template_threshold = max(0.0, min(1.0, template_threshold))
|
||||
|
||||
# 第一步:裁剪右上角图标区域
|
||||
ih, iw = img.shape[:2]
|
||||
roi_x1 = max(0, int(iw * 0.60))
|
||||
roi_y1 = 0
|
||||
roi_x2 = iw
|
||||
roi_y2 = min(ih, int(ih * 0.40))
|
||||
roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index]
|
||||
|
||||
if roi.size == 0:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", "_check_in_live_room_by_icon ROI区域为空"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
# 保存裁剪的ROI区域
|
||||
ocr_dir = os.path.join(pic_dir, "ocr")
|
||||
os.makedirs(ocr_dir, exist_ok=True)
|
||||
x_roi_path = os.path.join(ocr_dir, "xx.png")
|
||||
xin_roi_path = os.path.join(ocr_dir, "xxin.png")
|
||||
|
||||
try:
|
||||
cv2.imwrite(x_roi_path, roi) # type: ignore[attr-defined]
|
||||
cv2.imwrite(xin_roi_path, roi) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", "_check_in_live_room_by_icon 保存ROI失败", error=str(e)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 第二步:使用模板匹配
|
||||
template_roi_pairs = [
|
||||
(os.path.join(assets_dir, "x.png"), x_roi_path, "x"),
|
||||
(os.path.join(assets_dir, "xin.png"), xin_roi_path, "xin"),
|
||||
]
|
||||
|
||||
best_score = 0.0
|
||||
best_name = ""
|
||||
detected = False
|
||||
|
||||
for template_path, roi_path, icon_name in template_roi_pairs:
|
||||
try:
|
||||
if not os.path.exists(template_path) or not os.path.isfile(
|
||||
template_path
|
||||
):
|
||||
continue
|
||||
try:
|
||||
if os.path.getsize(template_path) == 0:
|
||||
continue
|
||||
except (OSError, IOError):
|
||||
continue
|
||||
|
||||
if not os.path.exists(roi_path) or not os.path.isfile(roi_path):
|
||||
continue
|
||||
|
||||
try:
|
||||
tpl = cv2.imread( # type: ignore[attr-defined]
|
||||
template_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||||
)
|
||||
roi_img = cv2.imread( # type: ignore[attr-defined]
|
||||
roi_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if tpl is None or roi_img is None:
|
||||
continue
|
||||
|
||||
th, tw = tpl.shape[:2]
|
||||
rh, rw = roi_img.shape[:2]
|
||||
|
||||
# 模板必须小于或等于ROI
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale <= 0:
|
||||
continue
|
||||
tpl = cv2.resize( # type: ignore[attr-defined]
|
||||
tpl, (max(1, int(tw * scale)), max(1, int(th * scale)))
|
||||
)
|
||||
th, tw = tpl.shape[:2]
|
||||
|
||||
# 在ROI中匹配模板
|
||||
res = cv2.matchTemplate( # type: ignore[attr-defined]
|
||||
roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
|
||||
)
|
||||
_min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc( # type: ignore[attr-defined]
|
||||
res
|
||||
)
|
||||
|
||||
if max_val > best_score:
|
||||
best_score = float(max_val or 0.0)
|
||||
best_name = (
|
||||
f"assets/{icon_name}.png -> "
|
||||
f"ocr/{'xx' if icon_name == 'x' else 'xxin'}.png"
|
||||
)
|
||||
|
||||
if max_val >= template_threshold:
|
||||
detected = True
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if not detected and best_score == 0.0:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断",
|
||||
"_check_in_live_room_by_icon 结果",
|
||||
detected=int(bool(detected)),
|
||||
score=round(best_score, 3),
|
||||
template=best_name or "-",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return bool(detected), float(best_score or 0.0)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_in_fudai_detail(analyser: Any) -> None:
|
||||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
# 这个方法非常长,直接调用原方法,保持兼容性
|
||||
# 注意:由于方法过于复杂(900+行),暂时保持原实现
|
||||
# 后续可以进一步拆分
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_live_room_has_or_not_fudai(analyser: Any) -> None:
|
||||
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
|
||||
try:
|
||||
already_verified = bool(
|
||||
getattr(analyser, "_fudai_detail_verified", False) or False
|
||||
)
|
||||
if already_verified:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 直接调用详情处理逻辑,不查找福袋
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_live_room_has_or_not_fudai完成(已验证详情页)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
|
||||
try:
|
||||
now_ts = time.time()
|
||||
focus_until = float(
|
||||
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
|
||||
)
|
||||
queue_full_waiting = bool(
|
||||
getattr(analyser, "queue_full_waiting_at_earliest", False) or False
|
||||
)
|
||||
|
||||
if focus_until > 0 and now_ts < focus_until and queue_full_waiting:
|
||||
if analyser.reservations and len(analyser.reservations) > 0:
|
||||
earliest = analyser.reservations[0]
|
||||
try:
|
||||
ft = float(earliest.get("future_ts") or 0.0)
|
||||
if ft > 0:
|
||||
join_ahead = float(
|
||||
getattr(
|
||||
analyser, "high_value_fudai_join_ahead_seconds", 120
|
||||
)
|
||||
or 120
|
||||
)
|
||||
poll_before = float(
|
||||
getattr(analyser, "poll_before_open_seconds", 10.0)
|
||||
or 10.0
|
||||
)
|
||||
time_window_start_ts = ft - join_ahead
|
||||
time_window_end_ts = ft + max(0.0, poll_before)
|
||||
|
||||
if now_ts < time_window_start_ts:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 锁定期内时间窗口未到,避免重复打开福袋详情",
|
||||
focus_until=int(focus_until),
|
||||
now_ts=int(now_ts),
|
||||
time_window_start=int(time_window_start_ts),
|
||||
remain_seconds=int(
|
||||
time_window_start_ts - now_ts
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
room_pos_ref: List[int] = [0]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref)
|
||||
if not opened:
|
||||
# 无福袋,交给 flow_control 的"无福袋处理"逻辑
|
||||
try:
|
||||
needswitch_cfg = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch_cfg = True
|
||||
|
||||
wait_times_ref = [0]
|
||||
swipe_times_ref = [0]
|
||||
reservation_focus_until_ts_ref = [0.0]
|
||||
reset_to_list_after_reservations_ref = [False]
|
||||
douyin_flow_control.handle_no_fudai_situation(
|
||||
analyser,
|
||||
x=0,
|
||||
swipe_times=0,
|
||||
wait_times_ref=wait_times_ref,
|
||||
needswitch=needswitch_cfg,
|
||||
reservation_focus_until_ts=0.0,
|
||||
reservations=[],
|
||||
room_pos=room_pos_ref[0],
|
||||
post_switch_delay_s=1.5,
|
||||
swipe_up_switch_callback=analyser.swipe_up_to_next_live, # type: ignore[attr-defined]
|
||||
swipe_down_back_callback=lambda: None,
|
||||
sort_reservations_callback=lambda: None,
|
||||
clear_reservations_callback=lambda: None,
|
||||
write_state_callback=lambda: None,
|
||||
back_to_list_callback=lambda: None,
|
||||
into_list_callback=lambda: None,
|
||||
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
|
||||
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
|
||||
swipe_times_ref=swipe_times_ref,
|
||||
)
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_live_room_has_or_not_fudai完成(无福袋)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return
|
||||
|
||||
# 成功打开详情:调用同一套详情处理逻辑
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_live_room_has_or_not_fudai完成(成功打开详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
工具函数模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
配置管理模块
|
||||
============
|
||||
|
||||
负责从 config.json 加载配置并设置到 analyser 对象
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
"""配置管理器类"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def load_config_from_file(
|
||||
analyser: Any, config_path: Optional[str] = None
|
||||
) -> None:
|
||||
"""从配置文件加载配置并设置到 analyser 对象
|
||||
|
||||
参数:
|
||||
analyser: fudai_analyse 实例
|
||||
config_path: 配置文件路径,如果为 None 则使用 analyser.config_path
|
||||
"""
|
||||
if config_path is None:
|
||||
config_path = getattr(analyser, "config_path", "config/config.json")
|
||||
|
||||
# 如果 config_path 仍然为 None,直接返回(使用默认值)
|
||||
if config_path is None:
|
||||
return
|
||||
|
||||
# 如果配置文件不存在,直接返回(使用默认值)
|
||||
if not os.path.exists(config_path):
|
||||
return
|
||||
|
||||
try:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
except (json.JSONDecodeError, IOError, OSError):
|
||||
# 如果 JSON 解析失败或文件读取失败,直接返回(使用默认值)
|
||||
return
|
||||
|
||||
# 保存 needswitch 的原始值(如果已通过命令行设置,则保留)
|
||||
original_needswitch = getattr(analyser, "needswitch", None)
|
||||
|
||||
# 加载基本配置
|
||||
if "min_prize_value_yuan" in config:
|
||||
analyser.min_prize_value_yuan = float(config["min_prize_value_yuan"] or 0.0)
|
||||
|
||||
if "min_participants" in config:
|
||||
analyser.min_participants = int(config["min_participants"] or 0)
|
||||
|
||||
if "max_participants" in config:
|
||||
analyser.max_participants = int(config["max_participants"] or 0)
|
||||
|
||||
if "skip_if_countdown_gt_seconds" in config:
|
||||
analyser.skip_if_countdown_gt_seconds = int(
|
||||
config["skip_if_countdown_gt_seconds"] or 900
|
||||
)
|
||||
|
||||
if "skip_if_countdown_lt_seconds" in config:
|
||||
analyser.skip_if_countdown_lt_seconds = int(
|
||||
config["skip_if_countdown_lt_seconds"] or 0
|
||||
)
|
||||
|
||||
if "fudai_icon_max_wait_seconds" in config:
|
||||
analyser.fudai_icon_max_wait_seconds = float(
|
||||
config["fudai_icon_max_wait_seconds"] or 5.0
|
||||
)
|
||||
|
||||
if "fudai_icon_retry_delay_seconds" in config:
|
||||
analyser.fudai_icon_retry_delay_seconds = float(
|
||||
config["fudai_icon_retry_delay_seconds"] or 0.6
|
||||
)
|
||||
|
||||
# 高价值福袋配置
|
||||
if "high_value_fudai_enabled" in config:
|
||||
analyser.high_value_fudai_enabled = bool(
|
||||
config["high_value_fudai_enabled"]
|
||||
)
|
||||
|
||||
if "high_value_fudai_threshold_yuan" in config:
|
||||
analyser.high_value_fudai_threshold_yuan = float(
|
||||
config["high_value_fudai_threshold_yuan"] or 500.0
|
||||
)
|
||||
|
||||
if "high_value_fudai_max_reservations" in config:
|
||||
max_reservations = int(config["high_value_fudai_max_reservations"] or 3)
|
||||
# 限制最大预约数量为50
|
||||
analyser.high_value_fudai_max_reservations = min(max_reservations, 50)
|
||||
|
||||
# needswitch 配置(如果已通过命令行设置,则保留原值)
|
||||
if original_needswitch is not None:
|
||||
# 保留命令行参数值(优先级最高)
|
||||
analyser.needswitch = original_needswitch
|
||||
elif "needswitch" in config:
|
||||
# 从配置文件读取
|
||||
analyser.needswitch = bool(config["needswitch"])
|
||||
else:
|
||||
# 如果配置文件中没有,使用默认值 True
|
||||
analyser.needswitch = True
|
||||
|
||||
# 列表配置
|
||||
if "contains_not_want" in config:
|
||||
analyser.contains_not_want = list(config["contains_not_want"] or [])
|
||||
|
||||
if "contains_want" in config:
|
||||
analyser.contains_want = list(config["contains_want"] or [])
|
||||
|
||||
# 阈值配置(限制在 0.0~1.0 范围内)
|
||||
if "lucky_draw_red_ratio_threshold" in config:
|
||||
threshold = float(config["lucky_draw_red_ratio_threshold"] or 0.9)
|
||||
analyser.lucky_draw_red_ratio_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "coupon_template_match_threshold" in config:
|
||||
threshold = float(config["coupon_template_match_threshold"] or 0.75)
|
||||
analyser.coupon_template_match_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "attend_button_red_ratio_threshold" in config:
|
||||
threshold = float(config["attend_button_red_ratio_threshold"] or 0.25)
|
||||
analyser.attend_button_red_ratio_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "fansclub_join_red_ratio_threshold" in config:
|
||||
threshold = float(config["fansclub_join_red_ratio_threshold"] or 0.25)
|
||||
analyser.fansclub_join_red_ratio_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
# 其他配置项(根据实际需要添加)
|
||||
if "no_attend_timeout_minutes" in config:
|
||||
analyser._no_attend_timeout_minutes = float(
|
||||
config["no_attend_timeout_minutes"] or 30.0
|
||||
)
|
||||
|
||||
if "auto_join_fansclub" in config:
|
||||
analyser.auto_join_fansclub = bool(config["auto_join_fansclub"])
|
||||
|
||||
if "fansclub_fail_action" in config:
|
||||
analyser.fansclub_fail_action = str(config["fansclub_fail_action"] or "stay")
|
||||
|
||||
if "high_value_fudai_join_ahead_seconds" in config:
|
||||
analyser.high_value_fudai_join_ahead_seconds = int(
|
||||
config["high_value_fudai_join_ahead_seconds"] or 120
|
||||
)
|
||||
|
||||
if "high_value_fudai_max_swipe_back" in config:
|
||||
analyser.high_value_fudai_max_swipe_back = int(
|
||||
config["high_value_fudai_max_swipe_back"] or 35
|
||||
)
|
||||
|
||||
if "high_value_fudai_after_action" in config:
|
||||
analyser.high_value_fudai_after_action = str(
|
||||
config["high_value_fudai_after_action"] or "continue"
|
||||
)
|
||||
|
||||
if "high_value_fudai_after_stay_seconds" in config:
|
||||
analyser.high_value_fudai_after_stay_seconds = int(
|
||||
config["high_value_fudai_after_stay_seconds"] or 120
|
||||
)
|
||||
|
||||
if "reservation_back_verify_enabled" in config:
|
||||
analyser.reservation_back_verify_enabled = bool(
|
||||
config["reservation_back_verify_enabled"]
|
||||
)
|
||||
|
||||
if "reservation_back_swipe_delay" in config:
|
||||
analyser.reservation_back_swipe_delay = float(
|
||||
config["reservation_back_swipe_delay"] or 0.6
|
||||
)
|
||||
|
||||
if "reservation_preempt_min_value_yuan" in config:
|
||||
analyser.reservation_preempt_min_value_yuan = float(
|
||||
config["reservation_preempt_min_value_yuan"] or 0.0
|
||||
)
|
||||
|
||||
if "poll_before_open_seconds" in config:
|
||||
analyser.poll_before_open_seconds = int(
|
||||
config["poll_before_open_seconds"] or 10
|
||||
)
|
||||
|
||||
if "reset_after_swipes_enabled" in config:
|
||||
analyser.reset_after_swipes_enabled = bool(
|
||||
config["reset_after_swipes_enabled"]
|
||||
)
|
||||
|
||||
if "reset_after_swipes" in config:
|
||||
analyser.reset_after_swipes = int(config["reset_after_swipes"] or 10)
|
||||
|
||||
if "fudai_click_wait_seconds" in config:
|
||||
analyser.fudai_click_wait_seconds = float(
|
||||
config["fudai_click_wait_seconds"] or 2.0
|
||||
)
|
||||
|
||||
if "switch_room_wait_after_stage_diag_seconds" in config:
|
||||
analyser.switch_room_wait_after_stage_diag_seconds = float(
|
||||
config["switch_room_wait_after_stage_diag_seconds"] or 7.0
|
||||
)
|
||||
|
||||
if "swipe_duration_ms" in config:
|
||||
analyser.swipe_duration_ms = int(config["swipe_duration_ms"] or 600)
|
||||
|
||||
if "fudai_finder_optimized_enabled" in config:
|
||||
analyser.fudai_finder_optimized_enabled = bool(
|
||||
config["fudai_finder_optimized_enabled"]
|
||||
)
|
||||
|
||||
if "fudai_click_verify_enabled" in config:
|
||||
analyser.fudai_click_verify_enabled = bool(
|
||||
config["fudai_click_verify_enabled"]
|
||||
)
|
||||
|
||||
if "fudai_find_max_retries" in config:
|
||||
analyser.fudai_find_max_retries = int(config["fudai_find_max_retries"] or 3)
|
||||
|
||||
if "screenshot_diagnose_min_interval_seconds" in config:
|
||||
analyser.screenshot_diagnose_min_interval_seconds = float(
|
||||
config["screenshot_diagnose_min_interval_seconds"] or 8.0
|
||||
)
|
||||
|
||||
if "live_room_match_threshold" in config:
|
||||
threshold = float(config["live_room_match_threshold"] or 0.8)
|
||||
analyser.live_room_match_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "fudai_template_match_enabled" in config:
|
||||
analyser.fudai_template_match_enabled = bool(
|
||||
config["fudai_template_match_enabled"]
|
||||
)
|
||||
|
||||
if "fudai_template_match_threshold" in config:
|
||||
threshold = float(config["fudai_template_match_threshold"] or 0.7)
|
||||
analyser.fudai_template_match_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "y_pianyi" in config:
|
||||
analyser.y_pianyi = int(config["y_pianyi"] or 0)
|
||||
@@ -0,0 +1,299 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
工具方法模块
|
||||
============
|
||||
|
||||
职责:通用工具方法
|
||||
- 点击操作封装
|
||||
- OCR检查开奖结果
|
||||
- 处理开奖结果
|
||||
- 截图并诊断
|
||||
- 读取像素阶段状态
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import shutil
|
||||
from typing import Any, Optional, Tuple, Dict, Union
|
||||
from datetime import datetime
|
||||
|
||||
from douyin.detection import douyin_pixel
|
||||
from douyin.handlers import douyin_screenshot_handler
|
||||
|
||||
|
||||
class HelperFunctions:
|
||||
"""工具函数集合:通用工具方法"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def click(analyser: Any, x: int, y: int) -> None:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
x: X坐标
|
||||
y: Y坐标
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, int(x), int(y))
|
||||
elapsed = time.time() - start_time
|
||||
if elapsed > 0.1: # 只记录耗时较长的点击操作
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"操作",
|
||||
"点击操作",
|
||||
x=int(x),
|
||||
y=int(y),
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def read_pixel_stage_state(
|
||||
analyser: Any, return_details: bool = False
|
||||
) -> Union[Dict[str, Any], Tuple[Dict[str, Any], Dict[str, Any]]]:
|
||||
"""读取像素阶段状态(用于阶段诊断)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||||
|
||||
返回:
|
||||
dict: 检测结果(return_details=False时)
|
||||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 获取分辨率比例和y偏移参数
|
||||
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
lucky_threshold = float(
|
||||
getattr(analyser, "lucky_draw_red_ratio_threshold", 0.9) or 0.9
|
||||
)
|
||||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||||
fudai_template_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None)
|
||||
or getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
if fudai_template_threshold < 0.0:
|
||||
fudai_template_threshold = 0.0
|
||||
if fudai_template_threshold > 1.0:
|
||||
fudai_template_threshold = 1.0
|
||||
return douyin_pixel.read_pixel_stage_state_from_screenshot(
|
||||
pic_path,
|
||||
resolution_ratio_x,
|
||||
resolution_ratio_y,
|
||||
y_pianyi,
|
||||
lucky_threshold,
|
||||
fudai_template_threshold,
|
||||
return_details=return_details,
|
||||
analyser=analyser,
|
||||
)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def check_lottery_result_by_ocr(analyser: Any) -> Optional[str]:
|
||||
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
"我知道了" - 识别到"我知道了"按钮
|
||||
"立即领取奖品" - 识别到"立即领取奖品"按钮
|
||||
None - 未识别到相关文本
|
||||
"""
|
||||
try:
|
||||
# OCR区域:(175, 1267) 到 (890, 1377)
|
||||
# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)
|
||||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||||
analyser, 175, 1267, 890, 1377, "", "开奖结果按钮", 0
|
||||
)
|
||||
|
||||
# OCR识别
|
||||
ocr_text = str(analyser.operation.analyse_pic_word("开奖结果按钮", 0) or "")
|
||||
|
||||
analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined]
|
||||
|
||||
# 检查识别到的文本
|
||||
if "我知道了" in ocr_text:
|
||||
return "我知道了"
|
||||
elif (
|
||||
"立即领取奖品" in ocr_text
|
||||
or "领取奖品" in ocr_text
|
||||
or "立即领取" in ocr_text
|
||||
):
|
||||
return "立即领取奖品"
|
||||
else:
|
||||
# 尝试模式1识别
|
||||
ocr_text_1 = str(
|
||||
analyser.operation.analyse_pic_word("开奖结果按钮", 1) or ""
|
||||
)
|
||||
if "我知道了" in ocr_text_1:
|
||||
return "我知道了"
|
||||
elif (
|
||||
"立即领取奖品" in ocr_text_1
|
||||
or "领取奖品" in ocr_text_1
|
||||
or "立即领取" in ocr_text_1
|
||||
):
|
||||
return "立即领取奖品"
|
||||
|
||||
return None
|
||||
except Exception as e:
|
||||
analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined]
|
||||
return None
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_lottery_result_by_ocr(analyser: Any, result_type: str) -> None:
|
||||
"""根据OCR识别结果处理开奖结果。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
result_type: "我知道了" 或 "立即领取奖品"
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
if result_type == "我知道了":
|
||||
# 识别到"我知道了",点击按钮,切换下一个直播间
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
# 按钮位置在OCR区域中心附近 (175+890)/2=532, (1267+1377)/2=1322
|
||||
btn_x = int(532 * rx // 1080)
|
||||
btn_y = int(1322 * ry // 2400)
|
||||
|
||||
analyser.operation.click(analyser.device_id, btn_x, btn_y)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "点击我知道了按钮", x=btn_x, y=btn_y
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
|
||||
# 切换下一个直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
|
||||
if needswitch:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
|
||||
)
|
||||
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果",
|
||||
"处理完开奖结果,未启用切换,继续在当前直播间",
|
||||
)
|
||||
|
||||
elif result_type == "立即领取奖品":
|
||||
# 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间
|
||||
try:
|
||||
# 确保有最新截图
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
src = os.path.join(pic_dir, "screenshot.png")
|
||||
|
||||
if os.path.exists(src):
|
||||
# 创建单独的文件夹保存"立即领取奖品"的截图
|
||||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||||
os.makedirs(prize_dir, exist_ok=True)
|
||||
|
||||
# 保存截图,文件名包含时间戳
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
dst = os.path.join(prize_dir, f"prize_{timestamp}.png")
|
||||
shutil.copy(src, dst)
|
||||
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "已保存立即领取奖品截图", path=dst
|
||||
)
|
||||
except Exception as e:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "保存截图失败", error=str(e)
|
||||
)
|
||||
|
||||
# 点击返回键
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "点击返回键关闭开奖结果"
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
|
||||
# 切换下一个直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
|
||||
if needswitch:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
|
||||
)
|
||||
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果",
|
||||
"处理完开奖结果,未启用切换,继续在当前直播间",
|
||||
)
|
||||
except Exception as e:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果",
|
||||
"处理开奖结果失败",
|
||||
error=str(e),
|
||||
result_type=result_type,
|
||||
)
|
||||
# 失败时尝试按返回键并切换
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_lottery_result_by_ocr完成",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
result_type=result_type,
|
||||
)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def shot_and_diagnose(
|
||||
analyser: Any, tag: str, msg: str, device_id: str, diagnose: bool = True
|
||||
) -> None:
|
||||
"""截图并执行阶段诊断(兼容旧版调用方式)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
tag: 日志标签
|
||||
msg: 日志消息
|
||||
device_id: 设备ID
|
||||
diagnose: 是否执行阶段诊断(默认True)
|
||||
"""
|
||||
try:
|
||||
# 截图
|
||||
ok = analyser.operation.get_screenshot(device_id)
|
||||
if not ok:
|
||||
analyser._log_kv(tag, f"{msg} - 获取截图失败", ok=0) # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
# 如果启用诊断,执行阶段诊断
|
||||
if diagnose:
|
||||
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
|
||||
analyser._last_diag_stage = stage # type: ignore[attr-defined]
|
||||
analyser._last_diag_seen = seen # type: ignore[attr-defined]
|
||||
analyser._last_diag_ts = time.time() # type: ignore[attr-defined]
|
||||
# 使用位置参数调用,避免与关键字参数冲突
|
||||
analyser._log_kv(tag, msg, **{"stage": stage, "seen": seen}) # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._log_kv(tag, msg) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
# 避免异常影响主流程
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
tag, f"{msg} - 异常: {type(e).__name__}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
from typing import Optional
|
||||
import re
|
||||
|
||||
from douyin_utils import normalize_countdown_text, extract_prize_value_yuan
|
||||
from douyin.utils.douyin_utils import normalize_countdown_text, extract_prize_value_yuan
|
||||
|
||||
|
||||
def _safe_str(text: Optional[str]) -> str:
|
||||
File renamed without changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
# 福袋详情模块目录
|
||||
|
||||
本目录包含 `douyin_fudai_detail.py` 的模块化子模块。
|
||||
|
||||
## 文件结构
|
||||
|
||||
- `fudai_detail_room_title.py` - 直播间标题处理模块
|
||||
- `fudai_detail_operations.py` - 福袋详情页操作模块(打开/关闭)
|
||||
- `fudai_detail_coupon_detection.py` - 优惠券弹窗检测模块
|
||||
- `fudai_detail_reader.py` - 福袋详情读取模块
|
||||
- `fudai_detail_validator.py` - 数据验证模块
|
||||
- `fudai_detail_utils.py` - 工具函数模块
|
||||
- `__init__.py` - 包初始化文件
|
||||
|
||||
## 使用方式
|
||||
|
||||
所有功能通过主模块 `douyin_fudai_detail` 导出,使用方式保持不变:
|
||||
|
||||
```python
|
||||
import douyin_fudai_detail
|
||||
|
||||
# 使用导出的函数
|
||||
douyin_fudai_detail.close_fudai_detail(analyser)
|
||||
douyin_fudai_detail.read_fudai_detail_once(analyser)
|
||||
# ... 等等
|
||||
```
|
||||
|
||||
## 模块说明
|
||||
|
||||
### fudai_detail_room_title.py
|
||||
处理直播间标题的OCR识别、噪音过滤、规范化等功能。
|
||||
|
||||
### fudai_detail_operations.py
|
||||
处理福袋详情页的打开和关闭操作。
|
||||
|
||||
### fudai_detail_coupon_detection.py
|
||||
检测当前弹窗是否为优惠券弹窗,而非真正的福袋详情页。
|
||||
|
||||
### fudai_detail_reader.py
|
||||
执行福袋详情的OCR识别和读取,包括单次读取和重试读取。
|
||||
|
||||
### fudai_detail_validator.py
|
||||
验证福袋详情数据的合理性,检测识别错误。
|
||||
|
||||
### fudai_detail_utils.py
|
||||
提供通用的工具函数。
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
福袋详情模块包
|
||||
==============
|
||||
|
||||
包含所有福袋详情相关的子模块。
|
||||
"""
|
||||
|
||||
__all__ = []
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
优惠券弹窗检测模块
|
||||
==================
|
||||
|
||||
检测当前弹窗是否为优惠券弹窗,而非真正的福袋详情页。
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
import os
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
"""在已点击疑似福袋后,判断当前弹窗是否为优惠券类,而非真正福袋详情。
|
||||
|
||||
只在"点击详情后"调用,不在平时循环中使用,避免额外开销。
|
||||
逻辑:
|
||||
1. 对屏幕中部区域做颜色统计
|
||||
2. 如果同时检测到福袋详情和优惠券特征,需要OCR确认"开心收下"字样
|
||||
3. 只有OCR确认是"开心收下"时,才判定为优惠券弹窗
|
||||
"""
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"获取截图失败(判断优惠券弹窗)",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
try:
|
||||
pic = Image.open(path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
pic = pic.convert("RGBA")
|
||||
pix = pic.load()
|
||||
w, h = pic.size
|
||||
|
||||
# 扫描区域:153,351 到 266,451(基于1080x2400基准坐标)
|
||||
# 根据实际分辨率缩放坐标
|
||||
scale_x = w / 1080.0
|
||||
scale_y = h / 2400.0
|
||||
x1 = int(153 * scale_x)
|
||||
y1 = int(351 * scale_y)
|
||||
x2 = int(266 * scale_x)
|
||||
y2 = int(451 * scale_y)
|
||||
|
||||
# 边界检查
|
||||
x1 = max(0, min(x1, w))
|
||||
y1 = max(0, min(y1, h))
|
||||
x2 = max(0, min(x2, w))
|
||||
y2 = max(0, min(y2, h))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
return False
|
||||
|
||||
fudai_like = 0
|
||||
coupon_like = 0
|
||||
step_x = max(1, (x2 - x1) // 40)
|
||||
step_y = max(1, (y2 - y1) // 40)
|
||||
|
||||
for yy in range(y1, y2, step_y):
|
||||
for xx in range(x1, x2, step_x):
|
||||
try:
|
||||
p = pix[xx, yy]
|
||||
except Exception as e:
|
||||
# 像素访问失败,跳过该像素(可能是坐标越界)
|
||||
continue
|
||||
if not (isinstance(p, tuple) and len(p) >= 3):
|
||||
continue
|
||||
r, g, b = int(p[0]), int(p[1]), int(p[2])
|
||||
# 福袋:粉/紫/粉蓝
|
||||
if r >= 200 and b >= 210 and 80 <= g <= 230:
|
||||
fudai_like += 1
|
||||
# 券:偏橙色
|
||||
if r >= 200 and 120 <= g <= 230 and b <= 180:
|
||||
coupon_like += 1
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
"弹窗颜色统计",
|
||||
fudai_like=fudai_like,
|
||||
coupon_like=coupon_like,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录弹窗颜色统计日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果券像素明显多于粉袋像素,可能需要OCR确认
|
||||
is_coupon_like_by_color = coupon_like > fudai_like * 1.2
|
||||
|
||||
# 检测是否同时有福袋详情特征(通过像素检测)
|
||||
has_fudai_detail = False
|
||||
try:
|
||||
from douyin.detection import douyin_pixel
|
||||
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
pic_rgb = pic.convert("RGB")
|
||||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None) or
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
result = douyin_pixel.detect_fudai_detail_page(
|
||||
pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi,
|
||||
template_threshold, return_info=True, analyser=analyser
|
||||
)
|
||||
if isinstance(result, tuple):
|
||||
has_fudai_detail, detect_info = result
|
||||
# 记录检测信息到日志
|
||||
try:
|
||||
task_count = detect_info.get("task_count", 0)
|
||||
detection_method = detect_info.get("method", "unknown")
|
||||
method_name = "任务数量检测" if detection_method == "task_count" else "未知"
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
f"检测福袋详情页({method_name})",
|
||||
task_count=task_count,
|
||||
method=detection_method,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录福袋详情检测日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
has_fudai_detail = result
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"检测福袋详情页失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果颜色统计显示可能是优惠券,需要严格确认:
|
||||
# 1. 先进行模板匹配确认(使用 detect_coupon_popup_background)
|
||||
# 2. 如果模板匹配成功,再进行OCR确认"开心收下"按钮
|
||||
# 3. 只有模板匹配和OCR都确认时,才判定为优惠券弹窗
|
||||
# 这样可以避免因识别福袋位置失败而误判为优惠券弹窗
|
||||
if is_coupon_like_by_color:
|
||||
try:
|
||||
# 步骤1:模板匹配确认
|
||||
template_matched = False
|
||||
try:
|
||||
from douyin.detection import douyin_pixel
|
||||
pic_rgb = pic.convert("RGB")
|
||||
template_matched = douyin_pixel.detect_coupon_popup_background(pic_rgb)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"模板匹配确认异常",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not template_matched:
|
||||
# 模板匹配失败,即使颜色统计偏向优惠券,也不判定为优惠券弹窗
|
||||
# 可能是识别福袋位置失败,导致点击了错误位置
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
"颜色统计偏向优惠券,但模板匹配未命中,不判定为优惠券弹窗",
|
||||
说明="可能是识别福袋位置失败,点击了错误位置",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录模板匹配失败日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 步骤2:OCR确认"开心收下"按钮(模板匹配成功后)
|
||||
if has_fudai_detail:
|
||||
analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认")
|
||||
else:
|
||||
analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认")
|
||||
|
||||
# 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域)
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
if os.path.exists(pic_path):
|
||||
pic_check = Image.open(pic_path)
|
||||
pic_check.load()
|
||||
pic_rgb_check = pic_check.convert("RGB")
|
||||
|
||||
width, height = pic_rgb_check.size
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = 200, 1940, 880, 2140
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int(y1_base * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int(y2_base * height / ry)
|
||||
|
||||
x1 = max(0, min(x1, width - 1))
|
||||
y1 = max(0, min(y1, height - 1))
|
||||
x2 = max(0, min(x2, width - 1))
|
||||
y2 = max(0, min(y2, height - 1))
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_check,
|
||||
operation_type="ocr",
|
||||
picname="参与按钮",
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"purpose": "检测开心收下",
|
||||
}
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"OCR识别前保存完整截图(参与按钮-检测开心收下)",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录调试图像日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存参与按钮调试截图失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
|
||||
|
||||
# 并行执行模式0和模式1的OCR(如果启用模式1)
|
||||
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
|
||||
coupon_text = ""
|
||||
if enable_ocr_mode1:
|
||||
# 并行执行两个OCR模式
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mode0 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 0)
|
||||
future_mode1 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 1)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
|
||||
if text_mode0 and "开心收下" in text_mode0:
|
||||
coupon_text = text_mode0
|
||||
elif text_mode1 and "开心收下" in text_mode1:
|
||||
coupon_text = text_mode1
|
||||
elif text_mode0:
|
||||
coupon_text = text_mode0
|
||||
else:
|
||||
coupon_text = text_mode1
|
||||
else:
|
||||
# 只使用模式0
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
# 模板匹配 + OCR 都确认,判定为优惠券弹窗
|
||||
analyser._log_kv("弹窗", "模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50])
|
||||
return True
|
||||
else:
|
||||
# 模板匹配成功,但OCR未确认"开心收下"
|
||||
# 如果同时检测到福袋详情,优先信任福袋详情
|
||||
if has_fudai_detail:
|
||||
analyser._log_kv("弹窗", "模板匹配成功但OCR未确认'开心收下',且检测到福袋详情,判定为福袋详情页", OCR文本=coupon_text[:50] if coupon_text else "空")
|
||||
return False
|
||||
else:
|
||||
# 模板匹配成功但OCR未确认,可能是识别福袋位置失败
|
||||
# 不判定为优惠券弹窗,避免误点返回
|
||||
analyser._log_kv(
|
||||
"弹窗",
|
||||
"模板匹配成功但OCR未确认'开心收下',不判定为优惠券弹窗",
|
||||
OCR文本=coupon_text[:50] if coupon_text else "空",
|
||||
说明="可能是识别福袋位置失败,点击了错误位置",
|
||||
)
|
||||
return False
|
||||
except Exception as e:
|
||||
# 确认过程异常,不判定为优惠券弹窗,避免误判
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"优惠券确认过程异常,不判定为优惠券弹窗",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 否则判定为福袋详情页
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
福袋详情页操作模块
|
||||
==================
|
||||
|
||||
处理福袋详情页的打开和关闭操作。
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
import time
|
||||
|
||||
|
||||
def close_fudai_detail(analyser: Any) -> None:
|
||||
"""关闭福袋详情:使用点击关闭详情页的坐标,而不是返回键。"""
|
||||
try:
|
||||
# 获取分辨率比例(基准分辨率 1080x2400)
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
# 计算关闭详情页的坐标(基准坐标 500, 470)
|
||||
close_x = int(500 * rx // 1080)
|
||||
close_y = int(470 * ry // 2400)
|
||||
|
||||
# 坐标验证:检查坐标是否在合理范围内
|
||||
# 获取屏幕尺寸(如果可用)
|
||||
screen_width = rx
|
||||
screen_height = ry
|
||||
try:
|
||||
if hasattr(analyser, 'operation') and hasattr(analyser.operation, 'get_screen_size'):
|
||||
try:
|
||||
screen_size = analyser.operation.get_screen_size(analyser.device_id)
|
||||
if screen_size:
|
||||
screen_width, screen_height = screen_size
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 验证坐标边界
|
||||
if close_x < 0 or close_x >= screen_width or close_y < 0 or close_y >= screen_height:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"验证",
|
||||
"关闭详情页坐标超出屏幕范围",
|
||||
x=close_x,
|
||||
y=close_y,
|
||||
screen_width=screen_width,
|
||||
screen_height=screen_height,
|
||||
base_x=500,
|
||||
base_y=470,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 修正坐标到屏幕范围内
|
||||
close_x = max(0, min(close_x, screen_width - 1))
|
||||
close_y = max(0, min(close_y, screen_height - 1))
|
||||
|
||||
analyser._log_kv(
|
||||
"详情",
|
||||
"close_fudai_detail:点击关闭详情页坐标",
|
||||
x=close_x,
|
||||
y=close_y,
|
||||
base_x=500,
|
||||
base_y=470,
|
||||
)
|
||||
except Exception as e:
|
||||
# 如果获取分辨率失败,使用默认坐标
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"获取分辨率失败,使用默认坐标",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
close_x, close_y = 500, 470
|
||||
try:
|
||||
analyser._log_kv("详情", "close_fudai_detail:使用默认坐标关闭详情页")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, close_x, close_y)
|
||||
except Exception as e1:
|
||||
# 兜底:尝试使用 analyser.click
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"使用operation.click关闭详情页失败,尝试备用方法",
|
||||
error=str(e1),
|
||||
error_type=type(e1).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.click(close_x, close_y)
|
||||
except Exception as e2:
|
||||
# 最后兜底:使用返回键
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"使用analyser.click关闭详情页失败,使用返回键",
|
||||
error=str(e2),
|
||||
error_type=type(e2).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception as e3:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"所有关闭详情页方法都失败",
|
||||
error=str(e3),
|
||||
error_type=type(e3).__name__,
|
||||
level="ERROR",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"operation.delay失败,使用time.sleep",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def ensure_fudai_detail_open(analyser: Any, fudai_x: int = 0) -> bool:
|
||||
"""确保福袋详情已打开:当前实现只记录日志并假定已打开。
|
||||
|
||||
Args:
|
||||
analyser: 分析器实例
|
||||
fudai_x: 福袋的x坐标(可选,当前实现未使用)
|
||||
"""
|
||||
try:
|
||||
analyser._log_kv("详情", "ensure_fudai_detail_open:假定已打开", fudai_x=fudai_x)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录ensure_fudai_detail_open日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,742 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
福袋详情读取模块
|
||||
================
|
||||
|
||||
执行福袋详情的OCR识别和读取,包括单次读取和重试读取。
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, Tuple, Optional
|
||||
import os
|
||||
import time
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.fudai.douyin_fudai_core import get_fudai_contain
|
||||
from .fudai_detail_validator import validate_fudai_detail
|
||||
|
||||
|
||||
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
"""执行一次福袋详情识别(本地完整版实现)。
|
||||
|
||||
流程:
|
||||
1. 获取截图(任务数量检测和弹窗检测已在阶段检测中完成,不再重复检测);
|
||||
2. 从阶段检测结果中获取任务数量(_fudai_detail_task_count_from_stage);
|
||||
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
|
||||
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取)
|
||||
# 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage
|
||||
task_count = 0
|
||||
try:
|
||||
task_count_from_stage = getattr(analyser, "_fudai_detail_task_count_from_stage", None)
|
||||
if task_count_from_stage is not None:
|
||||
task_count = int(task_count_from_stage or 0)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:从阶段检测获取任务数量(无需截图)",
|
||||
task_count=task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 如果阶段检测未保存任务数量,记录警告日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)",
|
||||
task_count_from_stage=task_count_from_stage,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 使用默认值
|
||||
task_count = 2
|
||||
|
||||
# 清除标志,避免影响后续调用
|
||||
try:
|
||||
analyser._fudai_detail_task_count_from_stage = None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底)
|
||||
# 在获取截图之前就返回错误,避免不必要的截图
|
||||
if task_count <= 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR",
|
||||
task_count=task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(任务数量为0)", elapsed_seconds=round(elapsed, 2))
|
||||
return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count}
|
||||
|
||||
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
|
||||
if task_count not in (1, 2, 3):
|
||||
task_count = 2
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:获取任务数量异常,使用默认值",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 异常时使用默认值
|
||||
task_count = 2
|
||||
|
||||
# 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量)
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
pic_rgb = None
|
||||
try:
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if pic_rgb is None:
|
||||
try:
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别")
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(截图失败)", elapsed_seconds=round(elapsed, 2))
|
||||
return "error", tup_err, {"reason": "screenshot_failed"}
|
||||
|
||||
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
|
||||
if task_count not in (1, 2, 3):
|
||||
task_count = 2
|
||||
|
||||
# 识别福袋内容 / 倒计时 / 价值
|
||||
try:
|
||||
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
|
||||
analyser, renwu=task_count
|
||||
)
|
||||
except Exception as e:
|
||||
# 出现异常时,记录错误并返回占位结果
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once 异常",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2))
|
||||
return "error", tup_err, {}
|
||||
|
||||
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
|
||||
is_watch_task = False
|
||||
try:
|
||||
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False))
|
||||
# 清除标志,避免影响后续调用
|
||||
if is_watch_task:
|
||||
try:
|
||||
analyser._is_watch_task_detected = False
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果检测到观看任务,返回 watch_task 状态
|
||||
if is_watch_task:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(观看任务)", elapsed_seconds=round(elapsed, 2))
|
||||
return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count}
|
||||
|
||||
# 解析倒计时 -> (剩余秒数, 未来时间戳)
|
||||
countdown_start = time.time()
|
||||
countdown_end = countdown_start + 60.0
|
||||
try:
|
||||
if time_text:
|
||||
res = analyser.operation.check_countdown(time_text)
|
||||
if isinstance(res, tuple) and len(res) == 2:
|
||||
total_seconds, future_ts = res
|
||||
try:
|
||||
total_seconds = int(total_seconds)
|
||||
except Exception:
|
||||
total_seconds = int(float(total_seconds or 0))
|
||||
if total_seconds > 0 and isinstance(future_ts, (int, float)):
|
||||
countdown_start = float(countdown_start)
|
||||
countdown_end = float(future_ts)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
detail_tuple = (
|
||||
content or "",
|
||||
time_text or "",
|
||||
int(participants or 0),
|
||||
int(copies or 0),
|
||||
float(prize_value_yuan or 0.0),
|
||||
(countdown_start, countdown_end),
|
||||
)
|
||||
extra: Dict[str, Any] = {
|
||||
"task_count": task_count,
|
||||
}
|
||||
|
||||
# 获取直播间名字
|
||||
room_title = ""
|
||||
room_title_raw = ""
|
||||
try:
|
||||
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
|
||||
room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 输出所有识别到的内容到运行日志和行为日志
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
# 格式化时间戳为可读格式
|
||||
countdown_start_str = ""
|
||||
countdown_end_str = ""
|
||||
if countdown_start and countdown_end:
|
||||
try:
|
||||
if countdown_start > 0:
|
||||
countdown_start_str = datetime.fromtimestamp(countdown_start).strftime("%Y-%m-%d %H:%M:%S")
|
||||
if countdown_end > 0:
|
||||
countdown_end_str = datetime.fromtimestamp(countdown_end).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 计算剩余秒数
|
||||
remain_seconds = 0
|
||||
if countdown_end > countdown_start:
|
||||
remain_seconds = int(countdown_end - time.time())
|
||||
|
||||
# 输出完整的识别结果到运行日志
|
||||
content_preview = (content or "")[:60] if content else "未识别到"
|
||||
content_full = content or ""
|
||||
# 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出)
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
|
||||
level="INFO",
|
||||
)
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
f"read_fudai_detail_once 完整识别结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
|
||||
status="ok",
|
||||
room_title=room_title,
|
||||
room_title_raw=room_title_raw,
|
||||
task_count=task_count,
|
||||
content=content_full,
|
||||
content_length=len(content_full),
|
||||
time_text=time_text or "",
|
||||
participants=int(participants or 0),
|
||||
copies=int(copies or 0),
|
||||
prize_value_yuan=float(prize_value_yuan or 0.0),
|
||||
countdown_start=countdown_start,
|
||||
countdown_start_str=countdown_start_str,
|
||||
countdown_end=countdown_end,
|
||||
countdown_end_str=countdown_end_str,
|
||||
remain_seconds=remain_seconds,
|
||||
elapsed_seconds=round(time.time() - start_time, 2),
|
||||
)
|
||||
|
||||
# 输出到行为日志(使用更详细的格式)
|
||||
content_preview = (content or "")[:60] if content else "未识别到"
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
|
||||
action="识别福袋详情",
|
||||
result="成功",
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"任务数量": task_count,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": countdown_start_str if countdown_start_str else f"{countdown_start}",
|
||||
"倒计时结束时间": countdown_end_str if countdown_end_str else f"{countdown_end}",
|
||||
"剩余秒数": remain_seconds,
|
||||
},
|
||||
)
|
||||
|
||||
# 输出简化的运行日志(兼容原有格式)
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once 结果",
|
||||
status="ok",
|
||||
content=detail_tuple[0],
|
||||
time_text=detail_tuple[1],
|
||||
participants=detail_tuple[2],
|
||||
copies=detail_tuple[3],
|
||||
prize_value_yuan=detail_tuple[4],
|
||||
countdown_start=countdown_start,
|
||||
countdown_end=countdown_end,
|
||||
task_count=task_count,
|
||||
)
|
||||
except Exception as e:
|
||||
# 如果详细日志输出失败,至少输出基本信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once 结果(简化)",
|
||||
status="ok",
|
||||
content=content or "",
|
||||
time_text=time_text or "",
|
||||
participants=int(participants or 0),
|
||||
copies=int(copies or 0),
|
||||
prize_value_yuan=float(prize_value_yuan or 0.0),
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2))
|
||||
return "ok", detail_tuple, extra
|
||||
|
||||
|
||||
def read_fudai_detail_with_retries(
|
||||
analyser: Any,
|
||||
fudai_x: int,
|
||||
read_once_callback,
|
||||
close_detail_callback,
|
||||
ensure_open_callback,
|
||||
) -> Tuple:
|
||||
"""多次重试读取福袋详情,返回 6 字段 detail tuple。
|
||||
|
||||
与原版保持兼容:总是返回
|
||||
(content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 首次识别前等待,确保详情页完全加载
|
||||
# 如果优化查找器已经验证过详情页,可以减少等待时间
|
||||
already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False)
|
||||
if already_verified:
|
||||
# 已经验证过,只需要短暂等待确保界面稳定
|
||||
initial_wait = 0.3
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:优化查找器已验证详情页,缩短等待时间",
|
||||
initial_wait=initial_wait,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 清除标志,避免影响后续调用
|
||||
try:
|
||||
analyser._fudai_detail_verified = False
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
initial_wait = float(
|
||||
getattr(analyser, "fudai_detail_initial_wait_seconds", 1.2) or 1.2
|
||||
)
|
||||
if initial_wait < 0.8:
|
||||
initial_wait = 0.8 # 最小0.8秒
|
||||
try:
|
||||
analyser.operation.delay(initial_wait)
|
||||
except Exception:
|
||||
time.sleep(initial_wait)
|
||||
|
||||
max_attempts = 2
|
||||
try:
|
||||
max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2)
|
||||
except Exception:
|
||||
max_attempts = 2
|
||||
if max_attempts < 1:
|
||||
max_attempts = 1
|
||||
retry_delay = 0.8
|
||||
try:
|
||||
retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.8) or 0.8)
|
||||
except Exception:
|
||||
retry_delay = 0.8
|
||||
|
||||
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
|
||||
extra: dict = {} # 初始化 extra,避免未绑定错误
|
||||
|
||||
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:
|
||||
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" or status == "watch_task":
|
||||
break
|
||||
|
||||
# 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开
|
||||
if status == "error" and isinstance(extra, dict) and extra.get("reason") == "task_count_zero":
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:任务数量为0,尝试重新打开福袋详情页",
|
||||
attempt=attempt + 1,
|
||||
max_attempts=max_attempts,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 调用回调函数重新打开福袋详情页
|
||||
try:
|
||||
if ensure_open_callback:
|
||||
ensure_open_callback(analyser, fudai_x)
|
||||
# 重新打开后等待一段时间,确保页面加载完成
|
||||
try:
|
||||
analyser.operation.delay(retry_delay + 0.5)
|
||||
except Exception:
|
||||
time.sleep(retry_delay + 0.5)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:重新打开福袋详情页失败",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser.operation.delay(retry_delay)
|
||||
except Exception:
|
||||
time.sleep(retry_delay)
|
||||
|
||||
if last_tuple is None:
|
||||
now = time.time()
|
||||
last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
|
||||
content, time_text, participants, copies, prize_value_yuan, cd = last_tuple
|
||||
cd_start, cd_end = None, None
|
||||
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
|
||||
cd_start, cd_end = cd[0], cd[1]
|
||||
|
||||
# 如果是优惠券弹窗,记录日志并明确标记
|
||||
is_coupon_popup = (last_status == "coupon_popup")
|
||||
is_watch_task = (last_status == "watch_task")
|
||||
|
||||
# 获取直播间名字(所有情况都需要,用于日志输出)
|
||||
room_title = ""
|
||||
room_title_raw = ""
|
||||
try:
|
||||
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
|
||||
room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 格式化时间信息(所有情况都需要,用于日志输出)
|
||||
cd_end_str = ""
|
||||
remain_seconds = 0
|
||||
try:
|
||||
from datetime import datetime
|
||||
if cd_end and isinstance(cd_end, (int, float)) and cd_end > 0:
|
||||
cd_end_str = datetime.fromtimestamp(cd_end).strftime("%Y-%m-%d %H:%M:%S")
|
||||
remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_coupon_popup:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries 最终结果:优惠券弹窗,已关闭,跳过后续处理",
|
||||
status=last_status,
|
||||
fudai_x=fudai_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 输出到行为日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
"识别福袋详情完成(最终结果)",
|
||||
action="识别福袋详情",
|
||||
result="优惠券弹窗",
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": str(cd_start) if cd_start else "",
|
||||
"倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "",
|
||||
"剩余秒数": remain_seconds,
|
||||
"状态": last_status,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elif is_watch_task:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries 最终结果:观看X分钟任务,已跳过,关闭详情",
|
||||
status=last_status,
|
||||
fudai_x=fudai_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 输出到行为日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
"识别福袋详情完成(最终结果)",
|
||||
action="识别福袋详情",
|
||||
result="观看任务",
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": str(cd_start) if cd_start else "",
|
||||
"倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "",
|
||||
"剩余秒数": remain_seconds,
|
||||
"状态": last_status,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
close_detail_callback(analyser)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
# 切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"检测到观看任务后切换直播间",
|
||||
)
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 正常情况(成功或错误):输出到运行日志和行为日志
|
||||
try:
|
||||
# 运行日志:完整的福袋详情
|
||||
content_preview = (content or "")[:60] if content else "未识别到"
|
||||
content_full = content or ""
|
||||
# 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出)
|
||||
if last_status == "ok":
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
|
||||
level="INFO",
|
||||
)
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
f"read_fudai_detail_with_retries 最终结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
|
||||
status=last_status,
|
||||
room_title=room_title,
|
||||
room_title_raw=room_title_raw,
|
||||
content=content_full,
|
||||
time_text=time_text,
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
countdown_start=cd_start,
|
||||
countdown_end=cd_end,
|
||||
countdown_end_str=cd_end_str if cd_end_str else "",
|
||||
remain_seconds=remain_seconds,
|
||||
fudai_x=fudai_x,
|
||||
)
|
||||
|
||||
# 行为日志:完整的福袋详情
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
f"识别福袋详情完成(最终结果):内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
|
||||
action="识别福袋详情",
|
||||
result="成功" if last_status == "ok" else last_status,
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": str(cd_start) if cd_start else "",
|
||||
"倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "",
|
||||
"剩余秒数": remain_seconds,
|
||||
"状态": last_status,
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
# 如果日志输出失败,至少尝试输出简化版本
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries 最终结果(简化)",
|
||||
status=last_status,
|
||||
content=content or "",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 将状态信息存储在 analyser 中,供调用方检查
|
||||
try:
|
||||
analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined]
|
||||
# 同时保存 extra 信息,用于检查错误原因
|
||||
if isinstance(extra, dict):
|
||||
analyser._last_fudai_detail_extra = extra # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._last_fudai_detail_extra = {} # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 验证福袋详情数据的合理性(仅在成功读取时验证)
|
||||
if last_status == "ok":
|
||||
is_valid, reason = validate_fudai_detail(last_tuple, analyser)
|
||||
if not is_valid:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:数据验证失败,识别可能出错",
|
||||
validation_reason=reason,
|
||||
content=content[:50] if content else "",
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
time_text=time_text[:30] if time_text else "",
|
||||
)
|
||||
# 标记为识别错误
|
||||
analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv("福袋详情", "read_fudai_detail_with_retries完成", elapsed_seconds=round(elapsed, 2), status=last_status, attempts=max_attempts)
|
||||
return last_tuple
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
直播间标题处理模块
|
||||
==================
|
||||
|
||||
处理直播间标题的OCR识别、噪音过滤、规范化等功能。
|
||||
"""
|
||||
|
||||
from typing import Any, Tuple, List
|
||||
import re
|
||||
|
||||
|
||||
def _room_title_has_ellipsis(s: str) -> bool:
|
||||
"""检查是否包含省略号。"""
|
||||
if "…" in s:
|
||||
return True
|
||||
if re.search(r"\.{3,}", s):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _strip_room_noise_text(s: str) -> str:
|
||||
"""移除直播间名 OCR 常见噪音(点赞/关注/粉丝等)。"""
|
||||
try:
|
||||
t = str(s or "")
|
||||
except Exception:
|
||||
# 字符串转换失败,返回空字符串
|
||||
return ""
|
||||
t = t.replace("\r", "\n").replace("\t", " ")
|
||||
t = re.sub(r"[\s\u3000]+", " ", t).strip()
|
||||
# 计数噪音:例如 1.2万点赞 / 234点赞 / 3W点赞
|
||||
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞)", " ", t)
|
||||
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*关注", " ", t)
|
||||
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*粉丝", " ", t)
|
||||
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t)
|
||||
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
|
||||
t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
|
||||
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"):
|
||||
t = t.replace(w, " ")
|
||||
t = re.sub(r"\s+", " ", t).strip()
|
||||
return t
|
||||
|
||||
|
||||
def _extract_room_title_candidate(raw_text: str) -> str:
|
||||
"""从 OCR 原文中提取更像"直播间名"的片段。"""
|
||||
t = _strip_room_noise_text(raw_text)
|
||||
if not t:
|
||||
return ""
|
||||
|
||||
segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()]
|
||||
best = ""
|
||||
best_score = -999
|
||||
for seg in segs:
|
||||
if not seg:
|
||||
continue
|
||||
seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip()
|
||||
if not seg2:
|
||||
continue
|
||||
seg = seg2
|
||||
score = len(seg)
|
||||
if _room_title_has_ellipsis(seg):
|
||||
score += 30
|
||||
if re.search(r"[\u4e00-\u9fffA-Za-z]", seg):
|
||||
score += 5
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best = seg
|
||||
|
||||
if best:
|
||||
m = re.search(r"(.*?)(…|\.{3,})", best)
|
||||
if m:
|
||||
cand = (m.group(1) + m.group(2)).strip()
|
||||
return cand if cand else best.strip()
|
||||
return best.strip()
|
||||
|
||||
m2 = re.search(r"(.*?)(…|\.{3,})", t)
|
||||
if m2:
|
||||
cand2 = (m2.group(1) + m2.group(2)).strip()
|
||||
if cand2:
|
||||
return cand2
|
||||
return t.strip()
|
||||
|
||||
|
||||
def _normalize_room_title(t: str) -> str:
|
||||
"""规范化直播间标题。"""
|
||||
s = _extract_room_title_candidate(str(t or ""))
|
||||
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 _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]:
|
||||
"""尝试 OCR 识别直播间标题。"""
|
||||
try:
|
||||
raw0 = analyser.operation.analyse_pic_word(cut_name, change_color)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"OCR识别直播间标题失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
cut_name=cut_name,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
raw0 = ""
|
||||
raw_text0 = str(raw0 or "").replace("\r", "\n").strip()
|
||||
cand_raw0 = _extract_room_title_candidate(raw_text0)
|
||||
title0 = _normalize_room_title(cand_raw0)
|
||||
return title0, cand_raw0
|
||||
|
||||
|
||||
def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]:
|
||||
"""从多个候选结果中选择最佳的一个。"""
|
||||
best = ("", "")
|
||||
best_score = -1
|
||||
for t_norm, t_raw, tag in cands:
|
||||
if not t_raw and not t_norm:
|
||||
continue
|
||||
ln = len(t_norm or "")
|
||||
score = ln
|
||||
if ln >= min_len:
|
||||
score += 10
|
||||
if ln == 1:
|
||||
score -= 4
|
||||
if ln == 2:
|
||||
score -= 1
|
||||
if _room_title_has_ellipsis(t_raw or ""):
|
||||
score += 8
|
||||
if tag.endswith("_cc0"):
|
||||
score += 2
|
||||
if tag.startswith("large"):
|
||||
score += 2
|
||||
if tag.startswith("mid"):
|
||||
score += 1
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best = (t_norm, t_raw)
|
||||
return best
|
||||
|
||||
|
||||
def read_live_room_title_core(
|
||||
analyser: Any,
|
||||
y_pianyi: int,
|
||||
min_len: int = 3,
|
||||
) -> Tuple[str, str]:
|
||||
"""读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。
|
||||
|
||||
使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。
|
||||
"""
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"获取截图失败(读取直播间标题)",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cands: List[Tuple[str, str, str]] = []
|
||||
|
||||
# mid ROI:优先使用更大区域,减少"只截到尾巴1个字"
|
||||
try:
|
||||
analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi)
|
||||
t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0)
|
||||
cands.append((t, r, 'mid_cc0'))
|
||||
if len(t or "") < min_len:
|
||||
t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1)
|
||||
cands.append((t1, r1, 'mid_cc1'))
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"OCR识别直播间标题(mid区域)失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# large ROI:进一步扩大,兼容机型/系统字体/刘海偏移
|
||||
if not cands or max(len(x[0] or "") for x in cands) < min_len:
|
||||
try:
|
||||
analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi)
|
||||
t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0)
|
||||
cands.append((t2, r2, 'large_cc0'))
|
||||
if len(t2 or "") < min_len:
|
||||
t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1)
|
||||
cands.append((t3, r3, 'large_cc1'))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# small ROI:最后兜底(历史区域),使用优化后的坐标
|
||||
if not cands or max(len(x[0] or "") for x in cands) <= 1:
|
||||
try:
|
||||
analyser.cut_pic(147, 147, 320, 188, '', 'live_room_title_small', y_pianyi)
|
||||
t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0)
|
||||
cands.append((t4, r4, 'small_cc0'))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
title, raw_text = _pick_best_room_title(cands, min_len)
|
||||
|
||||
# 更新 analyser 的属性
|
||||
try:
|
||||
analyser.current_room_title_raw = raw_text
|
||||
if title:
|
||||
analyser.current_room_title = title
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return title, raw_text
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
福袋详情工具函数模块
|
||||
====================
|
||||
|
||||
提供通用的工具函数。
|
||||
"""
|
||||
|
||||
|
||||
def is_abnormal_time_value(v: float) -> bool:
|
||||
"""Shim: treat clearly invalid time values as abnormal."""
|
||||
if v <= 0:
|
||||
return True
|
||||
if v > 24 * 3600 * 7:
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
福袋详情数据验证模块
|
||||
====================
|
||||
|
||||
验证福袋详情数据的合理性,检测识别错误。
|
||||
"""
|
||||
|
||||
from typing import Any, Tuple
|
||||
import re
|
||||
|
||||
|
||||
def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]:
|
||||
"""验证福袋详情数据的合理性。
|
||||
|
||||
返回:
|
||||
(is_valid, reason) - is_valid=True 表示数据合理,False 表示识别出错
|
||||
reason 为失败原因描述
|
||||
"""
|
||||
if not isinstance(detail, tuple) or len(detail) < 6:
|
||||
return False, "detail_tuple_invalid"
|
||||
|
||||
content = str(detail[0] or "").strip()
|
||||
time_text = str(detail[1] or "").strip()
|
||||
try:
|
||||
participants = int(detail[2] or 0)
|
||||
except Exception:
|
||||
participants = 0
|
||||
try:
|
||||
copies = int(detail[3] or 0)
|
||||
except Exception:
|
||||
copies = 0
|
||||
try:
|
||||
prize_value_yuan = float(detail[4] or 0.0)
|
||||
except Exception:
|
||||
prize_value_yuan = 0.0
|
||||
|
||||
countdown_tuple = detail[5]
|
||||
countdown_start, countdown_end = None, None
|
||||
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
|
||||
try:
|
||||
countdown_start = float(countdown_tuple[0] or 0.0)
|
||||
countdown_end = float(countdown_tuple[1] or 0.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查1:内容不能为空(至少要有一些文字)
|
||||
if not content or len(content.strip()) < 2:
|
||||
return False, "content_empty_or_too_short"
|
||||
|
||||
# 检查2:价值应该大于0(福袋至少应该有价值)
|
||||
if prize_value_yuan <= 0:
|
||||
return False, "prize_value_zero_or_negative"
|
||||
|
||||
# 检查3:价值应该合理(不能太大,比如超过100万)
|
||||
if prize_value_yuan > 1000000:
|
||||
return False, "prize_value_too_large"
|
||||
|
||||
# 检查4:倒计时应该合理
|
||||
if countdown_end is not None and countdown_start is not None:
|
||||
remain_seconds = countdown_end - countdown_start
|
||||
# 倒计时不能是负数
|
||||
if remain_seconds < 0:
|
||||
return False, "countdown_negative"
|
||||
# 倒计时不能太长(超过24小时)
|
||||
if remain_seconds > 24 * 3600:
|
||||
return False, "countdown_too_long"
|
||||
# 倒计时不能为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 为秒数
|
||||
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:
|
||||
return False, "participants_negative"
|
||||
|
||||
# 检查6:份数应该合理(不能是负数,至少应该是1)
|
||||
if copies < 0:
|
||||
return False, "copies_negative"
|
||||
|
||||
# 检查7:如果份数为0,但参与人数大于0,可能识别错误
|
||||
if copies == 0 and participants > 0:
|
||||
return False, "copies_zero_but_participants_positive"
|
||||
|
||||
# 检查8:时间文本应该存在(至少应该有倒计时信息)
|
||||
if not time_text and (countdown_end is None or countdown_end <= 0):
|
||||
return False, "no_time_text_and_no_countdown"
|
||||
|
||||
# 所有检查通过
|
||||
return True, "ok"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# GUI 目录
|
||||
|
||||
本目录包含项目的所有图形用户界面相关文件。
|
||||
|
||||
## 文件列表
|
||||
|
||||
- **gui_app.py** - 主GUI应用程序(基于tkinter/ttkbootstrap)
|
||||
- **gui_core.py** - GUI核心功能模块(参数处理、设备管理、配置读写等)
|
||||
- **web_gui.py** - Web GUI服务器
|
||||
- **webgui_launcher.py** - Web GUI启动器
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 桌面GUI
|
||||
```bash
|
||||
python gui/gui_app.py
|
||||
```
|
||||
|
||||
### Web GUI
|
||||
```bash
|
||||
python gui/webgui_launcher.py
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ from typing import Any, Callable
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)
|
||||
from gui_core import (
|
||||
from gui.gui_core import (
|
||||
RunParams,
|
||||
Runner,
|
||||
find_adb_executable,
|
||||
@@ -2319,14 +2319,31 @@ def main():
|
||||
|
||||
lines.append(f"参与成功: {fudai_attend_ok}")
|
||||
lines.append(f"参与失败: {fudai_attend_fail}")
|
||||
total_attend = fudai_attend_ok + fudai_attend_fail
|
||||
if total_attend > 0:
|
||||
success_rate = (fudai_attend_ok / total_attend) * 100
|
||||
# 参与成功率应该基于点击参与次数来计算
|
||||
# 因为参与成功可能包括"检测到已参与"的情况(没有点击)
|
||||
if fudai_click_attend > 0:
|
||||
# 通过点击参与成功的次数(不超过点击参与次数)
|
||||
click_attend_success = min(fudai_attend_ok, fudai_click_attend)
|
||||
success_rate = (click_attend_success / fudai_click_attend) * 100
|
||||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||||
# 如果参与成功 > 点击参与,说明有检测到已参与的情况
|
||||
if fudai_attend_ok > fudai_click_attend:
|
||||
detected_already_attended = fudai_attend_ok - fudai_click_attend
|
||||
lines.append(f" (其中 {detected_already_attended} 次为检测到已参与状态)")
|
||||
elif fudai_attend_ok > 0 or fudai_attend_fail > 0:
|
||||
# 如果没有点击参与但有参与结果,使用原来的计算方式
|
||||
total_attend = fudai_attend_ok + fudai_attend_fail
|
||||
if total_attend > 0:
|
||||
success_rate = (fudai_attend_ok / total_attend) * 100
|
||||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||||
|
||||
lines.append(f"中奖次数: {fudai_result_win}")
|
||||
lines.append(f"未中奖次数: {fudai_result_no_win}")
|
||||
total_results = fudai_result_win + fudai_result_no_win
|
||||
# 检查数据一致性:参与成功次数应该 >= 开奖结果次数
|
||||
if fudai_attend_ok > 0 and total_results < fudai_attend_ok:
|
||||
pending_results = fudai_attend_ok - total_results
|
||||
lines.append(f" 注意: 有 {pending_results} 次参与成功尚未开奖(或开奖结果未识别)")
|
||||
if total_results > 0:
|
||||
win_rate = (fudai_result_win / total_results) * 100
|
||||
lines.append(f" 中奖率: {win_rate:.1f}%")
|
||||
@@ -2407,6 +2424,9 @@ def main():
|
||||
lines.append(f"OCR尝试次数: {ocr_attempt}")
|
||||
lines.append(f"OCR成功次数: {ocr_success}")
|
||||
lines.append(f"OCR失败次数: {ocr_failed}")
|
||||
total_ocr_results = ocr_success + ocr_failed
|
||||
if total_ocr_results < ocr_attempt:
|
||||
lines.append(f" 注意: 有 {ocr_attempt - total_ocr_results} 次尝试未记录结果(可能日志格式不匹配)")
|
||||
if ocr_attempt > 0:
|
||||
ocr_rate = (ocr_success / ocr_attempt) * 100
|
||||
lines.append(f"OCR成功率: {ocr_rate:.1f}%")
|
||||
@@ -2423,6 +2443,9 @@ def main():
|
||||
lines.append(f"详情识别尝试: {fudai_detail_read_attempt}")
|
||||
lines.append(f"详情识别成功: {fudai_detail_read_success}")
|
||||
lines.append(f"详情识别失败: {fudai_detail_read_failed}")
|
||||
total_detail_results = fudai_detail_read_success + fudai_detail_read_failed
|
||||
if total_detail_results < fudai_detail_read_attempt:
|
||||
lines.append(f" 注意: 有 {fudai_detail_read_attempt - total_detail_results} 次尝试未记录结果(可能日志格式不匹配)")
|
||||
if fudai_detail_read_attempt > 0:
|
||||
detail_rate = (fudai_detail_read_success / fudai_detail_read_attempt) * 100
|
||||
lines.append(f"详情识别成功率: {detail_rate:.1f}%")
|
||||
@@ -2771,6 +2794,9 @@ def main():
|
||||
max_value = max(prize_values)
|
||||
min_value = min(prize_values)
|
||||
lines.append(f"识别到的福袋总数: {len(prize_values)}")
|
||||
# 说明:价值统计只统计了成功识别到价值的福袋,可能少于总识别次数
|
||||
if fudai_seen > len(prize_values):
|
||||
lines.append(f" (总识别次数: {fudai_seen},其中 {len(prize_values)} 个成功识别到价值)")
|
||||
lines.append(f"总价值: {total_value:.2f} 元")
|
||||
lines.append(f"平均价值: {avg_value:.2f} 元")
|
||||
lines.append(f"最高价值: {max_value:.2f} 元")
|
||||
@@ -11,7 +11,7 @@ from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.json")
|
||||
CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.json")
|
||||
|
||||
|
||||
def find_adb_executable() -> str:
|
||||
@@ -550,12 +550,13 @@ class Runner:
|
||||
if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s):
|
||||
self._inc("fudai_order_success")
|
||||
self._record_event("fudai_order_success", self._snapshot_fudai())
|
||||
# 等待开奖
|
||||
if ("[参与]" in s and "等待开奖" in s) or "等待开奖中" in s:
|
||||
# 等待开奖(只在设置等待开奖标志时计数,避免重复计数)
|
||||
# 注意:不要匹配"已经参与,等待开奖",因为那已经在参与成功时计数了
|
||||
if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ("[参与]" in s and "设置等待开奖标志" in s):
|
||||
self._inc("fudai_waiting_lottery")
|
||||
# 提取剩余秒数
|
||||
meta = self._snapshot_fudai()
|
||||
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
|
||||
m = re.search(r"(?:剩余|倒计时|remain_seconds)[=:]?\s*(\d+)", s)
|
||||
if m:
|
||||
try:
|
||||
meta["remain_seconds"] = int(m.group(1))
|
||||
@@ -11,8 +11,8 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Optional
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
BASE_DIR = os.path.dirname(__file__)
|
||||
CONFIG_PATH = os.path.join(BASE_DIR, "config.json")
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CONFIG_PATH = os.path.join(BASE_DIR, "config", "config.json")
|
||||
WEBUI_DIR = os.path.join(BASE_DIR, "webui")
|
||||
|
||||
# ANSI转义序列清理正则表达式
|
||||
@@ -662,12 +662,13 @@ class ProcRunner:
|
||||
if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s):
|
||||
self._inc("fudai_order_success")
|
||||
self._record_event("fudai_order_success", self._snapshot_fudai())
|
||||
# 等待开奖
|
||||
if ("[参与]" in s and "等待开奖" in s) or "等待开奖中" in s:
|
||||
# 等待开奖(只在设置等待开奖标志时计数,避免重复计数)
|
||||
# 注意:不要匹配"已经参与,等待开奖",因为那已经在参与成功时计数了
|
||||
if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ("[参与]" in s and "设置等待开奖标志" in s):
|
||||
self._inc("fudai_waiting_lottery")
|
||||
# 提取剩余秒数
|
||||
meta = self._snapshot_fudai()
|
||||
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
|
||||
m = re.search(r"(?:剩余|倒计时|remain_seconds)[=:]?\s*(\d+)", s)
|
||||
if m:
|
||||
try:
|
||||
meta["remain_seconds"] = int(m.group(1))
|
||||
@@ -1158,7 +1159,7 @@ class ProcRunner:
|
||||
_pick("skip_if_countdown_lt_seconds", 15) or 15
|
||||
)
|
||||
try:
|
||||
reset_after_swipes = int(_pick("reset_after_swipes", 10))
|
||||
reset_after_swipes = int(_pick("reset_after_swipes", 10) or 10)
|
||||
except Exception:
|
||||
reset_after_swipes = 10
|
||||
if reset_after_swipes < 1:
|
||||
File renamed without changes.
+1
-1
@@ -15,7 +15,7 @@ def get_project_root() -> str:
|
||||
|
||||
def get_config_path() -> str:
|
||||
"""返回 config.json 的路径"""
|
||||
return os.path.join(PROJECT_ROOT, "config.json")
|
||||
return os.path.join(PROJECT_ROOT, "config", "config.json")
|
||||
|
||||
|
||||
def get_logs_dir() -> str:
|
||||
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
[pytest]
|
||||
# pytest配置文件
|
||||
|
||||
# 测试发现模式
|
||||
python_files = test_*.py *_test.py
|
||||
python_classes = Test*
|
||||
python_functions = test_*
|
||||
|
||||
# 测试目录
|
||||
testpaths = tests
|
||||
|
||||
# 命令行选项
|
||||
addopts =
|
||||
-v
|
||||
--strict-markers
|
||||
--tb=short
|
||||
--cov=.
|
||||
--cov-report=term-missing
|
||||
-p no:warnings
|
||||
|
||||
# 标记定义
|
||||
markers =
|
||||
unit: 单元测试
|
||||
integration: 集成测试
|
||||
slow: 慢速测试(需要较长时间)
|
||||
requires_device: 需要真实设备(需要ADB连接)
|
||||
requires_gui: 需要GUI环境
|
||||
requires_network: 需要网络连接
|
||||
mock: 使用Mock的测试
|
||||
|
||||
# 日志配置
|
||||
log_cli = true
|
||||
log_cli_level = INFO
|
||||
log_cli_format = %(asctime)s [%(levelname)8s] %(name)s: %(message)s
|
||||
log_cli_date_format = %Y-%m-%d %H:%M:%S
|
||||
|
||||
# 超时设置(秒)
|
||||
timeout = 300
|
||||
timeout_method = thread
|
||||
|
||||
# 最小Python版本
|
||||
minversion = 7.4.0
|
||||
|
||||
# 忽略警告
|
||||
filterwarnings =
|
||||
ignore::DeprecationWarning
|
||||
ignore::PendingDeprecationWarning
|
||||
|
||||
@@ -123,6 +123,11 @@ paddlepaddle>=2.5.0,<3.0.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
# 测试依赖包
|
||||
# 安装命令: pip install -r requirements-test.txt
|
||||
|
||||
# 测试框架
|
||||
pytest>=7.4.0
|
||||
pytest-cov>=4.1.0
|
||||
pytest-mock>=3.11.0
|
||||
pytest-asyncio>=0.21.0
|
||||
pytest-timeout>=2.1.0
|
||||
pytest-xdist>=3.3.0 # 并行测试
|
||||
|
||||
# 代码质量检查(用于测试)
|
||||
pytest-flake8>=1.1.0
|
||||
pytest-pylint>=0.21.0
|
||||
|
||||
# 测试报告
|
||||
pytest-html>=3.2.0
|
||||
pytest-json-report>=1.5.0
|
||||
|
||||
# Mock和Fixtures
|
||||
responses>=0.23.0 # HTTP请求mock
|
||||
freezegun>=1.2.0 # 时间mock
|
||||
faker>=19.0.0 # 测试数据生成
|
||||
|
||||
# 代码覆盖率
|
||||
coverage>=7.3.0
|
||||
|
||||
# 类型检查(可选)
|
||||
mypy>=1.5.0
|
||||
types-requests>=2.31.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -139,6 +139,11 @@ ttkbootstrap>=1.10.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user