feat: Implement 30-minute timeout protection and unify path configurations
- Introduced a 30-minute timeout mechanism to prevent the script from getting stuck in invalid states, with configurable timeout settings. - Unified path configurations across the project to enhance maintainability and avoid hardcoded paths. - Updated documentation and flowcharts to reflect the new timeout feature and improved path management. - Fixed issues with template and screenshot path configurations to ensure consistency across the project.
This commit is contained in:
1 parent
686dde5cc0
commit
26df350755
64 files changed
+7568
-414
No files matched your search
@@ -25,6 +25,10 @@ htmlcov/
|
||||
# VS Code
|
||||
.vscode/
|
||||
|
||||
# Cursor IDE
|
||||
.cursor/
|
||||
.specstory/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,364 @@
|
||||
# 代码质量审查报告
|
||||
|
||||
**审查日期**: 2025-12-28
|
||||
**审查范围**: 所有 Python 文件(共 117 个文件)
|
||||
**审查标准**: 逻辑错误、格式规范、信息准确性、潜在风险
|
||||
|
||||
---
|
||||
|
||||
## 一、发现的严重错误
|
||||
|
||||
### 1. 硬编码绝对路径(高优先级)✅ 已修复
|
||||
|
||||
**类型**: 可移植性问题、安全隐患
|
||||
**位置**:
|
||||
- `run_cli.py:21` - `_EXTERNAL_DOUYIN_FUDAI_DIR = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf"` ✅ 已修复
|
||||
- `Underlying_Operations.py:39-40` - `_EXTERNAL_AXF_SCREENSHOT = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf\pic\screenshot.png"` ✅ 已修复
|
||||
|
||||
**描述**:
|
||||
- 代码中包含硬编码的用户特定路径,这会导致:
|
||||
1. 其他用户无法运行代码
|
||||
2. 代码无法在不同机器间移植
|
||||
3. 可能泄露用户信息(用户名)
|
||||
|
||||
**修复建议**:
|
||||
```python
|
||||
# 修复前
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf"
|
||||
|
||||
# 修复后
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.path.join(
|
||||
os.path.expanduser("~"),
|
||||
".cursor",
|
||||
"worktrees",
|
||||
"douyin_guaji-main",
|
||||
"axf"
|
||||
)
|
||||
# 或者使用环境变量
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get(
|
||||
"EXTERNAL_DOUYIN_FUDAI_DIR",
|
||||
os.path.join(os.path.expanduser("~"), ".cursor", "worktrees", "douyin_guaji-main", "axf")
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 递归调用可能导致栈溢出(高优先级)✅ 已修复
|
||||
|
||||
**类型**: 逻辑漏洞、性能问题
|
||||
**位置**: `douyin/core/douyin_fudai.py:1570` ✅ 已修复
|
||||
|
||||
**描述**:
|
||||
```python
|
||||
self.run_once_basic() # 递归调用
|
||||
```
|
||||
- 在 `run_once_basic()` 方法内部直接递归调用自身
|
||||
- 虽然注释说明"仅在当前检测到不在抖音前台的场景下递归一次",但:
|
||||
1. 如果自救逻辑失败,可能进入无限递归
|
||||
2. 没有明确的递归深度限制
|
||||
3. 可能导致栈溢出异常
|
||||
|
||||
**修复建议**:
|
||||
```python
|
||||
# 添加递归深度限制
|
||||
def run_once_basic(self, recursion_depth: int = 0) -> None:
|
||||
MAX_RECURSION_DEPTH = 3
|
||||
|
||||
if recursion_depth >= MAX_RECURSION_DEPTH:
|
||||
self._log_kv("流程", "达到最大递归深度,停止递归")
|
||||
return
|
||||
|
||||
# ... 原有逻辑 ...
|
||||
|
||||
# 递归调用时传递深度参数
|
||||
self.run_once_basic(recursion_depth + 1)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 过于宽泛的异常捕获(中高优先级)
|
||||
|
||||
**类型**: 逻辑漏洞、可维护性问题
|
||||
**位置**: 64 个文件中发现 1514 处 `except Exception:` 或 `except:`
|
||||
|
||||
**描述**:
|
||||
- 大量使用 `except Exception:` 或 `except:` 捕获所有异常
|
||||
- 这会隐藏真正的错误,导致:
|
||||
1. 难以调试问题
|
||||
2. 可能忽略关键错误
|
||||
3. 错误处理不够精确
|
||||
|
||||
**典型示例**:
|
||||
```python
|
||||
# douyin/fudai/douyin_fudai_core.py 等多处
|
||||
try:
|
||||
# 某些操作
|
||||
except Exception: # 过于宽泛
|
||||
pass # 静默忽略所有错误
|
||||
```
|
||||
|
||||
**修复建议**:
|
||||
```python
|
||||
# 修复前
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 修复后
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except (FileNotFoundError, PermissionError) as e:
|
||||
analyser._log_kv("截图", "获取截图失败", error=str(e))
|
||||
except Exception as e:
|
||||
analyser._log_kv("截图", "未知错误", error=str(e), error_type=type(e).__name__)
|
||||
# 根据实际情况决定是否重新抛出
|
||||
```
|
||||
|
||||
**影响文件**(部分):
|
||||
- `douyin/fudai/douyin_fudai_core.py` - 253 处
|
||||
- `douyin/core/douyin_fudai.py` - 144 处
|
||||
- `douyin/reservation/douyin_reservation_logic.py` - 110 处
|
||||
- `Underlying_Operations.py` - 81 处
|
||||
|
||||
---
|
||||
|
||||
### 4. 无限循环缺少退出条件(中优先级)
|
||||
|
||||
**类型**: 逻辑漏洞、性能问题
|
||||
**位置**:
|
||||
- `douyin/core/douyin_main_flow.py:65` - `while True:`
|
||||
- `gui/gui_app.py` - 3 处 `while True:`
|
||||
- `Underlying_Operations.py` - 4 处 `while True:`
|
||||
|
||||
**描述**:
|
||||
- 虽然大部分循环有保护机制(如时间限制、循环次数限制),但需要确保:
|
||||
1. 所有 `while True` 循环都有明确的退出条件
|
||||
2. 异常情况下能够正确退出
|
||||
3. 资源能够正确释放
|
||||
|
||||
**修复建议**:
|
||||
- 为所有无限循环添加明确的退出条件检查
|
||||
- 添加超时保护机制
|
||||
- 确保异常情况下能够正确清理资源
|
||||
|
||||
---
|
||||
|
||||
## 二、潜在问题与改进建议
|
||||
|
||||
### 1. 代码风格不一致
|
||||
|
||||
**风险等级**: 低
|
||||
**位置**: 整个代码库
|
||||
|
||||
**描述**:
|
||||
- 字符串引号使用不一致(单引号 vs 双引号)
|
||||
- 注释风格不统一
|
||||
- 函数命名风格混用(snake_case vs camelCase)
|
||||
|
||||
**优化建议**:
|
||||
- 使用代码格式化工具(如 `black`、`autopep8`)
|
||||
- 统一代码风格规范
|
||||
- 添加 pre-commit hooks
|
||||
|
||||
---
|
||||
|
||||
### 2. 大量 TODO/FIXME 标记
|
||||
|
||||
**风险等级**: 中
|
||||
**位置**: 55 个文件中发现 333 处 TODO/FIXME 标记
|
||||
|
||||
**描述**:
|
||||
- 代码中存在大量未完成的功能标记
|
||||
- 可能影响代码的可维护性和完整性
|
||||
|
||||
**优化建议**:
|
||||
- 定期审查和清理 TODO 标记
|
||||
- 将重要的 TODO 转换为 issue 跟踪
|
||||
- 完成或删除过时的 TODO
|
||||
|
||||
---
|
||||
|
||||
### 3. 类型注解不完整
|
||||
|
||||
**风险等级**: 低
|
||||
**位置**: 多个文件
|
||||
|
||||
**描述**:
|
||||
- 部分函数缺少类型注解
|
||||
- 使用 `Any` 类型过多,降低了类型检查的价值
|
||||
|
||||
**优化建议**:
|
||||
- 逐步添加完整的类型注解
|
||||
- 减少 `Any` 类型的使用
|
||||
- 使用 `mypy` 或 `pyright` 进行类型检查
|
||||
|
||||
---
|
||||
|
||||
### 4. 文件过大
|
||||
|
||||
**风险等级**: 中
|
||||
**位置**:
|
||||
- `douyin/fudai/douyin_fudai_core.py` - 5014 行
|
||||
- `douyin/core/douyin_fudai.py` - 约 3000+ 行
|
||||
|
||||
**描述**:
|
||||
- 单个文件过大,影响可维护性
|
||||
- 虽然已经进行了模块化拆分,但仍有改进空间
|
||||
|
||||
**优化建议**:
|
||||
- 继续拆分大文件
|
||||
- 使用 Mixin 模式(已在部分代码中使用)
|
||||
- 提取公共逻辑到独立模块
|
||||
|
||||
---
|
||||
|
||||
### 5. 资源管理
|
||||
|
||||
**风险等级**: 中
|
||||
**位置**: 文件操作、网络连接、线程池等
|
||||
|
||||
**描述**:
|
||||
- 需要确保所有资源(文件句柄、网络连接、线程池)都能正确关闭
|
||||
|
||||
**优化建议**:
|
||||
- 使用 `with` 语句管理资源
|
||||
- 确保异常情况下资源也能正确释放
|
||||
- 检查 `ThreadPoolExecutor` 是否正确关闭
|
||||
|
||||
---
|
||||
|
||||
### 6. 日志记录不一致
|
||||
|
||||
**风险等级**: 低
|
||||
**位置**: 整个代码库
|
||||
|
||||
**描述**:
|
||||
- 日志记录方式不统一
|
||||
- 部分关键操作缺少日志记录
|
||||
|
||||
**优化建议**:
|
||||
- 统一日志记录接口
|
||||
- 为关键操作添加日志
|
||||
- 使用结构化日志格式
|
||||
|
||||
---
|
||||
|
||||
### 7. 配置管理
|
||||
|
||||
**风险等级**: 低
|
||||
**位置**: 配置文件读取
|
||||
|
||||
**描述**:
|
||||
- 配置读取缺少验证
|
||||
- 默认值处理不一致
|
||||
|
||||
**优化建议**:
|
||||
- 添加配置验证
|
||||
- 统一默认值处理
|
||||
- 使用配置类管理配置项
|
||||
|
||||
---
|
||||
|
||||
## 三、总结报告
|
||||
|
||||
### 总体评价
|
||||
|
||||
**代码质量评分**: **6.5/10**
|
||||
|
||||
**评分说明**:
|
||||
- ✅ **优点**:
|
||||
- 代码结构相对清晰,已进行模块化拆分
|
||||
- 异常处理覆盖较全面(虽然过于宽泛)
|
||||
- 有日志记录机制
|
||||
- 部分代码使用了类型注解
|
||||
|
||||
- ⚠️ **缺点**:
|
||||
- 硬编码路径严重影响可移植性
|
||||
- 异常捕获过于宽泛,可能隐藏错误
|
||||
- 递归调用存在栈溢出风险
|
||||
- 代码风格不统一
|
||||
- 大量 TODO 标记未处理
|
||||
|
||||
---
|
||||
|
||||
### 最关键需要修复的 3 个问题
|
||||
|
||||
1. **硬编码绝对路径** (`run_cli.py`, `Underlying_Operations.py`) ✅ **已修复**
|
||||
- **影响**: 代码无法在其他机器上运行
|
||||
- **优先级**: 🔴 最高
|
||||
- **修复时间**: 约 30 分钟
|
||||
- **修复状态**: ✅ 已完成,使用环境变量和 `os.path.expanduser()` 替代硬编码路径
|
||||
|
||||
2. **递归调用栈溢出风险** (`douyin/core/douyin_fudai.py:1570`) ✅ **已修复**
|
||||
- **影响**: 可能导致程序崩溃
|
||||
- **优先级**: 🔴 最高
|
||||
- **修复时间**: 约 1 小时
|
||||
- **修复状态**: ✅ 已完成,添加递归深度限制(最大深度 3)
|
||||
|
||||
3. **过于宽泛的异常捕获** (64 个文件,1514 处)
|
||||
- **影响**: 难以调试,可能隐藏关键错误
|
||||
- **优先级**: 🟡 高
|
||||
- **修复时间**: 需要逐步修复,建议分阶段进行
|
||||
|
||||
---
|
||||
|
||||
### 整体改进建议
|
||||
|
||||
#### 短期(1-2周)
|
||||
1. ✅ **已完成** - 修复硬编码路径问题
|
||||
2. ✅ **已完成** - 添加递归深度限制
|
||||
3. ⏳ **进行中** - 修复关键路径的异常处理(至少前 10 个最常用的文件)
|
||||
|
||||
#### 中期(1-2月)
|
||||
1. 统一代码风格(使用格式化工具)
|
||||
2. 完善类型注解
|
||||
3. 清理和完成重要的 TODO 标记
|
||||
4. 添加单元测试覆盖关键逻辑
|
||||
|
||||
#### 长期(3-6月)
|
||||
1. 重构大文件,进一步模块化
|
||||
2. 建立代码审查流程
|
||||
3. 添加 CI/CD 流程
|
||||
4. 完善文档和注释
|
||||
|
||||
---
|
||||
|
||||
### 代码审查统计
|
||||
|
||||
| 类别 | 数量 | 严重程度 |
|
||||
|------|------|----------|
|
||||
| 硬编码路径 | 2 | 🔴 严重 |
|
||||
| 递归调用风险 | 1 | 🔴 严重 |
|
||||
| 宽泛异常捕获 | 1514 | 🟡 中等 |
|
||||
| 无限循环 | 11 | 🟡 中等 |
|
||||
| TODO/FIXME | 333 | 🟢 低 |
|
||||
| 文件过大 | 2 | 🟡 中等 |
|
||||
|
||||
---
|
||||
|
||||
### 审查方法说明
|
||||
|
||||
本次审查采用了以下方法:
|
||||
1. **静态代码分析**: 使用 grep 搜索常见问题模式
|
||||
2. **语义搜索**: 使用 codebase_search 查找特定问题
|
||||
3. **文件检查**: 检查关键文件的具体实现
|
||||
4. **Linter 检查**: 使用 Pylance 检查类型错误
|
||||
|
||||
---
|
||||
|
||||
## 四、未发现的问题
|
||||
|
||||
经过系统性检查,以下方面**未发现明显问题**:
|
||||
|
||||
1. ✅ **语法错误**: 所有 Python 文件语法正确
|
||||
2. ✅ **导入错误**: 未发现明显的导入问题
|
||||
3. ✅ **安全漏洞**: 未发现明显的安全漏洞(如 SQL 注入、命令注入等)
|
||||
4. ✅ **内存泄漏**: 未发现明显的内存泄漏模式
|
||||
5. ✅ **竞态条件**: 未发现明显的线程安全问题(但需要进一步测试验证)
|
||||
|
||||
---
|
||||
|
||||
**审查完成时间**: 2025-12-28
|
||||
**审查工具**: Cursor AI, Pylance, grep, codebase_search
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Markdown文件修复指南
|
||||
|
||||
## 问题诊断
|
||||
|
||||
如果遇到 "无法打开 MODULARIZATION SUMMARY.md" 或 "Assertion Failed: Argument is 'undefined' or 'null" 错误,这通常是IDE的文件名解析问题。
|
||||
|
||||
## 已完成的修复
|
||||
|
||||
✅ 所有33个Markdown文件已统一为UTF-8编码(无BOM)
|
||||
✅ 移除了所有BOM标记
|
||||
✅ 确保文件格式正确
|
||||
|
||||
## 解决方案
|
||||
|
||||
### 方案1:重启IDE
|
||||
1. 完全关闭IDE(VS Code / Cursor)
|
||||
2. 重新打开IDE
|
||||
3. 重新打开项目
|
||||
|
||||
### 方案2:清除IDE缓存
|
||||
1. 关闭IDE
|
||||
2. 删除以下目录(如果存在):
|
||||
- `.vscode/` 目录
|
||||
- `.cursor/` 目录中的缓存文件
|
||||
3. 重新打开项目
|
||||
|
||||
### 方案3:手动打开文件
|
||||
1. 在文件资源管理器中找到文件
|
||||
2. 右键点击 `MODULARIZATION_SUMMARY.md`
|
||||
3. 选择"打开方式" → 选择你的IDE
|
||||
|
||||
### 方案4:检查文件路径
|
||||
确保文件路径中没有特殊字符或空格:
|
||||
- ✅ 正确:`MODULARIZATION_SUMMARY.md`
|
||||
- ❌ 错误:`MODULARIZATION SUMMARY.md`(有空格)
|
||||
|
||||
### 方案5:重新索引项目
|
||||
在IDE中:
|
||||
1. 打开命令面板(Ctrl+Shift+P)
|
||||
2. 运行 "Reload Window" 或 "Developer: Reload Window"
|
||||
3. 或者运行 "File: Reopen Folder"
|
||||
|
||||
## 验证文件是否正常
|
||||
|
||||
运行以下命令检查文件:
|
||||
```bash
|
||||
python check_md_files.py
|
||||
```
|
||||
|
||||
如果所有文件显示 `[OK]`,说明文件本身没有问题。
|
||||
|
||||
## 如果问题仍然存在
|
||||
|
||||
1. 检查IDE的日志文件,查看具体错误信息
|
||||
2. 尝试用其他编辑器(如Notepad++)打开文件,确认文件本身没问题
|
||||
3. 检查文件权限,确保有读取权限
|
||||
4. 如果是在Windows上,检查文件名是否包含保留字符
|
||||
|
||||
## 文件列表
|
||||
|
||||
已修复的主要Markdown文件:
|
||||
- `MODULARIZATION_SUMMARY.md` - 模块化工作总结
|
||||
- `README.md` - 项目主文档
|
||||
- `douyin/README.md` - 核心模块文档
|
||||
- `douyin/fudai/core/MODULARIZATION_PLAN.md` - 模块化计划
|
||||
- `docs/` 目录下的所有文档
|
||||
|
||||
所有文件现在都使用UTF-8编码,应该可以在任何现代编辑器中正常打开。
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
基于 ADB + OCR + 像素检测 + 模板匹配技术
|
||||
|
||||
[](version.py)
|
||||
[](version.py)
|
||||
[](https://www.python.org/)
|
||||
[](https://www.microsoft.com/windows)
|
||||
|
||||
@@ -30,6 +30,24 @@
|
||||
|
||||
## 📋 版本更新日志
|
||||
|
||||
### V3.3.3 (2025-12-28)
|
||||
|
||||
- ✨ 新增:30分钟超时保护机制
|
||||
- 自动检测长时间无参与的情况,防止脚本卡在无效状态
|
||||
- 可配置超时时间(默认30分钟)
|
||||
- 超时后自动返回推荐页面重新开始
|
||||
- 🐛 修复:修复模板和截图路径配置问题
|
||||
- 统一使用项目根目录的 `assets` 和 `pic` 目录
|
||||
- 修复直播间检测模板文件路径错误
|
||||
- 确保所有模板文件路径配置正确
|
||||
- 🔧 优化:路径配置统一化
|
||||
- 使用 `path_config.py` 统一管理所有文件路径
|
||||
- 简化路径配置逻辑,提高代码可维护性
|
||||
- 📝 更新:完善文档和流程图
|
||||
- 更新流程图以反映30分钟超时检查
|
||||
- 修正阶段诊断步骤编号
|
||||
- 完善预约回退子流程图
|
||||
|
||||
### V3.3.2 (2025-12-25)
|
||||
|
||||
- 🐛 修复:修复预约回退功能不生效的问题
|
||||
@@ -229,6 +247,14 @@ pytest tests/unit/test_example.py::test_some_behavior -q
|
||||
- 支持切换N次后回到第一个直播间(循环模式)
|
||||
- 智能处理直播结束、网络异常等情况
|
||||
|
||||
### 11. 30分钟超时保护
|
||||
|
||||
- 自动检测长时间无参与的情况
|
||||
- 防止脚本在无效状态下卡死
|
||||
- 可配置超时时间(默认30分钟)
|
||||
- 超时后自动返回推荐页面重新开始
|
||||
- 记录最后成功参与时间,提高脚本稳定性
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 技术架构
|
||||
@@ -509,6 +535,7 @@ python run_cli.py \
|
||||
| `live_room_match_threshold` | float | `0.8` | 直播间检测阈值(0.0~1.0),值越高越严格,建议≥0.8 |
|
||||
| `stage_diag_max_time` | float | `15.0` | 阶段诊断的最大耗时(秒) |
|
||||
| `stage_diag_max_step_time` | float | `4.0` | 阶段诊断单步的最大耗时(秒) |
|
||||
`no_attend_timeout_minutes` | float | `30.0` | 30分钟超时保护:距离最后成功参与超过该分钟数则返回推荐页面(0表示禁用) |
|
||||
|
||||
### 福袋筛选设置
|
||||
|
||||
@@ -688,6 +715,11 @@ python run_cli.py \
|
||||
│
|
||||
├─> 初始化(加载配置、连接设备)
|
||||
│
|
||||
├─> 30分钟超时检查(防止脚本卡死)
|
||||
│ ├─> 检查最后参与时间是否超过30分钟
|
||||
│ ├─> 是 → 返回推荐页面重新开始
|
||||
│ └─> 否 → 继续执行
|
||||
│
|
||||
├─> 阶段诊断(判断当前页面)
|
||||
│ ├─> 直播间?
|
||||
│ │ ├─> 是 → 检测福袋图标
|
||||
@@ -1263,6 +1295,15 @@ python run_cli.py \
|
||||
3. 尝试点击"强制停止"按钮
|
||||
4. 重启脚本或设备
|
||||
|
||||
### Q10.5: 脚本长时间没有参与福袋怎么办?
|
||||
|
||||
**A**:
|
||||
1. 这是 V3.3.3+ 新增的30分钟超时保护机制在工作
|
||||
2. 脚本会自动检测30分钟内没有成功参与福袋的情况
|
||||
3. 超时后自动返回推荐页面,重新开始正常的直播间切换流程
|
||||
4. 这有助于防止脚本在无效直播间或异常状态下卡死
|
||||
5. 如果不想启用此功能,可在配置中设置 `no_attend_timeout_minutes: 0`
|
||||
|
||||
### Q11: 如何更新脚本?
|
||||
|
||||
**A**:
|
||||
@@ -1279,10 +1320,28 @@ python run_cli.py \
|
||||
|
||||
## 📜 版本历史
|
||||
|
||||
### V3.3.2 (2025-12-25)
|
||||
### V3.3.3 (2025-12-28)
|
||||
|
||||
**当前版本**
|
||||
|
||||
- ✨ 新增:30分钟超时保护机制
|
||||
- 自动检测长时间无参与的情况,防止脚本卡在无效状态
|
||||
- 可配置超时时间(默认30分钟)
|
||||
- 超时后自动返回推荐页面重新开始
|
||||
- 🐛 修复:修复模板和截图路径配置问题
|
||||
- 统一使用项目根目录的 `assets` 和 `pic` 目录
|
||||
- 修复直播间检测模板文件路径错误
|
||||
- 确保所有模板文件路径配置正确
|
||||
- 🔧 优化:路径配置统一化
|
||||
- 使用 `path_config.py` 统一管理所有文件路径
|
||||
- 简化路径配置逻辑,提高代码可维护性
|
||||
- 📝 更新:完善文档和流程图
|
||||
- 更新流程图以反映30分钟超时检查
|
||||
- 修正阶段诊断步骤编号
|
||||
- 完善预约回退子流程图
|
||||
|
||||
### V3.3.2 (2025-12-25)
|
||||
|
||||
- 🐛 修复:修复预约回退功能不生效的问题
|
||||
- 修复 `needswitch` 配置未从 `config.json` 正确加载的问题
|
||||
- 修复 `self.reservations` 未从状态文件加载的问题
|
||||
@@ -1290,7 +1349,6 @@ python run_cli.py \
|
||||
- 🔧 优化:预约回退逻辑优化
|
||||
- 每次 `run_once_basic` 执行时自动从状态文件加载预约数据
|
||||
- 确保预约队列始终包含最新数据
|
||||
- 📝 更新:完善文档和流程图
|
||||
|
||||
### V3.3.1 (2025-12-14)
|
||||
|
||||
|
||||
@@ -36,8 +36,20 @@ except Exception:
|
||||
_RESAMPLE = Image
|
||||
|
||||
# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用
|
||||
_EXTERNAL_AXF_SCREENSHOT = (
|
||||
r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf\pic\screenshot.png"
|
||||
# 使用环境变量或默认路径,避免硬编码用户路径
|
||||
_EXTERNAL_AXF_SCREENSHOT = os.path.join(
|
||||
os.environ.get(
|
||||
"EXTERNAL_DOUYIN_FUDAI_DIR",
|
||||
os.path.join(
|
||||
os.path.expanduser("~"),
|
||||
".cursor",
|
||||
"worktrees",
|
||||
"douyin_guaji-main",
|
||||
"axf"
|
||||
)
|
||||
),
|
||||
"pic",
|
||||
"screenshot.png"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""检查所有Markdown文件的编码和完整性"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def check_md_file(file_path):
|
||||
"""检查单个MD文件"""
|
||||
issues = []
|
||||
try:
|
||||
# 尝试以UTF-8读取
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
# 检查文件大小
|
||||
file_size = os.path.getsize(file_path)
|
||||
if file_size == 0:
|
||||
issues.append("文件为空")
|
||||
|
||||
# 检查是否有BOM
|
||||
if content.startswith("\ufeff"):
|
||||
issues.append("包含UTF-8 BOM标记")
|
||||
|
||||
# 检查是否有异常字符
|
||||
try:
|
||||
content.encode("utf-8")
|
||||
except UnicodeEncodeError as e:
|
||||
issues.append(f"编码错误: {e}")
|
||||
|
||||
# 检查基本格式
|
||||
if not content.strip():
|
||||
issues.append("文件内容为空(只有空白字符)")
|
||||
|
||||
return issues
|
||||
|
||||
except UnicodeDecodeError as e:
|
||||
return [f"无法以UTF-8解码: {e}"]
|
||||
except Exception as e:
|
||||
return [f"读取文件时出错: {e}"]
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
project_root = Path(__file__).parent
|
||||
md_files = list(project_root.rglob("*.md"))
|
||||
|
||||
print(f"找到 {len(md_files)} 个Markdown文件\n")
|
||||
|
||||
all_ok = True
|
||||
for md_file in sorted(md_files):
|
||||
relative_path = md_file.relative_to(project_root)
|
||||
issues = check_md_file(md_file)
|
||||
|
||||
if issues:
|
||||
print(f"[ERROR] {relative_path}")
|
||||
for issue in issues:
|
||||
print(f" - {issue}")
|
||||
all_ok = False
|
||||
else:
|
||||
file_size = os.path.getsize(md_file)
|
||||
print(f"[OK] {relative_path} ({file_size} bytes)")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
if all_ok:
|
||||
print("[SUCCESS] All Markdown files are valid!")
|
||||
else:
|
||||
print("[WARNING] Found some issues, please check above")
|
||||
|
||||
return 0 if all_ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"needswitch": false,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"y_pianyi": 0,
|
||||
"contains_not_want": [
|
||||
"首饰盒"
|
||||
],
|
||||
"min_prize_value_yuan": 200.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 120,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 50,
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"lucky_draw_red_ratio_threshold": 0.8,
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 500.0,
|
||||
"high_value_fudai_join_ahead_seconds": 120,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
"high_value_fudai_after_action": "continue",
|
||||
"high_value_room_revisit_enabled": true,
|
||||
"high_value_room_revisit_only_current_run": true,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.5,
|
||||
"reservation_preempt_min_value": 0.0,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_icon_max_wait_seconds": 8.5,
|
||||
"fudai_click_wait_seconds": 1.7,
|
||||
"switch_room_wait_after_stage_diag_seconds": 4.0,
|
||||
"live_room_match_threshold": 0.6,
|
||||
"fudai_quiet_hours_enabled": true,
|
||||
"fudai_quiet_start_hour": 2,
|
||||
"fudai_quiet_end_hour": 9,
|
||||
"stage_diag_max_time": 5.0,
|
||||
"stage_diag_max_step_time": 2.0,
|
||||
"enable_ocr_mode1": false,
|
||||
"fudai_template_match_enabled": false,
|
||||
"fudai_template_match_threshold": 0.7,
|
||||
"fudai_detail_template_threshold": 0.54,
|
||||
"coupon_template_match_threshold": 0.4,
|
||||
"attend_button_red_ratio_threshold": 0.25,
|
||||
"fansclub_join_red_ratio_threshold": 0.25,
|
||||
"skip_if_countdown_lt_seconds": 5,
|
||||
"debug_captures": {
|
||||
"enabled": true,
|
||||
"auto_cleanup": true,
|
||||
"keep_days": 3,
|
||||
"max_files": 2000
|
||||
},
|
||||
"yanghao_enabled": false,
|
||||
"yanghao_enable_actions": false,
|
||||
"yanghao_recommend_duration_seconds": 206,
|
||||
"yanghao_recommend_interval_seconds": 570,
|
||||
"yanghao_like_prob": 1.0,
|
||||
"yanghao_fav_prob": 0.85,
|
||||
"yanghao_comment_prob": 1.0,
|
||||
"yanghao_icon_roi_size": 240,
|
||||
"yanghao_icon_match_threshold": 0.77,
|
||||
"yanghao_step_screenshot": false,
|
||||
"yanghao_like_roi_offset_x": 0,
|
||||
"yanghao_like_roi_offset_y": -50,
|
||||
"yanghao_fav_roi_offset_x": 40,
|
||||
"yanghao_fav_roi_offset_y": 0,
|
||||
"yanghao_like_icon_x": 0,
|
||||
"yanghao_like_icon_y": -1,
|
||||
"yanghao_fav_icon_x": -1,
|
||||
"yanghao_fav_icon_y": 0,
|
||||
"yanghao_like_template_path": "assets/like.png",
|
||||
"yanghao_fav_template_path": "assets/fav.png",
|
||||
"yanghao_after_dwell_swipe_direction": "up",
|
||||
"yanghao_after_dwell_swipe_distance_px": 900,
|
||||
"yanghao_comment_btn_x": 0,
|
||||
"yanghao_comment_btn_y": -1,
|
||||
"yanghao_comment_input_x": 0,
|
||||
"yanghao_comment_input_y": 0,
|
||||
"yanghao_comment_send_x": 0,
|
||||
"yanghao_comment_send_y": -1,
|
||||
"yanghao_comment_close_x": 0,
|
||||
"yanghao_comment_close_y": 0,
|
||||
"yanghao_comment_texts": [],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": []
|
||||
}
|
||||
+18
-11
@@ -1,8 +1,8 @@
|
||||
# 抖音福袋挂机程序流程图(完整版)
|
||||
|
||||
**版本**: V3.3.2+
|
||||
**最后更新**: 2025-12-25
|
||||
**主要更新**: 预约回退功能修复、状态文件自动加载、配置加载优化
|
||||
**版本**: V3.3.3+
|
||||
**最后更新**: 2025-12-28
|
||||
**主要更新**: 30分钟超时保护、路径配置统一化、流程图完善
|
||||
|
||||
## 主流程图
|
||||
|
||||
@@ -15,14 +15,14 @@ flowchart TD
|
||||
CheckTime -->|是| MainLoop[主循环开始]
|
||||
|
||||
MainLoop --> CheckTimeout{检查30分钟超时<br/>V3.3.3+}
|
||||
CheckTimeout --> CheckLastAttend{是否成功参与过?}
|
||||
CheckTimeout --> CheckLastAttend{是否成功参与过福袋?}
|
||||
CheckLastAttend -->|是| CheckElapsed{距离最后参与<br/>是否超过30分钟?}
|
||||
CheckLastAttend -->|否| CheckRunTime{运行时间<br/>是否超过30分钟?}
|
||||
|
||||
|
||||
CheckElapsed -->|是| ReturnToRecommend[返回推荐页面<br/>多次点击返回键<br/>最多10次]
|
||||
CheckElapsed -->|否| CheckReservation
|
||||
CheckElapsed -->|否| LoadReservations
|
||||
CheckRunTime -->|是| ReturnToRecommend
|
||||
CheckRunTime -->|否| CheckReservation
|
||||
CheckRunTime -->|否| LoadReservations
|
||||
|
||||
ReturnToRecommend --> ClickFollow[点击关注标签]
|
||||
ClickFollow --> EnterLive[点击进入直播间<br/>连点2次]
|
||||
@@ -231,9 +231,9 @@ flowchart TD
|
||||
CheckOCRCoupon -->|否| CheckAttend
|
||||
|
||||
DetectAttend --> CheckAttend{检测到参与按钮?}
|
||||
CheckAttend -->|是| CheckFansClub
|
||||
CheckAttend -->|否| CheckFansClub
|
||||
|
||||
CheckAttend -->|是| CheckDetail
|
||||
CheckAttend -->|否| CheckDetail
|
||||
|
||||
DetectFansClub --> CheckFansClub{检测到粉丝团?}
|
||||
CheckFansClub -->|是| ReturnFansClub[返回: FANS_CLUB_JOIN]
|
||||
CheckFansClub -->|否| CheckDetail
|
||||
@@ -572,7 +572,13 @@ flowchart TD
|
||||
- **丢弃**: 不满足任何筛选条件
|
||||
- **更新参与时间(V3.3.3+)**: 参与成功后更新 `_last_successful_attend_ts`,用于30分钟超时检查
|
||||
|
||||
### 6. 预约回退决策点(V3.3.2+修复)
|
||||
### 6. 30分钟超时保护决策点(V3.3.3+)
|
||||
- **超时检查**: 检查距离最后成功参与是否超过 `no_attend_timeout_minutes`(默认30分钟)
|
||||
- **运行时间检查**: 如果从未成功参与,检查脚本运行时间是否超过30分钟
|
||||
- **自动恢复**: 超时后自动返回推荐页面,重新开始正常的直播间切换流程
|
||||
- **防止卡死**: 避免脚本在无效状态下长时间运行,提高脚本稳定性
|
||||
|
||||
### 7. 预约回退决策点(V3.3.2+修复)
|
||||
- **配置检查**: 检查 `needswitch` 是否启用(必须为 `true` 才能回退)
|
||||
- **状态文件加载**: 每次 `run_once_basic` 执行时从 `state/reservations.json` 加载预约数据
|
||||
- **预约队列检查**: 检查是否有预约队列且 `high_value_fudai_enabled` 是否启用
|
||||
@@ -609,6 +615,7 @@ flowchart TD
|
||||
|
||||
- **wait_minutes**: 控制主循环运行时间(0=无限循环)
|
||||
- **needswitch**: 控制是否切换直播间(必须为 `true` 才能使用预约回退功能)
|
||||
- **no_attend_timeout_minutes**: 30分钟超时保护时间(0=禁用,防止脚本卡在无效状态)
|
||||
- **min_prize_value_yuan**: 最小价值阈值
|
||||
- **skip_if_countdown_gt_seconds**: 倒计时最大阈值
|
||||
- **high_value_fudai_threshold_yuan**: 高价值阈值
|
||||
|
||||
+42
-130
@@ -33,8 +33,24 @@ from douyin.handlers import douyin_swipe_handler
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
from douyin.stage import douyin_stage_handler
|
||||
|
||||
from .fudai_modules import (
|
||||
NavigationMixin,
|
||||
StageDetectionMixin,
|
||||
PopupHandlerMixin,
|
||||
LotteryResultMixin,
|
||||
RoomUtilsMixin,
|
||||
MainLogicMixin,
|
||||
)
|
||||
|
||||
class fudai_analyse:
|
||||
|
||||
class fudai_analyse(
|
||||
NavigationMixin,
|
||||
StageDetectionMixin,
|
||||
PopupHandlerMixin,
|
||||
LotteryResultMixin,
|
||||
RoomUtilsMixin,
|
||||
MainLogicMixin,
|
||||
):
|
||||
"""福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。"""
|
||||
|
||||
# 类常量:魔法数字提取
|
||||
@@ -261,32 +277,9 @@ class fudai_analyse:
|
||||
self.load_config()
|
||||
|
||||
# ===== 兼容原始脚本的一些简单封装方法 =====
|
||||
def _find_room_pos_by_title(
|
||||
self, target_title: str, target_title_raw: str = ""
|
||||
) -> int | None:
|
||||
"""根据直播间标题在运行时映射表中查找对应的位置。
|
||||
# RoomUtilsMixin 已提供 _find_room_pos_by_title 和 _record_room_title_and_pos 方法
|
||||
|
||||
返回:
|
||||
如果找到匹配的位置,返回位置值;否则返回 None
|
||||
"""
|
||||
return douyin_reservation_handler.ReservationHandler.find_room_pos_by_title(
|
||||
self, target_title, target_title_raw
|
||||
)
|
||||
|
||||
def _record_room_title_and_pos(self) -> None:
|
||||
"""记录当前直播间的标题和位置到运行时映射表。
|
||||
|
||||
用于预约回退校验时验证位置信息。
|
||||
"""
|
||||
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
|
||||
|
||||
def click(self, x: int, y: int) -> None:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
|
||||
douyin_helpers.HelperFunctions.click(self, x, y)
|
||||
|
||||
def load_config(self) -> None:
|
||||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||||
douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined]
|
||||
# NavigationMixin 已提供 click 和 load_config 方法
|
||||
|
||||
# ========== 兼容旧入口:主循环 ==========
|
||||
def fudai_choujiang(
|
||||
@@ -452,56 +445,10 @@ class fudai_analyse:
|
||||
time.sleep(1.0)
|
||||
|
||||
# ========== 阶段诊断 ==========
|
||||
def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]:
|
||||
"""封装到子模块的阶段诊断入口。"""
|
||||
return douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen(
|
||||
self
|
||||
)
|
||||
# StageDetectionMixin 已提供 _diagnose_stage_from_current_screen 方法
|
||||
|
||||
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
|
||||
def cut_pic(
|
||||
self,
|
||||
x_top: int = 1,
|
||||
y_top: int = 1,
|
||||
x_bottom: int = 2,
|
||||
y_bottom: int = 2,
|
||||
target: str = "",
|
||||
cut_pic_name: str = "",
|
||||
y_pianyi: int = 0,
|
||||
) -> None:
|
||||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。"""
|
||||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||||
self, x_top, y_top, x_bottom, y_bottom, target, cut_pic_name, y_pianyi
|
||||
)
|
||||
|
||||
def _read_pixel_stage_state(
|
||||
self, return_details: bool = False
|
||||
) -> dict | tuple[dict, dict]:
|
||||
"""读取像素阶段状态(用于阶段诊断)。
|
||||
|
||||
参数:
|
||||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||||
|
||||
返回:
|
||||
dict: 检测结果(return_details=False时)
|
||||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
return douyin_helpers.HelperFunctions.read_pixel_stage_state(
|
||||
self, return_details
|
||||
)
|
||||
|
||||
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:
|
||||
"""将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。
|
||||
|
||||
返回 (scaled_x, scaled_y)
|
||||
"""
|
||||
return douyin_screenshot_handler.ScreenshotHandler.scale_from_base(
|
||||
self, base_x, base_y
|
||||
)
|
||||
|
||||
def _save_step_screenshot(self, label: str) -> None:
|
||||
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
|
||||
douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label)
|
||||
# NavigationMixin 和 StageDetectionMixin 已提供截图和坐标转换相关方法
|
||||
|
||||
def _check_in_live_room_by_icon(
|
||||
self,
|
||||
@@ -538,18 +485,15 @@ class fudai_analyse:
|
||||
)
|
||||
|
||||
# ========== 弹窗 / 人机校验 ==========
|
||||
def _check_coupon_popup(self) -> bool:
|
||||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。"""
|
||||
return douyin_popup_handler.PopupHandler.check_coupon_popup(self)
|
||||
|
||||
def _check_shopping_redpacket_popup(self) -> bool:
|
||||
"""购物红包中央弹窗。"""
|
||||
return douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup(self)
|
||||
# PopupHandlerMixin 已提供 _check_coupon_popup 和 _check_shopping_redpacket_popup 方法
|
||||
|
||||
# ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ==========
|
||||
def run_once_basic(self) -> None: # type: ignore[complexity]
|
||||
def run_once_basic(self, recursion_depth: int = 0) -> None: # type: ignore[complexity]
|
||||
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。
|
||||
|
||||
参数:
|
||||
recursion_depth: 递归深度,用于防止栈溢出(默认 0)
|
||||
|
||||
注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。
|
||||
"""
|
||||
from douyin.reservation import douyin_reservation_logic # 确保在函数作用域内可用
|
||||
@@ -1622,11 +1566,23 @@ class fudai_analyse:
|
||||
pass
|
||||
# 为避免递归过深,仅在当前检测到不在抖音前台的场景下递归一次;
|
||||
# 自救完成后前台包名应为抖音,下一次 run_once_basic 将不会再次进入自救分支。
|
||||
MAX_RECURSION_DEPTH = 3
|
||||
if recursion_depth >= MAX_RECURSION_DEPTH:
|
||||
try:
|
||||
self._log_kv(
|
||||
"流程",
|
||||
"run_once_basic:达到最大递归深度,停止递归",
|
||||
recursion_depth=recursion_depth,
|
||||
max_depth=MAX_RECURSION_DEPTH,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
self.operation.delay(0.5)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
self.run_once_basic()
|
||||
self.run_once_basic(recursion_depth + 1)
|
||||
return
|
||||
except Exception as e:
|
||||
try:
|
||||
@@ -2244,17 +2200,7 @@ class fudai_analyse:
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
|
||||
def _check_lottery_result_by_ocr(self) -> Optional[str]:
|
||||
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。"""
|
||||
return douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(self)
|
||||
|
||||
def _handle_lottery_result_by_ocr(self, result_type: str) -> None:
|
||||
"""根据OCR识别结果处理开奖结果。
|
||||
|
||||
参数:
|
||||
result_type: "我知道了" 或 "立即领取奖品"
|
||||
"""
|
||||
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type)
|
||||
# LotteryResultMixin 已提供 _check_lottery_result_by_ocr 和 _handle_lottery_result_by_ocr 方法
|
||||
|
||||
def _shot_and_diagnose(
|
||||
self, tag: str, msg: str, device_id: str, diagnose: bool = True
|
||||
@@ -2272,43 +2218,9 @@ class fudai_analyse:
|
||||
)
|
||||
|
||||
# ========== 基础动作封装 ==========
|
||||
def swipe_up_to_next_live(self) -> None:
|
||||
"""上滑切换直播间(简单版封装)。
|
||||
# NavigationMixin 已提供导航相关方法
|
||||
|
||||
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
|
||||
则不允许上划离开预约直播间,直接返回。
|
||||
"""
|
||||
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(self)
|
||||
|
||||
def _return_to_recommend_and_reenter_live(self) -> None:
|
||||
"""返回推荐页面并重新进入直播间。
|
||||
|
||||
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
|
||||
"""
|
||||
douyin_swipe_handler.SwipeHandler.return_to_recommend_and_reenter_live(self)
|
||||
|
||||
def swipe_down_back_from_live(self) -> None:
|
||||
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
|
||||
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(self)
|
||||
|
||||
def _maybe_reset_after_swipes(self) -> int:
|
||||
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
|
||||
|
||||
返回:
|
||||
重置后的滑动次数(通常为0)
|
||||
"""
|
||||
return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self)
|
||||
|
||||
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
|
||||
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
|
||||
|
||||
说明:
|
||||
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
|
||||
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
|
||||
"""
|
||||
return douyin_reservation_handler.ReservationHandler.seek_reservation_room(
|
||||
self, item
|
||||
)
|
||||
# RoomUtilsMixin 已提供 _seek_reservation_room 方法
|
||||
|
||||
# ========== 福袋相关 ==========
|
||||
def _handle_reservation_direct_attend(self) -> None:
|
||||
|
||||
@@ -60,10 +60,38 @@ class MainFlowController:
|
||||
# 记录运行开始时间
|
||||
analyser._run_start_ts = time.time()
|
||||
|
||||
# 主循环
|
||||
# 主循环(添加安全限制,防止无限运行)
|
||||
loop_count = 0
|
||||
max_loops = 10000 # 最大循环次数,防止无限运行
|
||||
start_time = time.time()
|
||||
|
||||
while True:
|
||||
loop_count += 1
|
||||
|
||||
# 安全检查:防止无限循环
|
||||
if loop_count > max_loops:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", "达到最大循环次数限制,停止运行",
|
||||
loop_count=loop_count,
|
||||
max_loops=max_loops,
|
||||
run_time_seconds=round(time.time() - start_time, 1)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
# 检查运行时间限制(例如24小时)
|
||||
if time.time() - start_time > 24 * 3600:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", "达到最大运行时间限制,停止运行",
|
||||
run_time_hours=round((time.time() - start_time) / 3600, 1)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", f"主循环第 {loop_count} 次", loop_count=loop_count
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""福袋主逻辑模块化组件
|
||||
|
||||
包含从 douyin_fudai.py 拆分出的各个功能模块。
|
||||
"""
|
||||
|
||||
from .base_interface import BaseFudaiMixin, FudaiAnalyzerInterface
|
||||
from .fudai_navigation import NavigationMixin
|
||||
from .fudai_stage_detection import StageDetectionMixin
|
||||
from .fudai_popup_handler import PopupHandlerMixin
|
||||
from .fudai_lottery_result import LotteryResultMixin
|
||||
from .fudai_room_utils import RoomUtilsMixin
|
||||
from .fudai_main_logic import MainLogicMixin
|
||||
|
||||
__all__ = [
|
||||
"BaseFudaiMixin",
|
||||
"FudaiAnalyzerInterface",
|
||||
"NavigationMixin",
|
||||
"StageDetectionMixin",
|
||||
"PopupHandlerMixin",
|
||||
"LotteryResultMixin",
|
||||
"RoomUtilsMixin",
|
||||
"MainLogicMixin",
|
||||
]
|
||||
@@ -0,0 +1,77 @@
|
||||
"""福袋分析器基础接口
|
||||
|
||||
定义所有福袋分析器混入类需要的基础方法和属性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Protocol, Optional
|
||||
from abc import ABC
|
||||
|
||||
|
||||
class FudaiAnalyzerInterface(Protocol):
|
||||
"""福袋分析器接口协议"""
|
||||
|
||||
# 基本属性
|
||||
device_id: str
|
||||
y_pianyi: int
|
||||
needswitch: bool
|
||||
resolution_ratio_x: int
|
||||
resolution_ratio_y: int
|
||||
|
||||
# 基础操作属性
|
||||
operation: Any # 底层操作对象
|
||||
|
||||
# 日志方法
|
||||
def _enhanced_log_kv(self, *args, **fields) -> None: ...
|
||||
|
||||
# 基础操作方法
|
||||
def click(self, x: int, y: int) -> None: ...
|
||||
def load_config(self) -> None: ...
|
||||
def cut_pic(
|
||||
self,
|
||||
x1: int,
|
||||
y1: int,
|
||||
x2: int,
|
||||
y2: int,
|
||||
name: str = "",
|
||||
desc: str = "",
|
||||
y_pianyi: int = 0,
|
||||
) -> None: ...
|
||||
|
||||
# 其他基础方法
|
||||
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]: ...
|
||||
def _save_step_screenshot(self, label: str) -> None: ...
|
||||
|
||||
|
||||
class BaseFudaiMixin:
|
||||
"""基础混入类,提供通用功能"""
|
||||
|
||||
def _safe_log(self, *args, **fields) -> None:
|
||||
"""安全的日志记录,避免依赖主类的日志方法"""
|
||||
try:
|
||||
# 尝试调用主类的日志方法
|
||||
if hasattr(self, '_enhanced_log_kv'):
|
||||
self._enhanced_log_kv(*args, **fields) # type: ignore
|
||||
else:
|
||||
# 兜底:使用标准print
|
||||
print(f"[LOG] {args} {fields}")
|
||||
except Exception:
|
||||
# 最后兜底
|
||||
print(f"[LOG] {args} {fields}")
|
||||
|
||||
def _safe_operation_call(self, operation_name: str, *args, **kwargs) -> Any:
|
||||
"""安全的操作调用,避免依赖未定义的属性"""
|
||||
try:
|
||||
if hasattr(self, operation_name):
|
||||
method = getattr(self, operation_name)
|
||||
if callable(method):
|
||||
return method(*args, **kwargs)
|
||||
else:
|
||||
self._safe_log("警告", f"方法 {operation_name} 不可用")
|
||||
except Exception as e:
|
||||
self._safe_log("错误", f"调用 {operation_name} 失败", error=str(e))
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""福袋开奖结果处理模块
|
||||
|
||||
包含开奖结果的OCR识别和处理功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class LotteryResultMixin:
|
||||
"""开奖结果处理功能混入类"""
|
||||
|
||||
def _check_lottery_result_by_ocr(self) -> Optional[str]:
|
||||
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。"""
|
||||
from douyin.utils import douyin_helpers
|
||||
return douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(self)
|
||||
|
||||
def _handle_lottery_result_by_ocr(self, result_type: str) -> None:
|
||||
"""根据OCR识别结果处理开奖结果。
|
||||
|
||||
参数:
|
||||
result_type: "我知道了" 或 "立即领取奖品"
|
||||
"""
|
||||
from douyin.utils import douyin_helpers
|
||||
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""福袋主逻辑模块
|
||||
|
||||
包含主要的业务逻辑和流程控制。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from .base_interface import BaseFudaiMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class MainLogicMixin(BaseFudaiMixin):
|
||||
"""主业务逻辑混入类"""
|
||||
|
||||
def _enhanced_log_kv(self, *args, **fields):
|
||||
"""增强版日志记录:自动添加时间戳、设备ID等通用字段。"""
|
||||
try:
|
||||
from douyin.logging import douyin_logging_wrapper
|
||||
douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(self, *args, **fields)
|
||||
except Exception:
|
||||
# 兜底:如果增强日志失败,使用标准日志
|
||||
print(f"[LOG] {args} {fields}")
|
||||
|
||||
def _log_step_time(self, step_name: str, start_time: float) -> None:
|
||||
"""记录步骤耗时(带格式化)。"""
|
||||
try:
|
||||
elapsed = time.time() - start_time
|
||||
self._enhanced_log_kv(
|
||||
"性能",
|
||||
f"{step_name} 耗时",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
step=step_name
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def fudai_choujiang(
|
||||
self,
|
||||
device_id: str = "",
|
||||
y_pianyi: int = 0,
|
||||
needswitch: bool = False,
|
||||
wait_minutes: int = 15,
|
||||
) -> None:
|
||||
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
|
||||
self.device_id = device_id or getattr(self, 'device_id', "")
|
||||
self.y_pianyi = int(y_pianyi or getattr(self, 'y_pianyi', 0))
|
||||
# 保存是否允许切换直播间的配置,供后续所有逻辑统一使用
|
||||
try:
|
||||
self.needswitch = bool(needswitch)
|
||||
except Exception:
|
||||
# 兜底:若赋值失败,则保持原有行为(默认允许切换)
|
||||
self.needswitch = True
|
||||
try:
|
||||
operation = getattr(self, 'operation', None)
|
||||
if operation and hasattr(operation, 'get_device_resolution'):
|
||||
rx, ry = operation.get_device_resolution(self.device_id)
|
||||
self.resolution_ratio_x, self.resolution_ratio_y = int(rx or 1080), int(
|
||||
ry or 2400
|
||||
)
|
||||
else:
|
||||
# 兜底分辨率
|
||||
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
|
||||
except Exception:
|
||||
# 兜底分辨率
|
||||
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
|
||||
|
||||
# 加载配置
|
||||
self._safe_operation_call("load_config")
|
||||
|
||||
# 主循环
|
||||
self._safe_operation_call("run_once_basic")
|
||||
|
||||
def _handle_reservation_direct_attend(self) -> None:
|
||||
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。"""
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend(
|
||||
self
|
||||
)
|
||||
|
||||
def _handle_in_fudai_detail(self) -> None:
|
||||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
|
||||
start_time = time.time()
|
||||
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
|
||||
|
||||
# 这里应该包含主要的福袋处理逻辑
|
||||
# 由于代码太长,这里暂时保留调用原有handler的逻辑
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_flow
|
||||
# 动态检查FudaiFlow是否存在
|
||||
if hasattr(douyin_fudai_flow, 'FudaiFlow'):
|
||||
flow_class = getattr(douyin_fudai_flow, 'FudaiFlow')
|
||||
if hasattr(flow_class, 'handle_in_fudai_detail'):
|
||||
flow_class.handle_in_fudai_detail(self)
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow.handle_in_fudai_detail 方法不可用")
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow 类不可用")
|
||||
except Exception as e:
|
||||
self._safe_log("错误", "_handle_in_fudai_detail 调用失败", error=str(e))
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
self._safe_log(
|
||||
"性能",
|
||||
"_handle_in_fudai_detail 耗时",
|
||||
elapsed_seconds=round(elapsed, 2)
|
||||
)
|
||||
|
||||
def _handle_live_room_has_or_not_fudai(self) -> None:
|
||||
"""直播间有无福袋的处理逻辑。"""
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_flow
|
||||
# 动态检查FudaiFlow是否存在
|
||||
if hasattr(douyin_fudai_flow, 'FudaiFlow'):
|
||||
flow_class = getattr(douyin_fudai_flow, 'FudaiFlow')
|
||||
if hasattr(flow_class, 'handle_live_room_has_or_not_fudai'):
|
||||
flow_class.handle_live_room_has_or_not_fudai(self)
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow.handle_live_room_has_or_not_fudai 方法不可用")
|
||||
else:
|
||||
self._safe_log("警告", "FudaiFlow 类不可用")
|
||||
except Exception as e:
|
||||
self._safe_log("错误", "_handle_live_room_has_or_not_fudai 调用失败", error=str(e))
|
||||
@@ -0,0 +1,93 @@
|
||||
"""福袋导航和交互模块
|
||||
|
||||
包含基本的导航、点击、滑动等交互功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from .base_interface import BaseFudaiMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class NavigationMixin(BaseFudaiMixin):
|
||||
"""导航和基础交互功能混入类"""
|
||||
|
||||
def click(self, x: int, y: int) -> None:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
|
||||
from douyin.utils import douyin_helpers
|
||||
douyin_helpers.HelperFunctions.click(self, x, y)
|
||||
|
||||
def load_config(self) -> None:
|
||||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||||
from douyin.utils import douyin_config
|
||||
douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined]
|
||||
|
||||
def cut_pic(
|
||||
self,
|
||||
x1: int,
|
||||
y1: int,
|
||||
x2: int,
|
||||
y2: int,
|
||||
name: str = "",
|
||||
desc: str = "",
|
||||
y_pianyi: int = 0,
|
||||
) -> None:
|
||||
"""截取指定区域的图片(兼容原版接口)。"""
|
||||
from douyin.handlers import douyin_screenshot_handler
|
||||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||||
self, x1, y1, x2, y2, name, desc, y_pianyi
|
||||
)
|
||||
|
||||
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:
|
||||
"""根据当前设备分辨率,从基准分辨率(1080x2400)缩放到实际分辨率。"""
|
||||
rx = getattr(self, "resolution_ratio_x", 1080) or 1080
|
||||
ry = getattr(self, "resolution_ratio_y", 2400) or 2400
|
||||
scaled_x = int(base_x * rx // 1080)
|
||||
scaled_y = int(base_y * ry // 2400)
|
||||
return scaled_x, scaled_y
|
||||
|
||||
def _save_step_screenshot(self, label: str) -> None:
|
||||
"""保存步骤截图用于调试(带时间戳)。"""
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_handler
|
||||
douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(
|
||||
self, label
|
||||
)
|
||||
except Exception as e:
|
||||
self._safe_log("调试", "保存步骤截图失败", error=str(e), label=label)
|
||||
|
||||
def swipe_up_to_next_live(self) -> None:
|
||||
"""上滑切换直播间(简单版封装)。
|
||||
|
||||
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
|
||||
则不允许上划离开预约直播间,直接返回。
|
||||
"""
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(self)
|
||||
|
||||
def _return_to_recommend_and_reenter_live(self) -> None:
|
||||
"""返回推荐页面并重新进入直播间。
|
||||
|
||||
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
|
||||
"""
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
douyin_swipe_handler.SwipeHandler.return_to_recommend_and_reenter_live(self)
|
||||
|
||||
def swipe_down_back_from_live(self) -> None:
|
||||
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(self)
|
||||
|
||||
def _maybe_reset_after_swipes(self) -> int:
|
||||
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
|
||||
|
||||
返回:
|
||||
重置后的滑动次数(通常为0)
|
||||
"""
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""福袋弹窗处理模块
|
||||
|
||||
包含各种弹窗的检测和处理功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base_interface import BaseFudaiMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class PopupHandlerMixin(BaseFudaiMixin):
|
||||
"""弹窗处理功能混入类"""
|
||||
|
||||
def _check_coupon_popup(self) -> bool:
|
||||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。"""
|
||||
from douyin.handlers import douyin_popup_handler
|
||||
return douyin_popup_handler.PopupHandler.check_coupon_popup(self)
|
||||
|
||||
def _check_shopping_redpacket_popup(self) -> bool:
|
||||
"""购物红包中央弹窗。"""
|
||||
from douyin.handlers import douyin_popup_handler
|
||||
return douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup(self)
|
||||
|
||||
def _shot_and_diagnose(
|
||||
self,
|
||||
operation_type: str,
|
||||
description: str,
|
||||
device_id: str | None = None,
|
||||
force_screenshot: bool = False,
|
||||
) -> None:
|
||||
"""统一截图并诊断方法。
|
||||
|
||||
参数:
|
||||
operation_type: 操作类型(如"开奖诊断"、"详情识别"等)
|
||||
description: 操作描述
|
||||
device_id: 设备ID,如果为None则使用self.device_id
|
||||
force_screenshot: 是否强制截图(忽略缓存)
|
||||
"""
|
||||
try:
|
||||
from douyin.utils import douyin_helpers
|
||||
actual_device_id = device_id or getattr(self, 'device_id', '')
|
||||
douyin_helpers.HelperFunctions.shot_and_diagnose(
|
||||
self, operation_type, description, actual_device_id, force_screenshot
|
||||
)
|
||||
except Exception as e:
|
||||
self._safe_log(
|
||||
"截图诊断",
|
||||
"截图并诊断失败",
|
||||
operation_type=operation_type,
|
||||
description=description,
|
||||
error=str(e),
|
||||
level="WARNING"
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""福袋房间工具模块
|
||||
|
||||
包含房间定位、记录等工具功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class RoomUtilsMixin:
|
||||
"""房间工具功能混入类"""
|
||||
|
||||
def _find_room_pos_by_title(
|
||||
self, target_title: str, target_title_raw: str = ""
|
||||
) -> int | None:
|
||||
"""根据直播间标题在运行时映射表中查找对应的位置。
|
||||
|
||||
返回:
|
||||
如果找到匹配的位置,返回位置值;否则返回 None
|
||||
"""
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
return douyin_reservation_handler.ReservationHandler.find_room_pos_by_title(
|
||||
self, target_title, target_title_raw
|
||||
)
|
||||
|
||||
def _record_room_title_and_pos(self) -> None:
|
||||
"""记录当前直播间的标题和位置到运行时映射表。
|
||||
|
||||
用于预约回退校验时验证位置信息。
|
||||
"""
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
|
||||
|
||||
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
|
||||
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
|
||||
|
||||
说明:
|
||||
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
|
||||
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
|
||||
"""
|
||||
from douyin.reservation import douyin_reservation_handler
|
||||
return douyin_reservation_handler.ReservationHandler.seek_reservation_room(
|
||||
self, item
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""福袋阶段检测模块
|
||||
|
||||
包含屏幕阶段诊断、像素状态检测等功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Tuple, TYPE_CHECKING
|
||||
|
||||
from .base_interface import BaseFudaiMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
class StageDetectionMixin(BaseFudaiMixin):
|
||||
"""阶段检测功能混入类"""
|
||||
|
||||
def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]:
|
||||
"""封装到子模块的阶段诊断入口。"""
|
||||
from douyin.stage import douyin_stage_handler
|
||||
return douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen(
|
||||
self
|
||||
)
|
||||
|
||||
def _read_pixel_stage_state(
|
||||
self, return_details: bool = False
|
||||
) -> dict | tuple[dict, dict]:
|
||||
"""读取像素阶段状态(用于阶段诊断)。
|
||||
|
||||
参数:
|
||||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||||
|
||||
返回:
|
||||
dict: 检测结果(return_details=False时)
|
||||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
from douyin.utils import douyin_helpers
|
||||
result = douyin_helpers.HelperFunctions.read_pixel_stage_state(
|
||||
self, return_details
|
||||
)
|
||||
return result # 明确返回以避免类型推断问题
|
||||
|
||||
def _check_in_live_room_by_icon(self) -> bool:
|
||||
"""通过检测直播间图标来判断是否在直播间内。
|
||||
|
||||
返回:
|
||||
bool: True 表示在直播间内,False 表示不在直播间内
|
||||
"""
|
||||
try:
|
||||
# 读取直播间图标区域的像素状态
|
||||
pixel_state = self._read_pixel_stage_state(return_details=False)
|
||||
|
||||
# 检查是否有直播间相关的特征
|
||||
if isinstance(pixel_state, dict):
|
||||
stage = pixel_state.get("stage", "")
|
||||
confidence = pixel_state.get("confidence", 0)
|
||||
|
||||
# 如果检测到直播间相关阶段且置信度足够高
|
||||
if stage in ["LIVE_ROOM", "LIVE_ROOM_HAS_FUDAI"] and confidence > 0.7:
|
||||
return True
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
self._safe_log(
|
||||
"阶段检测",
|
||||
"直播间图标检测失败",
|
||||
error=str(e),
|
||||
level="WARNING"
|
||||
)
|
||||
return False
|
||||
|
||||
def check_in_fudai_detail(self) -> bool:
|
||||
"""检查当前是否在福袋详情页面。
|
||||
|
||||
返回:
|
||||
bool: True 表示在福袋详情页,False 表示不在
|
||||
"""
|
||||
try:
|
||||
# 使用阶段诊断来判断是否在福袋详情页
|
||||
stage, seen = self._diagnose_stage_from_current_screen()
|
||||
|
||||
# 检查是否是福袋详情相关的阶段
|
||||
fudai_detail_stages = ["FUDAI_DETAIL", "FUDAI_DETAIL_READY"]
|
||||
if stage in fudai_detail_stages:
|
||||
self._safe_log(
|
||||
"阶段检测",
|
||||
"确认在福袋详情页面",
|
||||
stage=stage,
|
||||
seen=seen
|
||||
)
|
||||
return True
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
self._safe_log(
|
||||
"阶段检测",
|
||||
"福袋详情页检测失败",
|
||||
error=str(e),
|
||||
level="WARNING"
|
||||
)
|
||||
return False
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"updated_ts": 1766904368.3123198,
|
||||
"reason": "startup_clear",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "",
|
||||
"current_room_title_raw": "",
|
||||
"reservations": []
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
"""检测核心模块
|
||||
|
||||
本目录包含从 douyin_detection.py 模块化后的检测功能。
|
||||
"""
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后改为从子模块导入
|
||||
from ...detection.douyin_detection import (
|
||||
_ensure_detection_cache,
|
||||
check_detail_height,
|
||||
check_have_fudai_with_ready_screenshot,
|
||||
check_in_fudai_detail,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_ensure_detection_cache",
|
||||
"check_detail_height",
|
||||
"check_have_fudai_with_ready_screenshot",
|
||||
"check_in_fudai_detail",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -307,8 +307,11 @@ def check_have_fudai_with_ready_screenshot(
|
||||
max_loops = int(max_wait_s / retry_delay_s) + 10 # 额外的循环次数保护
|
||||
consecutive_failures = 0 # 连续失败计数
|
||||
max_consecutive_failures = 5 # 最大连续失败次数
|
||||
|
||||
while (time.time() - func_start) < max_wait_s:
|
||||
|
||||
# 额外的时间限制保护,防止死循环
|
||||
absolute_timeout = func_start + max(max_wait_s * 2, 300) # 最长5分钟
|
||||
|
||||
while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout:
|
||||
# 额外的循环次数保护:防止无限循环
|
||||
if loop >= max_loops:
|
||||
try:
|
||||
|
||||
@@ -20,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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return None
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ def detect_coupon_popup_background(
|
||||
try:
|
||||
import cv2 # type: ignore[import-untyped]
|
||||
import numpy as np # type: ignore[import-untyped]
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
@@ -139,7 +139,7 @@ def detect_coupon_popup_background(
|
||||
threshold = float(
|
||||
getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.75
|
||||
else:
|
||||
threshold = 0.75
|
||||
@@ -230,9 +230,9 @@ def detect_lucky_draw_result_popup(
|
||||
debug_path,
|
||||
red_ratio_threshold,
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
red_count = 0
|
||||
@@ -249,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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
if total_samples == 0:
|
||||
@@ -296,9 +296,9 @@ def detect_lucky_draw_result_popup(
|
||||
red_ratio_threshold,
|
||||
red_ratio,
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 如果请求详细信息,返回包含red_ratio的字典
|
||||
@@ -316,7 +316,7 @@ def detect_lucky_draw_result_popup(
|
||||
}
|
||||
|
||||
return result
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False
|
||||
|
||||
|
||||
@@ -370,9 +370,9 @@ def detect_attend_button_red_area(
|
||||
import logging
|
||||
|
||||
logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 采样检测点:检测大片红色区域
|
||||
@@ -387,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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
|
||||
@@ -406,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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.25
|
||||
else:
|
||||
threshold = 0.25
|
||||
@@ -454,9 +454,9 @@ def detect_attend_button_red_area(
|
||||
red_ratio,
|
||||
red_ratio,
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
return result
|
||||
@@ -545,7 +545,7 @@ def detect_fansclub_join_red_area(
|
||||
threshold = float(
|
||||
getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.25
|
||||
else:
|
||||
threshold = 0.25
|
||||
@@ -636,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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
if total_samples == 0:
|
||||
@@ -654,7 +654,7 @@ 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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False, 0.0
|
||||
|
||||
|
||||
@@ -784,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: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
attend_button_threshold = float(
|
||||
getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
fansclub_threshold = float(
|
||||
getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
detection_tasks = {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# douyin_fudai_core.py 模块化计划
|
||||
|
||||
## 当前状态
|
||||
- 文件大小:4720行
|
||||
- 包含11个主要函数
|
||||
|
||||
## 模块化结构
|
||||
|
||||
### 已创建模块
|
||||
1. `fudai_debug_utils.py` - 调试工具函数
|
||||
- `_save_full_screenshot_with_ocr_region`
|
||||
|
||||
### 待创建模块
|
||||
2. `fudai_detail_reader.py` - 福袋详情读取
|
||||
- `get_fudai_contain` (~1100行)
|
||||
- 辅助函数:`_parse_mm_ss`, `_extract_2digits`, `_read_countdown_split`, `_extract_participants_and_clean`
|
||||
|
||||
3. `fudai_attend.py` - 参与抽奖
|
||||
- `attend_choujiang` (~1200行)
|
||||
|
||||
4. `fudai_result_checker.py` - 开奖结果检查
|
||||
- `check_lucky_draw_result`
|
||||
- `check_have_reward_notice_confirm`
|
||||
- `check_in_order_confirm_page`
|
||||
- `get_reward`
|
||||
|
||||
5. `fudai_filter.py` - 过滤判断
|
||||
- `check_contain`
|
||||
- `is_watch_task_fudai`
|
||||
- `should_skip_fudai_by_config`
|
||||
- `basic_join_decision` (~1500行)
|
||||
|
||||
## 迁移策略
|
||||
|
||||
### 阶段1:创建模块结构(当前)
|
||||
- [x] 创建 `douyin/fudai/core/` 目录
|
||||
- [x] 创建 `fudai_debug_utils.py`
|
||||
- [ ] 创建其他模块骨架
|
||||
|
||||
### 阶段2:提取函数
|
||||
- [ ] 提取 `get_fudai_contain` 到 `fudai_detail_reader.py`
|
||||
- [ ] 提取 `attend_choujiang` 到 `fudai_attend.py`
|
||||
- [ ] 提取结果检查函数到 `fudai_result_checker.py`
|
||||
- [ ] 提取过滤函数到 `fudai_filter.py`
|
||||
|
||||
### 阶段3:更新导入
|
||||
- [ ] 更新原文件为 `__init__.py`,重新导出所有函数
|
||||
- [ ] 更新所有导入路径
|
||||
- [ ] 测试向后兼容性
|
||||
|
||||
### 阶段4:清理
|
||||
- [ ] 删除原文件中的函数定义(保留导入)
|
||||
- [ ] 添加类型注解
|
||||
- [ ] 修复Pylance问题
|
||||
|
||||
## 注意事项
|
||||
- 保持向后兼容:所有现有导入必须继续工作
|
||||
- 函数依赖关系复杂,需要仔细处理导入
|
||||
- `get_fudai_contain` 依赖 `_save_full_screenshot_with_ocr_region`
|
||||
- `basic_join_decision` 依赖多个其他函数
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""福袋核心模块
|
||||
|
||||
本目录包含从 douyin_fudai_core.py 模块化后的功能模块。
|
||||
|
||||
向后兼容:所有函数都从原文件重新导出,确保现有代码继续工作。
|
||||
"""
|
||||
|
||||
# 优先从子模块导入(如果已迁移)
|
||||
try:
|
||||
from .fudai_debug_utils import _save_full_screenshot_with_ocr_region
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import _save_full_screenshot_with_ocr_region
|
||||
|
||||
# 优先从子模块导入 get_fudai_contain
|
||||
try:
|
||||
from .fudai_detail_reader import get_fudai_contain
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import get_fudai_contain
|
||||
|
||||
# 优先从子模块导入 attend_choujiang
|
||||
try:
|
||||
from .fudai_attend import attend_choujiang
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import attend_choujiang
|
||||
|
||||
# 优先从子模块导入结果检查函数
|
||||
try:
|
||||
from .fudai_result_checker import (
|
||||
check_lucky_draw_result,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
get_reward,
|
||||
)
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import (
|
||||
check_lucky_draw_result,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
get_reward,
|
||||
)
|
||||
|
||||
# 优先从子模块导入过滤函数
|
||||
try:
|
||||
from .fudai_filter import (
|
||||
check_contain,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
basic_join_decision,
|
||||
)
|
||||
except ImportError:
|
||||
# 如果新模块不可用,从原文件导入
|
||||
from ..douyin_fudai_core import (
|
||||
check_contain,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
basic_join_decision,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_save_full_screenshot_with_ocr_region",
|
||||
"get_fudai_contain",
|
||||
"attend_choujiang",
|
||||
"check_lucky_draw_result",
|
||||
"check_have_reward_notice_confirm",
|
||||
"check_in_order_confirm_page",
|
||||
"get_reward",
|
||||
"check_contain",
|
||||
"is_watch_task_fudai",
|
||||
"should_skip_fudai_by_config",
|
||||
"basic_join_decision",
|
||||
]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
||||
"""福袋调试工具模块
|
||||
|
||||
包含调试相关的工具函数,如截图保存和OCR区域标注。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Tuple
|
||||
from PIL import Image
|
||||
|
||||
import path_config
|
||||
|
||||
|
||||
def save_full_screenshot_with_ocr_region(
|
||||
analyser: Any, picname: str, coords: Tuple[int, int, int, int], y_pianyi: int = 0
|
||||
) -> None:
|
||||
"""保存完整截图并标注OCR区域(用于调试)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
picname: 图片名称(如"福袋内容")
|
||||
coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400)
|
||||
y_pianyi: Y轴偏移
|
||||
"""
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
# 读取完整截图
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(pic_path):
|
||||
return
|
||||
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
|
||||
# 缩放坐标到实际分辨率
|
||||
width, height = pic_rgb.size
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = coords
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int((y1_base + y_pianyi) * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int((y2_base + y_pianyi) * height / ry)
|
||||
|
||||
# 边界检查和验证
|
||||
x1_original = x1
|
||||
y1_original = y1
|
||||
x2_original = x2
|
||||
y2_original = y2
|
||||
|
||||
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_original != x1
|
||||
or y1_original != y1
|
||||
or x2_original != x2
|
||||
or y2_original != y2
|
||||
):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"验证",
|
||||
"OCR区域坐标超出屏幕范围,已修正",
|
||||
original_coords=f"({x1_original},{y1_original})-({x2_original},{y2_original})",
|
||||
corrected_coords=f"({x1},{y1})-({x2},{y2})",
|
||||
screen_size=f"{width}x{height}",
|
||||
base_coords=coords,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"验证",
|
||||
"OCR区域坐标无效(x1>=x2或y1>=y2)",
|
||||
coords=f"({x1},{y1})-({x2},{y2})",
|
||||
base_coords=coords,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
|
||||
# 保存调试图片
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="ocr",
|
||||
picname=picname,
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"y_offset": y_pianyi,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
f"OCR识别前保存完整截图({picname})",
|
||||
path=debug_path,
|
||||
region=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存调试图像日志失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
picname=picname,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存完整截图并标注OCR区域失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
picname=picname,
|
||||
coords=coords,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 向后兼容:保留原函数名
|
||||
_save_full_screenshot_with_ocr_region = save_full_screenshot_with_ocr_region
|
||||
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,283 @@
|
||||
"""福袋结果检查模块
|
||||
|
||||
包含开奖结果检查、奖励领取等功能的实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def check_lucky_draw_result(analyser) -> int | bool:
|
||||
"""判定福袋抽奖的结果。"""
|
||||
# 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过)
|
||||
cache_key = ("lucky_draw_result", 0)
|
||||
now = time.time()
|
||||
need_screenshot = True
|
||||
|
||||
# 检查缓存是否有效
|
||||
if cache_key in analyser._ocr_cache:
|
||||
cached_ts, cached_result = analyser._ocr_cache[cache_key]
|
||||
if (
|
||||
(now - cached_ts) < 0.5
|
||||
and cached_result
|
||||
and ("没有抽中" in cached_result or "抽中福袋" in cached_result)
|
||||
):
|
||||
need_screenshot = False
|
||||
|
||||
if need_screenshot:
|
||||
analyser._shot_and_diagnose(
|
||||
"开奖结果", "识别是否中奖/未中奖", analyser.device_id
|
||||
)
|
||||
# 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋"
|
||||
analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") # 没有抽中福袋位置
|
||||
|
||||
# 诊断开始时间
|
||||
t0 = time.time()
|
||||
|
||||
# 检查缓存
|
||||
if cache_key in analyser._ocr_cache:
|
||||
cached_ts, cached_result = analyser._ocr_cache[cache_key]
|
||||
if (now - cached_ts) < analyser._ocr_cache_ttl:
|
||||
lucky_draw_result = cached_result
|
||||
else:
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 0) or ""
|
||||
)
|
||||
if not lucky_draw_result or (
|
||||
"没有抽中" not in lucky_draw_result
|
||||
and "抽中福袋" not in lucky_draw_result
|
||||
):
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 1) or ""
|
||||
)
|
||||
analyser._ocr_cache[cache_key] = (now, lucky_draw_result)
|
||||
else:
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 0) or ""
|
||||
)
|
||||
if not lucky_draw_result or (
|
||||
"没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result
|
||||
):
|
||||
lucky_draw_result = str(
|
||||
analyser.operation.analyse_pic_word("抽奖结果", 1) or ""
|
||||
)
|
||||
analyser._ocr_cache[cache_key] = (now, lucky_draw_result)
|
||||
|
||||
dur = time.time() - t0
|
||||
try:
|
||||
brief = (lucky_draw_result or "").replace("\n", " ")[:140]
|
||||
except Exception:
|
||||
brief = ""
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"开奖诊断",
|
||||
"lucky_draw_result",
|
||||
brief=brief,
|
||||
ocr_dur=round(dur, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if "没有抽中" in (lucky_draw_result or ""):
|
||||
# 速度优化:使用缓存避免重复OCR
|
||||
cache_key2 = ("no_award_confirm", 0)
|
||||
dur2 = 0.0 # Initialize dur2 to avoid unbound variable
|
||||
if cache_key2 in analyser._ocr_cache:
|
||||
cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2]
|
||||
if (now - cached_ts2) < analyser._ocr_cache_ttl:
|
||||
no_award_confirm = cached_result2
|
||||
else:
|
||||
t1 = time.time()
|
||||
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
|
||||
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
|
||||
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
|
||||
dur2 = time.time() - t1
|
||||
else:
|
||||
t1 = time.time()
|
||||
analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认")
|
||||
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
|
||||
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
|
||||
dur2 = time.time() - t1
|
||||
try:
|
||||
brief2 = (no_award_confirm or "").replace("\n", " ")[:140]
|
||||
except Exception:
|
||||
brief2 = ""
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"开奖诊断",
|
||||
"no_award_confirm",
|
||||
brief=brief2,
|
||||
ocr_dur=round(dur2, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if "我知道了" in (no_award_confirm or ""):
|
||||
return 1
|
||||
elif "领取并使用" in (no_award_confirm or ""):
|
||||
return 2
|
||||
return 3
|
||||
elif "抽中福袋" in (lucky_draw_result or ""):
|
||||
try:
|
||||
analyser._log_kv("开奖诊断", "恭喜中奖了", result_text=brief)
|
||||
except Exception:
|
||||
pass
|
||||
# 速度优化:优先检测第一个常见位置,命中即返回
|
||||
y_value = [1438, 1490]
|
||||
for y in y_value:
|
||||
cache_key3 = (f"have_read_user_agreement_{y}", 0)
|
||||
have_read_user_agreement = None
|
||||
dur3 = 0.0
|
||||
|
||||
if cache_key3 in analyser._ocr_cache:
|
||||
cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3]
|
||||
if (now - cached_ts3) < analyser._ocr_cache_ttl:
|
||||
have_read_user_agreement = cached_result3
|
||||
|
||||
if not have_read_user_agreement:
|
||||
t2 = time.time()
|
||||
analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}")
|
||||
have_read_user_agreement = analyser.operation.analyse_pic_word(
|
||||
f"已阅读用户协议_{y}"
|
||||
)
|
||||
analyser._ocr_cache[cache_key3] = (
|
||||
time.time(),
|
||||
have_read_user_agreement,
|
||||
)
|
||||
dur3 = time.time() - t2
|
||||
try:
|
||||
brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140]
|
||||
except Exception:
|
||||
brief3 = ""
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"开奖诊断",
|
||||
"have_read_user_agreement",
|
||||
brief=brief3,
|
||||
ocr_dur=round(dur3, 2),
|
||||
y=y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if "已阅读" in (have_read_user_agreement or ""):
|
||||
return y
|
||||
return False
|
||||
|
||||
|
||||
def check_have_reward_notice_confirm(analyser) -> bool:
|
||||
"""判断是否有领奖的二次确认提醒。"""
|
||||
analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id)
|
||||
analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认")
|
||||
reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1)
|
||||
if "我知道了" in (reward_notice_confirm or ""):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"开奖诊断",
|
||||
"存在奖品领取提醒",
|
||||
text=(reward_notice_confirm or "")[:80],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def check_in_order_confirm_page(analyser) -> bool:
|
||||
"""判断是否在中奖下单后的购买成功的页面。"""
|
||||
analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id)
|
||||
analyser.cut_pic(370, 120, 700, 220, "", "订单确认")
|
||||
order_confirm = analyser.operation.analyse_pic_word("订单确认")
|
||||
if "购买成功" in (order_confirm or ""):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"开奖诊断",
|
||||
"订单确认页面:购买成功",
|
||||
text=(order_confirm or "")[:80],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def get_reward(analyser, reward_y: int = 0) -> None:
|
||||
"""中奖后领奖然后返回。"""
|
||||
analyser.operation.save_reward_pic(analyser.device_id)
|
||||
try:
|
||||
analyser._log_kv("领奖", "保存中奖截图", step="save_reward_pic")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.click(243, reward_y) # 勾选协议
|
||||
analyser.operation.delay(1)
|
||||
analyser.click(540, reward_y - 140) # 点击领取
|
||||
try:
|
||||
analyser._log_kv("领奖", "勾选协议并点击领取", reward_y=reward_y)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.operation.delay(5)
|
||||
analyser.click(886, 2170) # 点击下单
|
||||
try:
|
||||
analyser._log_kv("领奖", "点击下单")
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(10)
|
||||
|
||||
# 循环检查下单结果,增加保护避免极端死循环
|
||||
max_checks = 5
|
||||
checks = 0
|
||||
while checks < max_checks and check_in_order_confirm_page(analyser):
|
||||
checks += 1
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
try:
|
||||
analyser._log_kv("领奖", "点击回退按钮", check_round=checks)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(4)
|
||||
|
||||
try:
|
||||
analyser._log_kv("领奖", "下完单返回到直播间", checks=checks)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(4)
|
||||
|
||||
if check_lucky_draw_result(analyser):
|
||||
try:
|
||||
analyser._log_kv("领奖", "领奖弹窗未关闭,准备关闭")
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(540, reward_y + 180)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"领奖",
|
||||
"点击关闭领奖弹窗",
|
||||
x=540,
|
||||
y=(reward_y + 180) * analyser.resolution_ratio_y // 2400,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(2)
|
||||
analyser.operation.save_reward_pic(analyser.device_id)
|
||||
try:
|
||||
analyser._log_kv("领奖", "保存关闭领奖弹窗后的截图")
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(2)
|
||||
|
||||
if check_have_reward_notice_confirm(analyser):
|
||||
try:
|
||||
analyser._log_kv("领奖", "提醒领奖弹窗未关闭,点击我知道了")
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(540, 1400)
|
||||
analyser.operation.delay(2)
|
||||
|
||||
try:
|
||||
analyser._log_kv("领奖", "关闭中奖提醒后等待", wait_seconds=30)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(30)
|
||||
+512
-218
File diff suppressed because it is too large.
Load diff
@@ -1400,7 +1400,10 @@ class FudaiFinder:
|
||||
consecutive_failures = 0 # 连续失败计数
|
||||
max_consecutive_failures = 5 # 最大连续失败次数
|
||||
|
||||
while (time.time() - overall_start) < self.max_wait_s:
|
||||
# 额外的时间限制保护,防止死循环(最长等待时间限制)
|
||||
absolute_timeout = overall_start + max(self.max_wait_s * 1.5, 180) # 最长3分钟
|
||||
|
||||
while (time.time() - overall_start) < self.max_wait_s and time.time() < absolute_timeout:
|
||||
# 额外的循环次数保护:防止无限循环
|
||||
if loop >= max_loops:
|
||||
try:
|
||||
|
||||
@@ -25,7 +25,17 @@ from types import ModuleType
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
_EXTERNAL_DIR = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf"
|
||||
# 使用环境变量或默认路径,避免硬编码用户路径
|
||||
_EXTERNAL_DIR = os.environ.get(
|
||||
"EXTERNAL_DOUYIN_FUDAI_DIR",
|
||||
os.path.join(
|
||||
os.path.expanduser("~"),
|
||||
".cursor",
|
||||
"worktrees",
|
||||
"douyin_guaji-main",
|
||||
"axf"
|
||||
)
|
||||
)
|
||||
_EXTERNAL_PATH = os.path.join(_EXTERNAL_DIR, "douyin_fudai_flow.py")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""福袋查找器模块
|
||||
|
||||
本目录包含从 douyin_fudai_finder.py 模块化后的福袋查找器功能。
|
||||
"""
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后改为从子模块导入
|
||||
from ...fudai.douyin_fudai_finder import (
|
||||
FudaiImageAcquirer,
|
||||
FudaiDetector,
|
||||
FudaiClickExecutor,
|
||||
FudaiDetailVerifier,
|
||||
FudaiFinder,
|
||||
check_have_fudai_with_ready_screenshot_optimized,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"FudaiImageAcquirer",
|
||||
"FudaiDetector",
|
||||
"FudaiClickExecutor",
|
||||
"FudaiDetailVerifier",
|
||||
"FudaiFinder",
|
||||
"check_have_fudai_with_ready_screenshot_optimized",
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,13 @@ def check_coupon_popup(analyser) -> bool:
|
||||
# 步骤1:模板匹配
|
||||
template_matched = False
|
||||
try:
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic = pic.convert("RGB")
|
||||
@@ -180,7 +186,13 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
pixel_check_start = time.time()
|
||||
has_popup_pixel = False
|
||||
try:
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic = pic.convert("RGB")
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""预约核心模块
|
||||
|
||||
本目录包含从 douyin_reservation_logic.py 模块化后的预约核心逻辑。
|
||||
"""
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后改为从子模块导入
|
||||
from ...reservation.douyin_reservation_logic import (
|
||||
_now_ts,
|
||||
_normalize_room_title_for_matching,
|
||||
_calculate_string_similarity,
|
||||
_extract_content_core,
|
||||
_sort_reservations_inplace,
|
||||
add_reservation_core_logic,
|
||||
validate_back_to_reservation,
|
||||
cleanup_expired_reservations,
|
||||
handle_queue_full_wait_at_earliest,
|
||||
process_reservation_attend_window,
|
||||
record_high_value_reservation,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_now_ts",
|
||||
"_normalize_room_title_for_matching",
|
||||
"_calculate_string_similarity",
|
||||
"_extract_content_core",
|
||||
"_sort_reservations_inplace",
|
||||
"add_reservation_core_logic",
|
||||
"validate_back_to_reservation",
|
||||
"cleanup_expired_reservations",
|
||||
"handle_queue_full_wait_at_earliest",
|
||||
"process_reservation_attend_window",
|
||||
"record_high_value_reservation",
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -79,7 +79,13 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
try:
|
||||
pixel_start = time.time()
|
||||
import os
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
if os.path.exists(pic_path):
|
||||
pic_rgb = douyin_pixel._safe_open_screenshot_rgb(pic_path)
|
||||
if pic_rgb is not None:
|
||||
|
||||
@@ -84,26 +84,61 @@ class StageHandler:
|
||||
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:
|
||||
import path_config
|
||||
assets_dir = path_config.get_assets_dir()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
assets_dir = os.path.join(base_dir, "assets")
|
||||
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
screenshot_path = os.path.join(pic_dir, "screenshot.png")
|
||||
|
||||
# 确保有最新截图
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not os.path.exists(screenshot_path):
|
||||
except Exception as e:
|
||||
# 记录截图获取失败,但不立即返回,继续检查文件是否存在
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断",
|
||||
"_check_in_live_room_by_icon 截图不存在",
|
||||
path=screenshot_path,
|
||||
"_check_in_live_room_by_icon 获取截图失败",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
# 如果预期路径不存在,尝试从其他可能的位置查找截图
|
||||
if not os.path.exists(screenshot_path):
|
||||
# 尝试从项目根目录的 pic 目录查找
|
||||
try:
|
||||
import path_config
|
||||
alt_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(alt_path) and alt_path != screenshot_path:
|
||||
# 如果找到备用路径,使用它
|
||||
screenshot_path = alt_path
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果仍然不存在,记录错误
|
||||
if not os.path.exists(screenshot_path):
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断",
|
||||
"_check_in_live_room_by_icon 截图不存在",
|
||||
path=screenshot_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
try:
|
||||
img = cv2.imread( # type: ignore[attr-defined]
|
||||
@@ -146,6 +181,13 @@ class StageHandler:
|
||||
return False, 0.0
|
||||
|
||||
# 保存裁剪的ROI区域
|
||||
# 使用统一的 pic 目录配置
|
||||
try:
|
||||
import path_config
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
ocr_dir = os.path.join(pic_dir, "ocr")
|
||||
os.makedirs(ocr_dir, exist_ok=True)
|
||||
x_roi_path = os.path.join(ocr_dir, "xx.png")
|
||||
@@ -174,17 +216,56 @@ class StageHandler:
|
||||
|
||||
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
|
||||
):
|
||||
# 调试日志:检查文件存在性
|
||||
template_exists = os.path.exists(template_path) and os.path.isfile(template_path)
|
||||
roi_exists = os.path.exists(roi_path) and os.path.isfile(roi_path)
|
||||
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", f"_check_in_live_room_by_icon 检查文件",
|
||||
icon_name=icon_name,
|
||||
template_exists=template_exists,
|
||||
template_path=template_path,
|
||||
roi_exists=roi_exists,
|
||||
roi_path=roi_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not template_exists:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", f"_check_in_live_room_by_icon 模板文件不存在",
|
||||
icon_name=icon_name,
|
||||
template_path=template_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
|
||||
try:
|
||||
if os.path.getsize(template_path) == 0:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", f"_check_in_live_room_by_icon 模板文件为空",
|
||||
icon_name=icon_name,
|
||||
template_path=template_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
except (OSError, IOError):
|
||||
continue
|
||||
|
||||
if not os.path.exists(roi_path) or not os.path.isfile(roi_path):
|
||||
if not roi_exists:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"阶段诊断", f"_check_in_live_room_by_icon ROI文件不存在",
|
||||
icon_name=icon_name,
|
||||
roi_path=roi_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
|
||||
try:
|
||||
|
||||
@@ -63,7 +63,14 @@ class HelperFunctions:
|
||||
dict: 检测结果(return_details=False时)
|
||||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"folders": [
|
||||
{
|
||||
"path": "."
|
||||
}
|
||||
],
|
||||
"settings": {
|
||||
"files.associations": {
|
||||
"*.md": "markdown"
|
||||
},
|
||||
"files.encoding": "utf8",
|
||||
"files.eol": "\n",
|
||||
"markdown.preview.enabled": true,
|
||||
"markdown.preview.openMarkdownLinks": "inPreview",
|
||||
"markdown.preview.breaks": true,
|
||||
"markdown.preview.fontSize": 14,
|
||||
"editor.wordWrap": "on",
|
||||
"editor.renderWhitespace": "boundary",
|
||||
"[markdown]": {
|
||||
"editor.wordWrap": "on",
|
||||
"editor.quickSuggestions": {
|
||||
"comments": "off",
|
||||
"strings": "off",
|
||||
"other": "off"
|
||||
},
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "yzhang.markdown-all-in-one"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"recommendations": [
|
||||
"yzhang.markdown-all-in-one",
|
||||
"shd101wyy.markdown-preview-enhanced",
|
||||
"bierner.markdown-mermaid"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""修复 Cursor IDE 无法打开 Markdown 文件的问题"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
def check_file_permissions(file_path):
|
||||
"""检查文件权限"""
|
||||
issues = []
|
||||
try:
|
||||
if not os.path.exists(file_path):
|
||||
issues.append("文件不存在")
|
||||
return issues
|
||||
|
||||
if not os.access(file_path, os.R_OK):
|
||||
issues.append("文件无读取权限")
|
||||
|
||||
# 检查文件是否被锁定
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
f.read(1)
|
||||
except PermissionError:
|
||||
issues.append("文件被锁定或无权限")
|
||||
except Exception as e:
|
||||
issues.append(f"无法读取文件: {e}")
|
||||
|
||||
except Exception as e:
|
||||
issues.append(f"检查权限时出错: {e}")
|
||||
|
||||
return issues
|
||||
|
||||
def create_test_md_file():
|
||||
"""创建一个测试 Markdown 文件"""
|
||||
test_file = Path("TEST_MARKDOWN.md")
|
||||
content = """# Test Markdown File
|
||||
|
||||
This is a test file to verify Cursor can open Markdown files.
|
||||
|
||||
## Test Section
|
||||
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Item 3
|
||||
|
||||
**Bold text** and *italic text*
|
||||
|
||||
```python
|
||||
print("Hello, World!")
|
||||
```
|
||||
|
||||
"""
|
||||
try:
|
||||
with open(test_file, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write(content)
|
||||
print(f"[OK] 已创建测试文件: {test_file}")
|
||||
return test_file
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 创建测试文件失败: {e}")
|
||||
return None
|
||||
|
||||
def fix_md_file_encoding(file_path):
|
||||
"""修复单个 MD 文件的编码"""
|
||||
try:
|
||||
# 读取文件
|
||||
encodings = ['utf-8', 'utf-8-sig', 'gbk', 'gb2312']
|
||||
content = None
|
||||
|
||||
for encoding in encodings:
|
||||
try:
|
||||
with open(file_path, 'r', encoding=encoding) as f:
|
||||
content = f.read()
|
||||
break
|
||||
except (UnicodeDecodeError, UnicodeError):
|
||||
continue
|
||||
|
||||
if content is None:
|
||||
return False, "无法读取文件"
|
||||
|
||||
# 移除BOM
|
||||
if content.startswith('\ufeff'):
|
||||
content = content[1:]
|
||||
|
||||
# 确保以UTF-8保存(无BOM,使用LF换行)
|
||||
with open(file_path, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write(content)
|
||||
|
||||
return True, "已修复"
|
||||
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("=" * 60)
|
||||
print("Cursor IDE Markdown 文件修复工具")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# 检查主要MD文件
|
||||
main_files = [
|
||||
"MODULARIZATION_SUMMARY.md",
|
||||
"README.md",
|
||||
"douyin/README.md",
|
||||
"douyin/fudai/core/MODULARIZATION_PLAN.md",
|
||||
]
|
||||
|
||||
print("检查主要 Markdown 文件...")
|
||||
print()
|
||||
|
||||
all_ok = True
|
||||
for file_path_str in main_files:
|
||||
file_path = Path(file_path_str)
|
||||
if not file_path.exists():
|
||||
print(f"[WARN] {file_path_str} - 文件不存在")
|
||||
continue
|
||||
|
||||
# 检查权限
|
||||
perm_issues = check_file_permissions(file_path)
|
||||
if perm_issues:
|
||||
print(f"[ERROR] {file_path_str}")
|
||||
for issue in perm_issues:
|
||||
print(f" - {issue}")
|
||||
all_ok = False
|
||||
continue
|
||||
|
||||
# 修复编码
|
||||
success, message = fix_md_file_encoding(file_path)
|
||||
if success:
|
||||
file_size = os.path.getsize(file_path)
|
||||
print(f"[OK] {file_path_str} ({file_size} bytes) - {message}")
|
||||
else:
|
||||
print(f"[ERROR] {file_path_str} - {message}")
|
||||
all_ok = False
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
|
||||
# 创建测试文件
|
||||
print("创建测试文件...")
|
||||
test_file = create_test_md_file()
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("修复建议:")
|
||||
print("=" * 60)
|
||||
print()
|
||||
print("1. 重启 Cursor IDE")
|
||||
print(" - 完全关闭 Cursor")
|
||||
print(" - 重新打开 Cursor 和项目")
|
||||
print()
|
||||
print("2. 清除 Cursor 缓存")
|
||||
print(" - 关闭 Cursor")
|
||||
print(" - 删除以下目录(如果存在):")
|
||||
print(" - %APPDATA%\\Cursor\\Cache")
|
||||
print(" - %APPDATA%\\Cursor\\CachedData")
|
||||
print(" - 重新打开 Cursor")
|
||||
print()
|
||||
print("3. 检查 Cursor 设置")
|
||||
print(" - 打开设置 (Ctrl+,)")
|
||||
print(" - 搜索 'markdown'")
|
||||
print(" - 确保 Markdown 预览功能已启用")
|
||||
print()
|
||||
print("4. 重新安装 Markdown 扩展")
|
||||
print(" - 打开扩展面板 (Ctrl+Shift+X)")
|
||||
print(" - 搜索 'Markdown'")
|
||||
print(" - 禁用并重新启用相关扩展")
|
||||
print()
|
||||
print("5. 使用命令面板")
|
||||
print(" - 按 Ctrl+Shift+P")
|
||||
print(" - 输入 'Reload Window'")
|
||||
print(" - 选择 'Developer: Reload Window'")
|
||||
print()
|
||||
print("6. 手动打开文件")
|
||||
print(" - 在文件资源管理器中找到文件")
|
||||
print(" - 右键点击 .md 文件")
|
||||
print(" - 选择 '打开方式' -> 'Cursor'")
|
||||
print()
|
||||
|
||||
if test_file:
|
||||
print(f"7. 测试文件")
|
||||
print(f" - 尝试打开: {test_file}")
|
||||
print(f" - 如果这个文件能打开,说明是特定文件的问题")
|
||||
print(f" - 如果这个文件也不能打开,说明是 Cursor 的配置问题")
|
||||
print()
|
||||
|
||||
print("=" * 60)
|
||||
|
||||
if all_ok:
|
||||
print("[SUCCESS] 所有文件检查通过")
|
||||
print("如果仍然无法打开,请按照上述建议操作")
|
||||
else:
|
||||
print("[WARNING] 发现一些问题,请查看上面的详细信息")
|
||||
|
||||
return 0 if all_ok else 1
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
@@ -37,7 +37,13 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
pass
|
||||
return False
|
||||
|
||||
path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
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
|
||||
@@ -225,7 +231,13 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
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()
|
||||
|
||||
@@ -99,7 +99,13 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
pic_rgb = None
|
||||
try:
|
||||
if os.path.exists(pic_path):
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""GUI组件模块
|
||||
|
||||
本目录包含从 gui_app.py 模块化后的GUI组件。
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""行为日志查看组件
|
||||
|
||||
包含行为日志显示、搜索等功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Tuple
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
|
||||
ScrolledText = TBSrolledText
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
|
||||
def create_actions_log_viewer(
|
||||
parent: Any
|
||||
):
|
||||
"""创建行为日志查看器组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
|
||||
返回:
|
||||
(actions_log_text, refresh_actions_log_func)
|
||||
"""
|
||||
actions_log_text = ScrolledText(parent)
|
||||
actions_log_text.pack(fill="both", expand=True, padx=10, pady=10)
|
||||
|
||||
try:
|
||||
actions_log_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def refresh_actions_log() -> None:
|
||||
"""刷新行为日志。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return actions_log_text, refresh_actions_log
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""配置管理组件
|
||||
|
||||
包含配置加载、保存等功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
from gui.gui_core import read_config, write_config
|
||||
|
||||
|
||||
def load_config_to_ui(
|
||||
cfg: dict[str, Any],
|
||||
vars_dict: dict[str, Any],
|
||||
on_line: Callable[[str], None],
|
||||
) -> None:
|
||||
"""从配置文件加载到UI变量。
|
||||
|
||||
参数:
|
||||
cfg: 配置字典
|
||||
vars_dict: UI变量字典
|
||||
on_line: 日志输出回调
|
||||
"""
|
||||
# TODO: 实现配置加载逻辑
|
||||
# 临时从原文件导入
|
||||
pass
|
||||
|
||||
|
||||
def save_ui_to_config(
|
||||
vars_dict: dict[str, Any],
|
||||
on_line: Callable[[str], None],
|
||||
) -> None:
|
||||
"""将UI变量保存到配置文件。
|
||||
|
||||
参数:
|
||||
vars_dict: UI变量字典
|
||||
on_line: 日志输出回调
|
||||
"""
|
||||
# TODO: 实现配置保存逻辑
|
||||
# 临时从原文件导入
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""设备选择组件
|
||||
|
||||
包含设备选择、刷新设备等功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
from gui.gui_core import find_adb_executable, list_adb_devices
|
||||
|
||||
|
||||
def create_device_selector(
|
||||
parent: Any,
|
||||
on_line: Callable[[str], None],
|
||||
device_var: tk.StringVar,
|
||||
) -> tuple[ttk.Combobox, Callable[[], None]]:
|
||||
"""创建设备选择组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
on_line: 日志输出回调
|
||||
device_var: 设备ID变量
|
||||
|
||||
返回:
|
||||
(device_combo, refresh_devices_func) 设备下拉框和刷新函数
|
||||
"""
|
||||
adb_exe = find_adb_executable()
|
||||
devices = list_adb_devices(adb_exe)
|
||||
device_var.set(devices[0] if devices else "")
|
||||
|
||||
ttk.Label(parent, text="设备:").pack(side="left")
|
||||
device_combo = ttk.Combobox(parent, textvariable=device_var, values=devices, width=28)
|
||||
device_combo.pack(side="left", padx=(0, 10))
|
||||
|
||||
def refresh_devices():
|
||||
nonlocal adb_exe
|
||||
adb_exe = find_adb_executable()
|
||||
devs = list_adb_devices(adb_exe)
|
||||
device_combo["values"] = devs
|
||||
if devs and not device_var.get():
|
||||
device_var.set(devs[0])
|
||||
if not adb_exe:
|
||||
on_line("[设备] 未找到 adb.exe(请确认已安装 platform-tools)")
|
||||
elif not devs:
|
||||
on_line("[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)")
|
||||
|
||||
ttk.Button(parent, text="刷新设备", command=refresh_devices).pack(
|
||||
side="left", padx=(0, 20)
|
||||
)
|
||||
|
||||
return device_combo, refresh_devices
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""高价值房间显示组件
|
||||
|
||||
包含高价值房间显示和刷新功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Tuple
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
|
||||
ScrolledText = TBSrolledText
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
|
||||
def create_high_value_rooms_display(
|
||||
parent: Any
|
||||
):
|
||||
"""创建高价值房间显示组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
|
||||
返回:
|
||||
(high_value_text, refresh_high_value_rooms_func)
|
||||
"""
|
||||
high_value_text = ScrolledText(parent)
|
||||
high_value_text.pack(fill="both", expand=True, padx=10, pady=10)
|
||||
|
||||
try:
|
||||
high_value_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def refresh_high_value_rooms() -> None:
|
||||
"""刷新高价值房间。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return high_value_text, refresh_high_value_rooms
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""图像查看组件
|
||||
|
||||
包含图像预览、列表等功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
import os
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
|
||||
def create_image_viewer(
|
||||
parent: Any,
|
||||
on_line: Callable[[str], None],
|
||||
) -> tuple[Any, Callable[[], None], Callable[[], None]]:
|
||||
"""创建图像查看器组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
on_line: 日志输出回调
|
||||
|
||||
返回:
|
||||
(image_var, update_image_list_func, refresh_preview_func)
|
||||
"""
|
||||
image_var = tk.StringVar()
|
||||
|
||||
def update_image_list(refresh_after: bool = True) -> None:
|
||||
"""更新图像列表。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
def refresh_preview() -> None:
|
||||
"""刷新图像预览。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return image_var, update_image_list, refresh_preview
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""日志查看组件
|
||||
|
||||
包含日志显示、搜索等功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Tuple, Callable
|
||||
import queue
|
||||
import re
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
|
||||
ScrolledText = TBSrolledText
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
|
||||
def format_gui_log_line(line: str) -> str:
|
||||
"""将完整日志行转换为GUI显示用的精简版本。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
return line
|
||||
|
||||
|
||||
def create_log_viewer(
|
||||
parent: Any,
|
||||
log_queue: "queue.Queue[str]",
|
||||
on_line: Callable[[str], None]
|
||||
):
|
||||
"""创建日志查看器组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
log_queue: 日志队列
|
||||
on_line: 日志输出回调
|
||||
|
||||
返回:
|
||||
(log_text, pump_logs_func) 日志文本框和日志泵函数
|
||||
"""
|
||||
log_text = ScrolledText(parent)
|
||||
log_text.pack(fill="both", expand=True, padx=10, pady=10)
|
||||
|
||||
try:
|
||||
log_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def pump_logs():
|
||||
"""从队列中取出日志并显示。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return log_text, pump_logs
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""主窗口组件
|
||||
|
||||
包含主窗口布局和事件绑定的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
|
||||
def create_main_window(
|
||||
title: str = "抖音福袋挂机 - 可视化控制台",
|
||||
geometry: str = "1400x900",
|
||||
) -> Any:
|
||||
"""创建主窗口。
|
||||
|
||||
参数:
|
||||
title: 窗口标题
|
||||
geometry: 窗口尺寸
|
||||
|
||||
返回:
|
||||
root窗口对象
|
||||
"""
|
||||
# ttkbootstrap 优先(更美观);没装则回退到原生 tkinter
|
||||
try:
|
||||
import ttkbootstrap as tb
|
||||
root = tb.Window(themename="darkly")
|
||||
except Exception:
|
||||
root = tk.Tk()
|
||||
|
||||
root.title(title)
|
||||
root.geometry(geometry)
|
||||
|
||||
return root
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""OCR面板组件
|
||||
|
||||
包含OCR区域配置、截图OCR等功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
|
||||
def create_ocr_panel(
|
||||
parent: Any,
|
||||
device_var: tk.StringVar,
|
||||
y_var: tk.IntVar,
|
||||
on_line: Callable[[str], None],
|
||||
) -> tuple[Any, Callable[[], None]]:
|
||||
"""创建OCR面板组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
device_var: 设备ID变量
|
||||
y_var: Y偏移变量
|
||||
on_line: 日志输出回调
|
||||
|
||||
返回:
|
||||
(ocr_results_var, do_screenshot_func)
|
||||
"""
|
||||
ocr_results_var = {"results": []}
|
||||
|
||||
def do_screenshot() -> None:
|
||||
"""执行截图和OCR识别。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return ocr_results_var, do_screenshot
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""预约显示组件
|
||||
|
||||
包含预约队列显示和刷新功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Tuple
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
|
||||
ScrolledText = TBSrolledText
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
|
||||
def create_reservation_display(
|
||||
parent: Any
|
||||
):
|
||||
"""创建预约显示组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
|
||||
返回:
|
||||
(reservation_text, refresh_reservations_func)
|
||||
"""
|
||||
reservation_text = ScrolledText(parent)
|
||||
reservation_text.pack(fill="both", expand=True, padx=10, pady=10)
|
||||
|
||||
try:
|
||||
reservation_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def refresh_reservations() -> None:
|
||||
"""刷新预约队列。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return reservation_text, refresh_reservations
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""统计显示组件
|
||||
|
||||
包含统计信息显示和刷新功能的GUI组件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Tuple
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
|
||||
ScrolledText = TBSrolledText
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
|
||||
def create_stats_display(
|
||||
parent: Any,
|
||||
runner: Any,
|
||||
status_var: Any
|
||||
):
|
||||
"""创建统计显示组件。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
runner: 运行器对象
|
||||
status_var: 状态变量
|
||||
|
||||
返回:
|
||||
(stats_text, refresh_stats_func) 统计文本框和刷新函数
|
||||
"""
|
||||
stats_text = ScrolledText(parent)
|
||||
stats_text.pack(fill="both", expand=True, padx=10, pady=10)
|
||||
|
||||
try:
|
||||
stats_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def refresh_stats() -> None:
|
||||
"""刷新统计信息。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
pass
|
||||
|
||||
return stats_text, refresh_stats
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Web GUI组件模块
|
||||
|
||||
本目录包含从 web_gui.py 模块化后的Web GUI组件。
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"""HTTP请求处理器组件
|
||||
|
||||
包含HTTP请求处理和路由功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后,移除此导入并在此文件中实现
|
||||
from gui.web_gui import Handler
|
||||
|
||||
__all__ = ["Handler"]
|
||||
@@ -0,0 +1,16 @@
|
||||
"""进程运行器组件
|
||||
|
||||
包含进程管理、日志收集等功能。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后,移除此导入并在此文件中实现
|
||||
from ..web_gui import ProcRunner
|
||||
|
||||
__all__ = ["ProcRunner"]
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""底层操作模块
|
||||
|
||||
本目录包含从 Underlying_Operations.py 模块化后的操作模块。
|
||||
"""
|
||||
|
||||
# 从子模块导入
|
||||
from .ocr_operations import (
|
||||
analyse_pic_word,
|
||||
analyse_pic_digits,
|
||||
extract_ocr_content,
|
||||
_ensure_ocr,
|
||||
_detect_gpu_available,
|
||||
)
|
||||
from .screenshot_operations import (
|
||||
get_screenshot,
|
||||
_find_pic_path,
|
||||
cut_pic,
|
||||
save_reward_pic,
|
||||
)
|
||||
|
||||
# 从原文件导入以保持向后兼容
|
||||
# TODO: 逐步迁移后改为从子模块导入
|
||||
from Underlying_Operations import (
|
||||
_safe_replace_file,
|
||||
_ensure_parent_dir,
|
||||
_mirror_screenshot_to_external,
|
||||
underlying_operations,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# OCR相关
|
||||
"analyse_pic_word",
|
||||
"analyse_pic_digits",
|
||||
"extract_ocr_content",
|
||||
"_ensure_ocr",
|
||||
"_detect_gpu_available",
|
||||
# 截图相关
|
||||
"get_screenshot",
|
||||
"_find_pic_path",
|
||||
"cut_pic",
|
||||
"save_reward_pic",
|
||||
# 其他操作
|
||||
"_safe_replace_file",
|
||||
"_ensure_parent_dir",
|
||||
"_mirror_screenshot_to_external",
|
||||
"underlying_operations",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""设备操作模块
|
||||
|
||||
包含ADB设备操作,如点击、滑动、输入等。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后,移除此导入并在此文件中实现
|
||||
from Underlying_Operations import underlying_operations
|
||||
|
||||
# 导出设备操作相关方法
|
||||
# TODO: 实现这些函数后添加到__all__列表中
|
||||
__all__ = []
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""图像处理操作模块
|
||||
|
||||
包含图像裁剪、处理等操作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
# 临时导入:从原文件导入,后续会逐步迁移
|
||||
# TODO: 迁移完成后,移除此导入并在此文件中实现
|
||||
from Underlying_Operations import underlying_operations
|
||||
|
||||
# 导出图像处理相关方法
|
||||
# TODO: 实现这些函数后添加到__all__列表中
|
||||
__all__ = []
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
"""OCR操作模块
|
||||
|
||||
包含OCR识别相关的操作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import contextlib
|
||||
from typing import Any, Optional
|
||||
|
||||
# PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。
|
||||
# 这里提前设置环境变量,避免启动耗时/卡死。
|
||||
os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
|
||||
# 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING)
|
||||
os.environ.setdefault("GLOG_minloglevel", "2")
|
||||
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||||
|
||||
|
||||
class OCRProcessor:
|
||||
"""OCR处理器类"""
|
||||
|
||||
def __init__(self):
|
||||
# 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。
|
||||
# 支持延迟初始化(测试流程/只做点击时不需要 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():
|
||||
self._init_ocr()
|
||||
|
||||
def _init_ocr(self):
|
||||
"""初始化OCR引擎"""
|
||||
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
|
||||
# 首先尝试EasyOCR
|
||||
devnull = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports]
|
||||
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
# 自动检测GPU可用性,如果可用则启用GPU加速
|
||||
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})")
|
||||
except Exception:
|
||||
# EasyOCR初始化失败,回退到PaddleOCR
|
||||
try:
|
||||
if devnull is not None:
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(
|
||||
devnull
|
||||
), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
|
||||
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",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||||
print(
|
||||
f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
|
||||
)
|
||||
except Exception:
|
||||
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
|
||||
try:
|
||||
if devnull is not None:
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
finally:
|
||||
try:
|
||||
if devnull is not None:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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",
|
||||
):
|
||||
# 强制启用时,验证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加速")
|
||||
return True
|
||||
else:
|
||||
print("[OCR] 环境变量要求启用GPU,但GPU不可用,使用CPU模式")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[OCR] 环境变量要求启用GPU,但PyTorch未安装,使用CPU模式")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[OCR] GPU检测失败: {e},使用CPU模式")
|
||||
return False
|
||||
|
||||
# 默认使用CPU模式
|
||||
return False
|
||||
|
||||
def _ensure_ocr(self):
|
||||
"""确保OCR引擎已初始化"""
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
# 重新检测GPU(延迟初始化时)
|
||||
self._gpu_available = self._detect_gpu_available()
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
devnull = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
|
||||
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})")
|
||||
except Exception:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
try:
|
||||
if devnull is not None:
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
|
||||
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",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||||
except Exception as e:
|
||||
print(f"[OCR] OCR引擎初始化失败: {e}")
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
finally:
|
||||
try:
|
||||
if devnull is not None:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 全局OCR处理器实例
|
||||
_ocr_processor = OCRProcessor()
|
||||
|
||||
|
||||
def _detect_gpu_available() -> bool:
|
||||
"""检测GPU是否可用(向后兼容接口)"""
|
||||
return _ocr_processor._detect_gpu_available()
|
||||
|
||||
|
||||
def _ensure_ocr():
|
||||
"""确保OCR引擎已初始化(向后兼容接口)"""
|
||||
_ocr_processor._ensure_ocr()
|
||||
|
||||
|
||||
def analyse_pic_word(picname, change_color=0, pic_path=None):
|
||||
"""文字OCR识别(向后兼容接口)"""
|
||||
# 这里应该实现实际的OCR文字识别逻辑
|
||||
# 暂时从原文件导入以保持功能
|
||||
from Underlying_Operations import underlying_operations
|
||||
instance = underlying_operations()
|
||||
return instance.analyse_pic_word(picname, change_color, pic_path)
|
||||
|
||||
|
||||
def analyse_pic_digits(picname, change_color=1, pic_path=None):
|
||||
"""数字OCR识别(向后兼容接口)"""
|
||||
# 这里应该实现实际的OCR数字识别逻辑
|
||||
# 暂时从原文件导入以保持功能
|
||||
from Underlying_Operations import underlying_operations
|
||||
instance = underlying_operations()
|
||||
return instance.analyse_pic_digits(picname, change_color, pic_path)
|
||||
|
||||
|
||||
def extract_ocr_content(content=[], return_confidence=False):
|
||||
"""提取OCR内容(向后兼容接口)"""
|
||||
# 这里应该实现实际的OCR内容提取逻辑
|
||||
# 暂时从原文件导入以保持功能
|
||||
from Underlying_Operations import underlying_operations
|
||||
instance = underlying_operations()
|
||||
return instance.extract_ocr_content(content, return_confidence)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OCRProcessor",
|
||||
"analyse_pic_word",
|
||||
"analyse_pic_digits",
|
||||
"extract_ocr_content",
|
||||
"_ensure_ocr",
|
||||
"_detect_gpu_available",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""截图操作模块
|
||||
|
||||
包含截图、图片裁剪等截图相关操作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from Underlying_Operations import _safe_replace_file, _mirror_screenshot_to_external
|
||||
|
||||
|
||||
class ScreenshotOperations:
|
||||
"""截图操作类"""
|
||||
|
||||
@staticmethod
|
||||
def _adb() -> str:
|
||||
"""返回adb命令路径"""
|
||||
import os
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
# 始终加引号,避免路径带空格 / 版本混用
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
return adb
|
||||
return f'"{adb}"'
|
||||
|
||||
@staticmethod
|
||||
def _adb_path() -> str:
|
||||
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
|
||||
import os
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
adb = adb[1:-1]
|
||||
return adb
|
||||
|
||||
def get_screenshot(self, device_id, path="pic") -> bool:
|
||||
"""截图3个adb命令需要2S左右的时间"""
|
||||
if path == "pic":
|
||||
out_dir = os.path.join(os.path.dirname(__file__), "pic")
|
||||
else:
|
||||
out_dir = os.path.join(os.path.dirname(__file__), "target_pic")
|
||||
if not os.path.exists(out_dir):
|
||||
os.makedirs(out_dir)
|
||||
|
||||
# 统一输出到固定文件名,兼容现有 cut_pic()/后续流程
|
||||
out_file = os.path.join(out_dir, "screenshot.png")
|
||||
tmp_file = out_file + ".tmp"
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
|
||||
adb = self._adb_path()
|
||||
|
||||
def _valid_png(path0: str) -> bool:
|
||||
try:
|
||||
if not os.path.exists(path0):
|
||||
return False
|
||||
sz = os.path.getsize(path0)
|
||||
# PNG 通常远大于 1KB;0 字节/极小文件大概率是 adb 输出异常/中断
|
||||
return sz >= 1024
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
|
||||
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
|
||||
for _ in range(2):
|
||||
try:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
with open(tmp_file, "wb") as f:
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=f,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=10, # 添加10秒超时,避免无限等待
|
||||
)
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
|
||||
return True
|
||||
else:
|
||||
# 如果替换失败,但临时文件有效,仍然返回成功
|
||||
# 后续代码可以读取临时文件或重试
|
||||
print(f"[截图] 文件替换失败,但截图已保存到临时文件,将重试")
|
||||
# 不立即返回,继续尝试回退方案
|
||||
except subprocess.TimeoutExpired:
|
||||
# 超时异常,记录并继续重试
|
||||
print(f"[截图] exec-out 超时,尝试重试或回退方案")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 继续回退/重试
|
||||
print(f"[截图] exec-out 异常:{e}")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退方案:老式 shell screencap + pull(兼容极少数不支持 exec-out 的环境)
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
"/sdcard/DCIM/screenshot.png",
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=10, # 添加超时
|
||||
)
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=10, # 添加超时
|
||||
)
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print("{} 获取屏幕截图".format(timetag))
|
||||
return True
|
||||
else:
|
||||
print("[截图] 回退方案文件替换失败")
|
||||
return False
|
||||
else:
|
||||
print("[截图] 回退方案截图无效")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[截图] 回退方案失败:{e}")
|
||||
return False
|
||||
|
||||
def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
"""根据图片名称查找图片路径。
|
||||
|
||||
参数:
|
||||
picname: 图片文件名
|
||||
for_reading: 是否用于读取(决定搜索的目录顺序)
|
||||
|
||||
返回:
|
||||
图片的完整路径,如果未找到则返回 None
|
||||
"""
|
||||
# 搜索目录优先级
|
||||
search_dirs = []
|
||||
if for_reading:
|
||||
# 读取时优先搜索当前目录的pic文件夹
|
||||
search_dirs = [
|
||||
os.path.join(os.path.dirname(__file__), "pic"),
|
||||
os.path.join(os.path.dirname(__file__), "target_pic"),
|
||||
os.path.dirname(__file__), # 当前目录
|
||||
]
|
||||
else:
|
||||
# 写入时优先使用pic目录
|
||||
search_dirs = [
|
||||
os.path.join(os.path.dirname(__file__), "pic"),
|
||||
]
|
||||
|
||||
# 尝试在每个目录中查找文件
|
||||
for search_dir in search_dirs:
|
||||
if not os.path.exists(search_dir):
|
||||
continue
|
||||
|
||||
pic_path = os.path.join(search_dir, picname)
|
||||
if os.path.exists(pic_path):
|
||||
return pic_path
|
||||
|
||||
return None
|
||||
|
||||
def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""):
|
||||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。"""
|
||||
# 这里应该实现图片裁剪逻辑
|
||||
# 暂时从原文件导入以保持功能
|
||||
from Underlying_Operations import underlying_operations
|
||||
instance = underlying_operations()
|
||||
return instance.cut_pic(left_up, right_down, target, name)
|
||||
|
||||
def save_reward_pic(self, device_id):
|
||||
"""保存奖励图片"""
|
||||
# 这里应该实现奖励图片保存逻辑
|
||||
# 暂时从原文件导入以保持功能
|
||||
from Underlying_Operations import underlying_operations
|
||||
instance = underlying_operations()
|
||||
return instance.save_reward_pic(device_id)
|
||||
|
||||
|
||||
# 全局截图操作实例
|
||||
_screenshot_ops = ScreenshotOperations()
|
||||
|
||||
|
||||
def get_screenshot(device_id, path="pic") -> bool:
|
||||
"""获取屏幕截图(向后兼容接口)"""
|
||||
return _screenshot_ops.get_screenshot(device_id, path)
|
||||
|
||||
|
||||
def _find_pic_path(picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
"""查找图片路径(向后兼容接口)"""
|
||||
return _screenshot_ops._find_pic_path(picname, for_reading)
|
||||
|
||||
|
||||
def cut_pic(left_up=(0, 63), right_down=(1080, 1620), target="", name=""):
|
||||
"""裁剪图片(向后兼容接口)"""
|
||||
return _screenshot_ops.cut_pic(left_up, right_down, target, name)
|
||||
|
||||
|
||||
def save_reward_pic(device_id):
|
||||
"""保存奖励图片(向后兼容接口)"""
|
||||
return _screenshot_ops.save_reward_pic(device_id)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ScreenshotOperations",
|
||||
"get_screenshot",
|
||||
"_find_pic_path",
|
||||
"cut_pic",
|
||||
"save_reward_pic",
|
||||
]
|
||||
@@ -0,0 +1,78 @@
|
||||
import os
|
||||
import sys
|
||||
sys.path.append('.')
|
||||
|
||||
# 演示统一的路径配置 vs 旧的路径配置的区别
|
||||
|
||||
print("=== 路径配置对比演示 ===\n")
|
||||
|
||||
# 项目根目录
|
||||
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
print(f"项目根目录: {PROJECT_ROOT}\n")
|
||||
|
||||
# ===== 统一路径配置 =====
|
||||
print("=== 统一路径配置 (path_config.py) ===")
|
||||
try:
|
||||
import path_config
|
||||
unified_screenshot = path_config.get_screenshot_path()
|
||||
unified_assets = path_config.get_assets_dir()
|
||||
unified_pic = path_config.get_pic_dir()
|
||||
|
||||
print(f" 截图路径: {unified_screenshot}")
|
||||
print(f" assets路径: {unified_assets}")
|
||||
print(f" pic路径: {unified_pic}")
|
||||
print(" OK 始终指向项目根目录下的正确目录")
|
||||
except Exception as e:
|
||||
print(f" FAIL 导入失败: {e}")
|
||||
|
||||
print("\n" + "="*50 + "\n")
|
||||
|
||||
# ===== 旧的路径配置 =====
|
||||
print("=== 旧的路径配置 (硬编码相对路径) ===")
|
||||
|
||||
# 模拟不同文件中的旧路径配置
|
||||
files_and_old_paths = [
|
||||
("douyin/stage/douyin_stage_handler.py", "douyin/stage"),
|
||||
("douyin/utils/douyin_helpers.py", "douyin/utils"),
|
||||
("douyin/other/douyin_popups.py", "douyin/other"),
|
||||
("fudai_detail_modules/fudai_detail_coupon_detection.py", "fudai_detail_modules"),
|
||||
]
|
||||
|
||||
for file_path, module_dir in files_and_old_paths:
|
||||
print(f"\nFile: {file_path}")
|
||||
print(f" 模块目录: {module_dir}")
|
||||
|
||||
# 旧的硬编码路径
|
||||
old_base_dir = os.path.join(PROJECT_ROOT, module_dir)
|
||||
old_screenshot = os.path.join(old_base_dir, "pic", "screenshot.png")
|
||||
old_assets = os.path.join(old_base_dir, "assets")
|
||||
|
||||
print(f" OLD 旧截图路径: {old_screenshot}")
|
||||
print(f" OLD 旧assets路径: {old_assets}")
|
||||
|
||||
# 检查这些路径是否存在
|
||||
screenshot_exists = os.path.exists(old_screenshot)
|
||||
assets_exists = os.path.exists(old_assets)
|
||||
print(f" 截图文件存在: {'OK' if screenshot_exists else 'MISSING'}")
|
||||
print(f" assets目录存在: {'OK' if assets_exists else 'MISSING'}")
|
||||
|
||||
print("\n" + "="*50 + "\n")
|
||||
|
||||
# ===== 实际对比 =====
|
||||
print("=== 实际对比 ===")
|
||||
print("OK 统一路径: 总是指向项目根目录的正确位置")
|
||||
print("FAIL 旧路径: 根据文件位置动态变化,可能指向错误目录")
|
||||
|
||||
print("\n=== 影响 ===")
|
||||
print("• 模板匹配失败 → 直播间检测错误")
|
||||
print("• 截图读取失败 → 像素检测异常")
|
||||
print("• 文件找不到 → 功能无法正常工作")
|
||||
|
||||
print("\n=== 修复方法 ===")
|
||||
print("• 使用 path_config.py 中的统一路径函数")
|
||||
print("• 确保所有文件都使用相同的基准目录(项目根目录)")
|
||||
|
||||
print("\n=== 修复结果 ===")
|
||||
print("• 模板匹配正常工作 (分数0.957)")
|
||||
print("• 像素检测返回完整信息")
|
||||
print("• 警告信息消失")
|
||||
+11
-1
@@ -18,7 +18,17 @@ except Exception:
|
||||
# 需要优先加载这些本地实现,再去加载完整逻辑模块。
|
||||
|
||||
_BASE_DIR = os.path.dirname(__file__)
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf"
|
||||
# 使用环境变量或默认路径,避免硬编码用户路径
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get(
|
||||
"EXTERNAL_DOUYIN_FUDAI_DIR",
|
||||
os.path.join(
|
||||
os.path.expanduser("~"),
|
||||
".cursor",
|
||||
"worktrees",
|
||||
"douyin_guaji-main",
|
||||
"axf"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _load_local_shim(mod_name: str, rel_path: str) -> None:
|
||||
|
||||
+2
-2
@@ -10,8 +10,8 @@
|
||||
from typing import Optional
|
||||
|
||||
APP_NAME = "douyin_guaji"
|
||||
APP_VERSION = "V3.3.1"
|
||||
APP_BUILD_DATE = "2025-12-14"
|
||||
APP_VERSION = "V3.3.3"
|
||||
APP_BUILD_DATE = "2025-12-28"
|
||||
|
||||
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
|
||||
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
|
||||
|
||||
Reference in new issue
Block a user