diff --git a/CODE_QUALITY_REVIEW.md b/CODE_QUALITY_REVIEW.md deleted file mode 100644 index c18dcda..0000000 --- a/CODE_QUALITY_REVIEW.md +++ /dev/null @@ -1,364 +0,0 @@ -# 代码质量审查报告 - -**审查日期**: 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 - diff --git a/IMPORT_FIXES_REPORT.md b/IMPORT_FIXES_REPORT.md deleted file mode 100644 index 3657fe4..0000000 --- a/IMPORT_FIXES_REPORT.md +++ /dev/null @@ -1,127 +0,0 @@ -# 导入问题修复报告 - -**修复日期**: 2025-12-28 -**修复范围**: 所有Python文件的导入语句 - -## 修复的问题 - -### 1. 语法错误修复 - -**文件**: `douyin/detection/douyin_pixel.py` -- **问题**: 第892行有重复的返回语句和多余的代码块 -- **修复**: 删除重复的返回语句 -- **状态**: ✅ 已修复 - -### 2. 导入路径错误修复 - -#### 2.1 `douyin_fudai_detail` 导入修复 - -**文件**: -- `douyin/fudai/douyin_fudai_core.py` (2处) -- `douyin/fudai/core/fudai_filter.py` (1处) - -**问题**: 使用了错误的导入方式 -```python -import douyin_fudai_detail as dfd_module # ❌ 错误 -``` - -**修复**: 改为正确的包导入 -```python -from douyin.fudai import douyin_fudai_detail as dfd_module # ✅ 正确 -``` - -**状态**: ✅ 已修复 - -#### 2.2 `douyin_logging` 和 `douyin_logger` 导入修复 - -**文件**: `douyin/logging/douyin_logging_wrapper.py` (2处) - -**问题**: 使用了错误的导入方式 -```python -import douyin_logging # ❌ 错误 -import douyin_logger # ❌ 错误 -``` - -**修复**: 改为正确的包导入 -```python -from douyin.logging import douyin_logging # ✅ 正确 -from douyin.logging import douyin_logger # ✅ 正确 -``` - -**状态**: ✅ 已修复 - -#### 2.3 `douyin_reservation_verify` 导入修复 - -**文件**: `douyin/reservation/douyin_reservation_logic.py` (1处) - -**问题**: 使用了错误的导入方式 -```python -import douyin_reservation_verify # ❌ 错误 -``` - -**修复**: 改为正确的包导入 -```python -from douyin.reservation import douyin_reservation_verify # ✅ 正确 -``` - -**状态**: ✅ 已修复 - -### 3. 之前已修复的问题 - -#### 3.1 `douyin_detection` 导入修复 - -**文件**: `douyin/detection/douyin_pixel.py` -- **问题**: `from douyin_detection import check_detail_height` -- **修复**: `from .douyin_detection import check_detail_height` -- **状态**: ✅ 已修复 - -## 验证结果 - -所有修复后的导入都已通过测试: - -- ✅ `douyin.detection.douyin_pixel` - 导入成功 -- ✅ `douyin.fudai.douyin_fudai_detail` - 导入成功 -- ✅ `douyin.logging.douyin_logging` - 导入成功 -- ✅ `douyin.logging.douyin_logger` - 导入成功 -- ✅ `douyin.reservation.douyin_reservation_verify` - 导入成功 - -## 导入规范总结 - -### 正确的导入方式 - -1. **同一包内的模块**:使用相对导入 - ```python - from .module_name import function_name - ``` - -2. **跨包导入**:使用绝对导入(完整包路径) - ```python - from douyin.package import module_name - ``` - -3. **根目录模块**:直接导入 - ```python - import path_config - from Underlying_Operations import underlying_operations - ``` - -### 错误的导入方式(已修复) - -1. ❌ `import douyin_fudai_detail` → ✅ `from douyin.fudai import douyin_fudai_detail` -2. ❌ `import douyin_logging` → ✅ `from douyin.logging import douyin_logging` -3. ❌ `import douyin_reservation_verify` → ✅ `from douyin.reservation import douyin_reservation_verify` -4. ❌ `from douyin_detection import` → ✅ `from .douyin_detection import` - -## 注意事项 - -- 所有修复都保持了向后兼容性 -- 修复后的代码已通过导入测试 -- 没有发现循环导入问题 -- 所有模块文件都存在且可访问 - -## 后续建议 - -1. 在代码审查时注意检查导入语句 -2. 使用类型检查工具(如 pyright)可以帮助发现导入问题 -3. 统一导入风格,提高代码可维护性 - diff --git a/PYLANCE_FIXES_REPORT.md b/PYLANCE_FIXES_REPORT.md deleted file mode 100644 index ead931a..0000000 --- a/PYLANCE_FIXES_REPORT.md +++ /dev/null @@ -1,156 +0,0 @@ -# Pylance 问题修复报告 - -**修复日期**: 2025-12-29 - -## 修复的问题 - -### 1. 模块导出问题 - -**文件**: `douyin/detection/__init__.py` -- **问题**: 空文件,没有导出 `douyin_pixel` 和 `douyin_detection` 模块 -- **修复**: 添加了模块导出 -```python -from . import douyin_detection -from . import douyin_pixel - -__all__ = ["douyin_detection", "douyin_pixel"] -``` -- **状态**: ✅ 已修复 - -### 2. 导入路径修复 - -**文件**: `douyin/utils/douyin_helpers.py` -- **问题**: `No name 'douyin_pixel' in module 'douyin.detection'` -- **修复**: 改为直接导入函数 -```python -# 修复前 -from douyin.detection import douyin_pixel -return douyin_pixel.read_pixel_stage_state_from_screenshot(...) - -# 修复后 -from douyin.detection.douyin_pixel import read_pixel_stage_state_from_screenshot -return read_pixel_stage_state_from_screenshot(...) -``` -- **状态**: ✅ 已修复 - -### 3. 未使用的导入和变量 - -**文件**: `douyin/fudai/douyin_fudai_finder.py` -- **问题**: - - `List` 从 typing 导入但未使用 - - `detect_method` 变量未使用 - - `verify_after_click` 参数未使用 -- **修复**: - - 移除未使用的 `List` 导入 - - 将 `detect_method` 改为 `_detect_method`(表示有意未使用) - - 为 `verify_after_click` 添加 `# noqa: ARG002` 注释 -- **状态**: ✅ 已修复 - -### 4. OpenCV (cv2) 类型问题 - -**问题**: Pylance 无法识别 cv2 模块的成员(如 `cv2.imread`, `cv2.matchTemplate` 等) - -**修复**: 创建类型存根文件 -- **文件**: `typings/cv2.pyi` -- **内容**: 定义了常用的 cv2 函数和常量的类型签名 -- **状态**: ✅ 已创建 - -### 5. Pylance 配置优化 - -**文件**: `config/pyrightconfig.json` -- **优化**: - - 清理了重复的配置项 - - 添加了 `stubPath` 指向 `./typings` 目录 - - 设置了合理的类型检查模式 - - 禁用了不必要的警告(如访问受保护成员、捕获宽泛异常等) -- **状态**: ✅ 已优化 - -### 6. 新增修复 (2025-12-29) - -#### 6.1 devnull变量绑定问题 - -**文件**: `Underlying_Operations.py`, `operations/ocr_operations.py` -- **问题**: `devnull` 变量在条件分支中定义,但在异常处理块中使用,导致"可能未绑定"错误 -- **修复**: 将 `devnull = None` 初始化移到更外层的scope,确保变量在所有使用点都已定义 -- **状态**: ✅ 已修复 - -#### 6.2 方法覆盖返回类型不匹配 - -**文件**: `douyin/core/fudai_modules/fudai_stage_detection.py` -- **问题**: `_check_in_live_room_by_icon` 方法在基类中返回 `bool`,在子类中返回 `Tuple[bool, float]` -- **修复**: 修改基类方法返回类型为 `Tuple[bool, float]` 以保持一致性 -- **状态**: ✅ 已修复 - -#### 6.3 静态方法中self未定义 - -**文件**: `douyin/fudai/douyin_fudai_flow.py` -- **问题**: 在 `@staticmethod` 装饰的方法中使用了 `self` 变量 -- **修复**: 将所有 `self` 引用替换为正确的 `analyser` 参数 -- **状态**: ✅ 已修复 - -#### 6.4 缺失的类型导入 - -**文件**: `douyin/logging/performance_tracker.py` -- **问题**: 使用了 `List` 类型但未导入 -- **修复**: 在 typing 导入中添加 `List` -- **状态**: ✅ 已修复 - -#### 6.5 变量未定义问题 - -**文件**: `douyin/other/douyin_robot.py` -- **问题**: `path` 变量在函数中未定义就被使用 -- **修复**: 将 `path_config.get_robot_verify_pic_path()` 的返回值正确赋值给 `path` 变量 -- **状态**: ✅ 已修复 - -#### 6.6 OpenCV类型存根扩展 - -**文件**: `typings/cv2.pyi` -- **问题**: 缺少 `imwrite` 方法和 `utils.logging` 模块定义 -- **修复**: 添加了缺失的方法和类的类型定义 -- **状态**: ✅ 已修复 - -## 配置说明 - -### 类型检查模式 -- `typeCheckingMode: "basic"` - 使用基础类型检查,平衡准确性和性能 - -### 已禁用的报告 -以下报告已禁用,因为它们会产生大量误报或不适用于当前代码风格: -- `reportAttributeAccessIssue` - Mixin 模式需要访问受保护成员 -- `reportPrivateImportUsage` - 某些内部导入是必要的 -- `reportGeneralTypeIssues` - 允许使用 `Any` 类型 -- `reportUnknownMemberType` - 动态属性访问 - -### 保留的警告 -- `reportUnusedImport: "warning"` - 警告未使用的导入 -- `reportUnusedVariable: "warning"` - 警告未使用的变量 -- `reportDuplicateImport: "warning"` - 警告重复导入 - -## 验证结果 - -- ✅ `douyin.detection.douyin_pixel` 导入成功 -- ✅ `douyin.utils.douyin_helpers` 导入成功 -- ✅ 类型存根文件已创建并扩展 -- ✅ 配置文件已优化 -- ✅ 修复了devnull变量绑定问题 -- ✅ 修复了方法覆盖返回类型不匹配 -- ✅ 修复了静态方法中self未定义问题 -- ✅ 修复了缺失的类型导入 -- ✅ 修复了变量未定义问题 - -**剩余错误**: 约94个错误,主要集中在预约系统和GUI组件中的变量绑定问题。这些错误大多是预期的动态导入模式或复杂的条件分支逻辑,不影响代码功能。 - -## 剩余警告 - -以下警告是预期的,不需要修复: - -1. **访问受保护成员** - Mixin 模式的设计需要 -2. **捕获宽泛异常** - 现有代码风格,用于错误恢复 -3. **字符串语句无效果** - 文档字符串,不影响功能 - -## 后续建议 - -1. 如果需要更严格的类型检查,可以将 `typeCheckingMode` 改为 `"standard"` 或 `"strict"` -2. 可以逐步添加更多类型注解以提高类型检查的准确性 -3. 可以为其他第三方库(如 PIL, numpy)创建类型存根文件 - diff --git a/auto_test_result.txt b/auto_test_result.txt deleted file mode 100644 index 5e0d825..0000000 Binary files a/auto_test_result.txt and /dev/null differ diff --git a/check_jpeg_support.py b/check_jpeg_support.py new file mode 100644 index 0000000..9939208 --- /dev/null +++ b/check_jpeg_support.py @@ -0,0 +1,523 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# pyright: reportOptionalMemberAccess=false +""" +详细检查设备是否支持 JPEG 截图 +测试各种可能的 JPEG 截图方法 +""" + +import os +import sys +import subprocess +import tempfile +import time +from datetime import datetime +from typing import Dict, List, Tuple, cast, IO + +def get_adb_path() -> str: + """获取 adb 路径""" + adb = os.environ.get("ADB_EXECUTABLE", "adb") + if adb.startswith('"') and adb.endswith('"'): + adb = adb[1:-1] + return adb + +def get_device_info(device_id: str) -> Dict[str, str]: + """获取设备信息""" + adb = get_adb_path() + info = {} + + try: + # Android 版本 + result = subprocess.run( + [adb, "-s", device_id, "shell", "getprop", "ro.build.version.release"], + capture_output=True, + text=True, + timeout=3 + ) + info["android_version"] = result.stdout.strip() if result.returncode == 0 else "未知" + except: + info["android_version"] = "未知" + + try: + # 设备型号 + result = subprocess.run( + [adb, "-s", device_id, "shell", "getprop", "ro.product.model"], + capture_output=True, + text=True, + timeout=3 + ) + info["model"] = result.stdout.strip() if result.returncode == 0 else "未知" + except: + info["model"] = "未知" + + try: + # 制造商 + result = subprocess.run( + [adb, "-s", device_id, "shell", "getprop", "ro.product.manufacturer"], + capture_output=True, + text=True, + timeout=3 + ) + info["manufacturer"] = result.stdout.strip() if result.returncode == 0 else "未知" + except: + info["manufacturer"] = "未知" + + return info + +def check_root_access(device_id: str) -> bool: + """检查 root 权限""" + adb = get_adb_path() + try: + result = subprocess.run( + [adb, "-s", device_id, "shell", "su", "-c", "id"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=3, + capture_output=True, + ) + return "uid=0" in result.stdout.decode('utf-8', errors='ignore') + except: + return False + +def test_screencap_jpeg_direct(device_id: str) -> Tuple[bool, str, float]: + """测试方法1: screencap 直接输出 JPEG(如果支持)""" + adb = get_adb_path() + tmp_file = os.path.join(tempfile.gettempdir(), "test_jpeg_direct.jpg") + + # 测试各种可能的 JPEG 参数 + test_commands = [ + ["exec-out", "screencap", "-j"], # 标准 JPEG 参数 + ["exec-out", "screencap", "--jpeg"], # 长参数 + ["exec-out", "screencap", "-f", "jpeg"], # 格式参数 + ["exec-out", "screencap", "-p", "-j"], # PNG + JPEG + ["shell", "screencap", "-j", "/sdcard/test.jpg"], # shell 模式 + ] + + for cmd in test_commands: + try: + if os.path.exists(tmp_file): + try: + os.remove(tmp_file) + except: + pass + + start_time = time.time() + full_cmd = [adb, "-s", device_id] + cmd + + if "exec-out" in cmd: + # 流式读取 + process = subprocess.Popen( + full_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + + if process.stdout is None: + continue + + assert process.stdout is not None + stdout = cast(IO[bytes], process.stdout) + with open(tmp_file, "wb") as f: + while True: + chunk = stdout.read(65536) # type: ignore[union-attr] + if not chunk: + break + f.write(chunk) + + return_code = process.wait(timeout=5) + else: + # shell 模式 + result = subprocess.run( + full_cmd, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + ) + return_code = result.returncode + + if return_code == 0 and "shell" in cmd: + # 如果是 shell 模式,需要 pull + subprocess.run( + [adb, "-s", device_id, "pull", "/sdcard/test.jpg", tmp_file], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + ) + + elapsed = (time.time() - start_time) * 1000 + + if return_code == 0 and os.path.exists(tmp_file): + file_size = os.path.getsize(tmp_file) + # 检查是否是有效的 JPEG(检查文件头) + if file_size > 100: + with open(tmp_file, "rb") as f: + header = f.read(2) + if header == b'\xff\xd8': # JPEG 文件头 + return True, f"命令: {' '.join(cmd)}", elapsed + + except Exception as e: + continue + + return False, "不支持直接 JPEG 输出", 0.0 + +def test_screencap_help(device_id: str) -> Dict[str, bool]: + """检查 screencap 帮助信息,查看支持的参数""" + adb = get_adb_path() + result = {} + + try: + # 获取 screencap 帮助信息 + help_output = "" + try: + help_output += subprocess.run( + [adb, "-s", device_id, "shell", "screencap", "-h"], + capture_output=True, + text=True, + timeout=3, + ).stdout + except: + pass + + try: + help_output += subprocess.run( + [adb, "-s", device_id, "shell", "screencap", "--help"], + capture_output=True, + text=True, + timeout=3, + ).stdout + except: + pass + + # 检查是否包含 JPEG 相关参数 + result["has_jpeg_flag"] = any(keyword in help_output.lower() for keyword in ["-j", "jpeg", "--jpeg"]) + result["has_format_flag"] = any(keyword in help_output.lower() for keyword in ["-f", "format", "--format"]) + result["has_quality_flag"] = any(keyword in help_output.lower() for keyword in ["-q", "quality", "--quality"]) + + except: + result["has_jpeg_flag"] = False + result["has_format_flag"] = False + result["has_quality_flag"] = False + + return result + +def test_device_tools(device_id: str) -> Dict[str, bool]: + """检查设备上是否有可用的转换工具""" + adb = get_adb_path() + tools = {} + + # 检查 ImageMagick convert + try: + result = subprocess.run( + [adb, "-s", device_id, "shell", "which", "convert"], + capture_output=True, + text=True, + timeout=3, + ) + tools["imagemagick"] = result.returncode == 0 and result.stdout.strip() != "" + except: + tools["imagemagick"] = False + + # 检查 /data/local/tmp/convert + try: + result = subprocess.run( + [adb, "-s", device_id, "shell", "test", "-f", "/data/local/tmp/convert"], + capture_output=True, + text=True, + timeout=3, + ) + tools["imagemagick_tmp"] = result.returncode == 0 + except: + tools["imagemagick_tmp"] = False + + # 检查 Python + try: + result = subprocess.run( + [adb, "-s", device_id, "shell", "which", "python3"], + capture_output=True, + text=True, + timeout=3, + ) + tools["python3"] = result.returncode == 0 and result.stdout.strip() != "" + except: + tools["python3"] = False + + # 检查 Python (python) + try: + result = subprocess.run( + [adb, "-s", device_id, "shell", "which", "python"], + capture_output=True, + text=True, + timeout=3, + ) + tools["python"] = result.returncode == 0 and result.stdout.strip() != "" + except: + tools["python"] = False + + # 检查 BusyBox + try: + result = subprocess.run( + [adb, "-s", device_id, "shell", "which", "busybox"], + capture_output=True, + text=True, + timeout=3, + ) + tools["busybox"] = result.returncode == 0 and result.stdout.strip() != "" + except: + tools["busybox"] = False + + return tools + +def test_pc_conversion(device_id: str) -> Tuple[bool, str, float]: + """测试方法2: PC 端转换(PNG -> JPEG)""" + try: + from PIL import Image + import io + except ImportError: + return False, "PIL/Pillow 未安装", 0.0 + + adb = get_adb_path() + tmp_jpg = os.path.join(tempfile.gettempdir(), "test_jpeg_pc.jpg") + + try: + start_time = time.time() + + # 流式接收 PNG + process = subprocess.Popen( + [adb, "-s", device_id, "exec-out", "screencap", "-p"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + + if process.stdout is None: + return False, "无法创建进程输出流", 0.0 + + assert process.stdout is not None + stdout = cast(IO[bytes], process.stdout) + png_data = b"" + while True: + chunk = stdout.read(65536) # type: ignore[union-attr] + if not chunk: + break + png_data += chunk + + process.wait(timeout=10) + + if len(png_data) < 100: + return False, "PNG 数据无效", 0.0 + + # 转换为 JPEG(RGBA 需要先转换为 RGB) + img = Image.open(io.BytesIO(png_data)) + if img.mode == 'RGBA': + # 创建白色背景 + rgb_img = Image.new('RGB', img.size, (255, 255, 255)) + rgb_img.paste(img, mask=img.split()[3]) # 使用 alpha 通道作为 mask + img = rgb_img + elif img.mode != 'RGB': + img = img.convert('RGB') + + jpeg_data = io.BytesIO() + img.save(jpeg_data, format='JPEG', quality=85, optimize=True) + + with open(tmp_jpg, "wb") as f: + f.write(jpeg_data.getvalue()) + + elapsed = (time.time() - start_time) * 1000 + file_size = os.path.getsize(tmp_jpg) + + return True, f"PC 端转换成功,文件大小: {file_size/1024:.1f}KB", elapsed + + except Exception as e: + return False, f"PC 端转换失败: {str(e)}", 0.0 + +def test_device_conversion(device_id: str) -> Tuple[bool, str, float]: + """测试方法3: 设备端转换(如果工具可用)""" + adb = get_adb_path() + tools = test_device_tools(device_id) + + # 测试 ImageMagick + if tools.get("imagemagick") or tools.get("imagemagick_tmp"): + convert_path = "/data/local/tmp/convert" if tools.get("imagemagick_tmp") else "convert" + + try: + start_time = time.time() + tmp_file = os.path.join(tempfile.gettempdir(), "test_jpeg_device.jpg") + + # 使用 shell 命令组合 + cmd = f"screencap -p | {convert_path} - -quality 85 jpg:-" + process = subprocess.Popen( + [adb, "-s", device_id, "exec-out", "sh", "-c", cmd], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + + if process.stdout is None: + raise Exception("无法创建进程输出流") + + assert process.stdout is not None + stdout = cast(IO[bytes], process.stdout) + with open(tmp_file, "wb") as f: + while True: + chunk = stdout.read(65536) # type: ignore[union-attr] + if not chunk: + break + f.write(chunk) + + return_code = process.wait(timeout=10) + elapsed = (time.time() - start_time) * 1000 + + if return_code == 0 and os.path.exists(tmp_file): + file_size = os.path.getsize(tmp_file) + if file_size > 100: + with open(tmp_file, "rb") as f: + header = f.read(2) + if header == b'\xff\xd8': + return True, f"ImageMagick 转换成功,文件大小: {file_size/1024:.1f}KB", elapsed + except Exception as e: + pass + + return False, "设备端无可用转换工具", 0.0 + +def main(): + """主函数""" + print("=" * 70) + print("设备 JPEG 截图支持检查工具") + print("=" * 70) + print() + + # 获取设备ID + device_id = None + if len(sys.argv) > 1: + device_id = sys.argv[1] + else: + device_id = os.environ.get("ANDROID_DEVICE_ID") + + if not device_id: + # 尝试从 adb devices 获取 + try: + adb = get_adb_path() + result = subprocess.run( + [adb, "devices"], + capture_output=True, + text=True, + timeout=3, + ) + lines = result.stdout.strip().split('\n')[1:] # 跳过第一行 + devices = [line.split()[0] for line in lines if line.strip() and 'device' in line] + if len(devices) == 1: + device_id = devices[0] + elif len(devices) > 1: + print(f"[INFO] 发现多个设备: {', '.join(devices)}") + print(f"[INFO] 使用第一个设备: {devices[0]}") + device_id = devices[0] + except: + pass + + if not device_id: + print("[ERROR] 未找到设备ID") + print("使用方法: python check_jpeg_support.py [设备ID]") + print("或设置环境变量: set ANDROID_DEVICE_ID=设备ID") + return + + print(f"设备ID: {device_id}") + print() + + # 获取设备信息 + print("1. 设备信息") + print("-" * 70) + info = get_device_info(device_id) + print(f" 制造商: {info.get('manufacturer', '未知')}") + print(f" 型号: {info.get('model', '未知')}") + print(f" Android 版本: {info.get('android_version', '未知')}") + + has_root = check_root_access(device_id) + print(f" Root 权限: {'是' if has_root else '否'}") + print() + + # 检查 screencap 帮助信息 + print("2. screencap 命令支持检查") + print("-" * 70) + help_info = test_screencap_help(device_id) + print(f" 支持 -j/--jpeg 参数: {'是' if help_info.get('has_jpeg_flag') else '否'}") + print(f" 支持 -f/--format 参数: {'是' if help_info.get('has_format_flag') else '否'}") + print(f" 支持质量参数: {'是' if help_info.get('has_quality_flag') else '否'}") + print() + + # 测试直接 JPEG 输出 + print("3. 测试直接 JPEG 截图") + print("-" * 70) + success, msg, elapsed = test_screencap_jpeg_direct(device_id) + if success: + print(f" [OK] 支持直接 JPEG 输出") + print(f" 方法: {msg}") + print(f" 耗时: {elapsed:.0f}ms") + else: + print(f" [X] 不支持直接 JPEG 输出") + print(f" 原因: {msg}") + print() + + # 检查设备工具 + print("4. 设备端工具检查") + print("-" * 70) + tools = test_device_tools(device_id) + print(f" ImageMagick (convert): {'是' if tools.get('imagemagick') else '否'}") + print(f" ImageMagick (/data/local/tmp): {'是' if tools.get('imagemagick_tmp') else '否'}") + print(f" Python3: {'是' if tools.get('python3') else '否'}") + print(f" Python: {'是' if tools.get('python') else '否'}") + print(f" BusyBox: {'是' if tools.get('busybox') else '否'}") + print() + + # 测试设备端转换 + print("5. 测试设备端转换") + print("-" * 70) + success, msg, elapsed = test_device_conversion(device_id) + if success: + print(f" [OK] 设备端转换可用") + print(f" 方法: {msg}") + print(f" 耗时: {elapsed:.0f}ms") + else: + print(f" [X] 设备端转换不可用") + print(f" 原因: {msg}") + print() + + # 测试 PC 端转换 + print("6. 测试 PC 端转换") + print("-" * 70) + success, msg, elapsed = test_pc_conversion(device_id) + if success: + print(f" [OK] PC 端转换可用") + print(f" 方法: {msg}") + print(f" 耗时: {elapsed:.0f}ms") + else: + print(f" [X] PC 端转换不可用") + print(f" 原因: {msg}") + print() + + # 总结 + print("=" * 70) + print("检查结果总结") + print("=" * 70) + + recommendations = [] + + direct_success, _, _ = test_screencap_jpeg_direct(device_id) + pc_success, _, _ = test_pc_conversion(device_id) + device_success, _, _ = test_device_conversion(device_id) + + if direct_success: + recommendations.append("[OK] 设备支持直接 JPEG 截图(推荐使用)") + elif pc_success: + recommendations.append("[OK] 可以使用 PC 端转换方法(推荐,无需设备端工具)") + elif device_success: + recommendations.append("[OK] 可以使用设备端转换方法(需要安装工具)") + else: + recommendations.append("[X] 当前设备不支持 JPEG 截图,建议使用 PNG 格式") + + for rec in recommendations: + print(f" {rec}") + + print() + print("=" * 70) + +if __name__ == "__main__": + main() + diff --git a/check_screenshot.py b/check_screenshot.py index c8384f8..6660911 100644 --- a/check_screenshot.py +++ b/check_screenshot.py @@ -47,3 +47,9 @@ if __name__ == "__main__": check_screenshot_file() + + + + + + diff --git a/check_screenshot_service_status.py b/check_screenshot_service_status.py index a846d5b..ba98066 100644 --- a/check_screenshot_service_status.py +++ b/check_screenshot_service_status.py @@ -60,3 +60,8 @@ def main(): if __name__ == '__main__': main() + + + + + diff --git a/crash_test_result.txt b/crash_test_result.txt deleted file mode 100644 index 67d02da..0000000 Binary files a/crash_test_result.txt and /dev/null differ diff --git a/demo_log_rotation.py b/demo_log_rotation.py deleted file mode 100644 index 5f8b4f8..0000000 --- a/demo_log_rotation.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python3 -""" -日志轮转功能演示脚本 -================== - -演示新的日志轮转功能的各项特性: -1. 大小限制轮转 -2. 日期+大小混合轮转 -3. 自动压缩 -4. 智能清理 -5. 监控和告警 -""" - -import os -import sys -import time -import logging -from datetime import datetime - -# 添加项目路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from douyin.logging.douyin_logging import ( - configure_logging, - get_log_stats, - cleanup_old_logs, - start_log_monitor, - get_logger, - path_config -) - - -def demo_basic_rotation(): - """演示基本的日志轮转功能""" - print("=== 基本日志轮转演示 ===") - - # 配置日志系统(启用所有新功能) - configure_logging( - log_level="DEBUG", - max_bytes=1024 * 1024, # 1MB用于演示 - backup_count=3, - compress_logs=True, - enable_monitor=True, - monitor_warning_mb=2.0, # 2MB警告 - monitor_critical_mb=5.0, # 5MB严重 - ) - - logger = get_logger("demo_rotation") - - # 生成大量日志来触发轮转 - print("生成测试日志...") - for i in range(100): - logger.info(f"测试日志条目 #{i+1}: " + "这是一条很长的日志消息用于测试轮转功能,包含足够的内容来快速填满文件。" * 10) - if (i + 1) % 20 == 0: - print(f"已生成 {i+1} 条日志") - - print("轮转演示完成") - - -def demo_compression(): - """演示日志压缩功能""" - print("\n=== 日志压缩演示 ===") - - logs_dir = path_config.get_logs_dir() - base_name = "unified" - - # 显示压缩前的统计 - print("压缩前统计:") - stats_before = get_log_stats(logs_dir, base_name) - print(f" 文件数: {stats_before['total_files']}") - print(f" 总大小: {stats_before['total_size_mb']:.2f}MB") - print(f" 压缩文件数: {stats_before['compressed_files']}") - - # 执行手动压缩(7天前) - print("\n执行压缩...") - cleanup_stats = cleanup_old_logs( - logs_dir=logs_dir, - base_name=base_name, - keep_days=365, # 不删除,只压缩 - compress_after_days=0, # 压缩所有文件(演示用) - compress=True, - ) - - print("压缩结果:") - print(f" 压缩文件数: {cleanup_stats['compressed']}") - - # 显示压缩后的统计 - print("\n压缩后统计:") - stats_after = get_log_stats(logs_dir, base_name) - print(f" 文件数: {stats_after['total_files']}") - print(f" 总大小: {stats_after['total_size_mb']:.2f}MB") - print(f" 压缩文件数: {stats_after['compressed_files']}") - if stats_after['compression_ratio'] > 0: - print(f" 压缩率: {stats_after['compression_ratio']*100:.1f}%") - - -def demo_monitoring(): - """演示日志监控功能""" - print("\n=== 日志监控演示 ===") - - def alert_callback(level: str, message: str): - """告警回调函数""" - timestamp = datetime.now().strftime("%H:%M:%S") - print(f"[{timestamp}] 告警 [{level}]: {message}") - - # 启动监控器 - logs_dir = path_config.get_logs_dir() - start_log_monitor( - logs_dir=logs_dir, - base_name="unified", - warning_size_mb=1.0, # 1MB警告 - critical_size_mb=3.0, # 3MB严重 - check_interval=10, # 10秒检查一次 - alert_callback=alert_callback, - ) - - print("监控器已启动,等待检查...") - - # 生成一些日志来触发监控 - logger = get_logger("demo_monitor") - for i in range(50): - logger.warning(f"监控测试日志 #{i+1}: " + "警告消息用于测试监控功能。" * 5) - time.sleep(0.1) - - print("监控演示完成,监控器将在后台继续运行") - - -def demo_management_tools(): - """演示日志管理工具""" - print("\n=== 日志管理工具演示 ===") - - # 模拟运行管理工具 - logs_dir = path_config.get_logs_dir() - base_name = "unified" - - print("运行日志统计:") - os.system(f"python manage_logs.py stats --logs-dir \"{logs_dir}\" --base-name {base_name}") - - print("\n预览清理操作:") - os.system(f"python manage_logs.py cleanup --logs-dir \"{logs_dir}\" --base-name {base_name} --keep-days 30 --dry-run") - - -def main(): - """主演示函数""" - print("日志轮转功能完整演示") - print("=" * 50) - - try: - # 演示1: 基本轮转 - demo_basic_rotation() - - # 等待一下,让监控器有机会运行 - time.sleep(2) - - # 演示2: 压缩功能 - demo_compression() - - # 演示3: 监控功能 - demo_monitoring() - - # 等待监控器检查 - time.sleep(15) - - # 演示4: 管理工具 - demo_management_tools() - - print("\n" + "=" * 50) - print("演示完成!") - print("\n新功能特性:") - print("✓ 大小限制轮转 (100MB/文件)") - print("✓ 日期+大小混合轮转策略") - print("✓ 自动压缩旧日志 (gzip)") - print("✓ 智能清理 (时间+大小+数量三重限制)") - print("✓ 实时监控和告警") - print("✓ 完整的管理工具集") - - except KeyboardInterrupt: - print("\n演示被用户中断") - except Exception as e: - print(f"\n演示过程中出错: {e}") - import traceback - traceback.print_exc() - - -if __name__ == "__main__": - main() diff --git a/docs/scrcpy_手动安装指南.md b/docs/scrcpy_手动安装指南.md index e874fd9..17339b0 100644 --- a/docs/scrcpy_手动安装指南.md +++ b/docs/scrcpy_手动安装指南.md @@ -205,3 +205,8 @@ scrcpy --bit-rate=2M - scrcpy 文档: https://github.com/Genymobile/scrcpy/blob/master/README.md - ADB 安装: https://developer.android.com/studio/releases/platform-tools + + + + + diff --git a/docs/多线程优化实现总结.md b/docs/多线程优化实现总结.md index 23d424e..79d0a77 100644 --- a/docs/多线程优化实现总结.md +++ b/docs/多线程优化实现总结.md @@ -198,3 +198,9 @@ python tools/check_system_config.py + + + + + + diff --git a/docs/多线程截图优化说明.md b/docs/多线程截图优化说明.md index d2aa0d7..3da92b9 100644 --- a/docs/多线程截图优化说明.md +++ b/docs/多线程截图优化说明.md @@ -216,3 +216,9 @@ python tools/check_system_config.py + + + + + + diff --git a/docs/截图服务日志说明.md b/docs/截图服务日志说明.md index 76025d5..c04529a 100644 --- a/docs/截图服务日志说明.md +++ b/docs/截图服务日志说明.md @@ -275,3 +275,9 @@ grep "缓存命中" logs/unified_*.log + + + + + + diff --git a/docs/日志轮转功能说明.md b/docs/日志轮转功能说明.md index 00f638b..f7df523 100644 --- a/docs/日志轮转功能说明.md +++ b/docs/日志轮转功能说明.md @@ -187,3 +187,8 @@ unified_2024-01-15.1.log.gz # 压缩后的文件 4. 重启程序启用新功能 新版本完全向后兼容,现有日志文件无需转换。 + + + + + diff --git a/docs/测试验证指南.md b/docs/测试验证指南.md index 06d9239..75c3081 100644 --- a/docs/测试验证指南.md +++ b/docs/测试验证指南.md @@ -178,3 +178,9 @@ print(f"最后截图时间: {info['last_screenshot_time']}") + + + + + + diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 0cb2213..8666f86 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -21,7 +21,7 @@ from douyin.stage import douyin_stage from douyin.detection import douyin_detection from douyin.fudai import douyin_fudai_detail from douyin.fudai import douyin_fudai_core -import douyin.core.douyin_flow_control as douyin_flow_control +from douyin.core import douyin_flow_control from douyin.other import douyin_live_room from douyin.reservation import douyin_reservation_logic from douyin.utils import douyin_config @@ -313,24 +313,6 @@ class fudai_analyse: except Exception: self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400 - # 启动后台截图服务(多线程优化) - try: - from operations.screenshot_service import ScreenshotService - service = ScreenshotService.get_instance() - if self.device_id: - service.start(self.device_id, interval=1.5) - # 验证服务是否启动成功 - time.sleep(0.1) # 短暂等待 - if service.is_running(): - self._log_kv("截图服务", "后台截图服务启动成功", device_id=self.device_id, interval=1.5) - else: - self._log_kv("截图服务", "后台截图服务启动失败", device_id=self.device_id) - else: - self._log_kv("截图服务", "设备ID为空,无法启动后台截图服务") - except Exception as e: - # 服务启动失败不影响主流程,回退到直接截图 - self._log_kv("截图服务", "后台截图服务启动异常", error=str(e)) - # 记录运行开始 from datetime import datetime @@ -1249,7 +1231,7 @@ class fudai_analyse: except Exception: pass # 查找福袋并打开详情页 - import douyin.core.douyin_flow_control as douyin_flow_control + from douyin.core import douyin_flow_control room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)] original_max_wait = getattr( @@ -2072,7 +2054,7 @@ class fudai_analyse: pass # 查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds 作为最大等待时间) - import douyin.core.douyin_flow_control as douyin_flow_control + from douyin.core import douyin_flow_control room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)] # 临时设置 fudai_icon_max_wait_seconds 为 switch_room_wait_after_stage_diag_seconds diff --git a/douyin/core/fudai_modules/base_interface.py b/douyin/core/fudai_modules/base_interface.py index 11db6e0..701c8da 100644 --- a/douyin/core/fudai_modules/base_interface.py +++ b/douyin/core/fudai_modules/base_interface.py @@ -103,6 +103,12 @@ class BaseFudaiMixin: + + + + + + diff --git a/douyin/core/fudai_modules/fudai_room_utils.py b/douyin/core/fudai_modules/fudai_room_utils.py index 7e78b8c..8d44ac8 100644 --- a/douyin/core/fudai_modules/fudai_room_utils.py +++ b/douyin/core/fudai_modules/fudai_room_utils.py @@ -77,6 +77,12 @@ class RoomUtilsMixin: + + + + + + diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index 49c9736..ec65132 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767151029.2816675, + "updated_ts": 1767171278.9123406, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/detection/core/__init__.py b/douyin/detection/core/__init__.py index ce44efe..ad3f99f 100644 --- a/douyin/detection/core/__init__.py +++ b/douyin/detection/core/__init__.py @@ -49,6 +49,12 @@ __all__ = [ + + + + + + diff --git a/douyin/fudai/core/MODULARIZATION_PLAN.md b/douyin/fudai/core/MODULARIZATION_PLAN.md index d16d688..7817436 100644 --- a/douyin/fudai/core/MODULARIZATION_PLAN.md +++ b/douyin/fudai/core/MODULARIZATION_PLAN.md @@ -90,6 +90,12 @@ + + + + + + diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index 976fd18..cb115a1 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -508,7 +508,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 try: - with ThreadPoolExecutor(max_workers=5) as executor: + # 使用动态线程池大小,根据CPU核心数优化 + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: future_task_list = executor.submit(ocr_task_list) future_content = executor.submit(ocr_content) future_countdown_mm = executor.submit(ocr_countdown_mm) @@ -611,7 +614,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) try: - def ocr_task_list_fallback(): try: return analyser.operation.analyse_pic_word("福袋任务列表", 0) @@ -692,7 +694,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass return None - with ThreadPoolExecutor(max_workers=5) as executor: + # 使用动态线程池大小,根据CPU核心数优化 + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: future_task_list = executor.submit(ocr_task_list_fallback) future_content = executor.submit(ocr_content_fallback) future_countdown_mm = executor.submit(ocr_countdown_mm_fallback) @@ -706,61 +711,61 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_ss_raw = future_countdown_ss.result() value_raw = future_value.result() - # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) - if task_list_raw: - try: - analyser._log_kv( - "福袋", - "OCR识别任务列表区域(备用并行)", - task_list_text=task_list_raw[:200] if task_list_raw else "", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "记录备用任务列表OCR结果日志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - # 检查任务列表中是否包含"观看X分钟"任务 - is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) - if is_watch_task_in_list: + # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) + if task_list_raw: try: analyser._log_kv( "福袋", - "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", + "OCR识别任务列表区域(备用并行)", task_list_text=task_list_raw[:200] if task_list_raw else "", ) except Exception as e: try: analyser._log_kv( "错误", - "记录备用观看任务检测日志失败", + "记录备用任务列表OCR结果日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) except Exception: pass - # 设置标志,让调用方知道这是观看任务 - try: - analyser._is_watch_task_detected = True - except Exception as e: + # 检查任务列表中是否包含"观看X分钟"任务 + is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw)) + if is_watch_task_in_list: try: analyser._log_kv( - "错误", - "设置备用观看任务标志失败", - error=str(e), - error_type=type(e).__name__, - level="WARNING", + "福袋", + "任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理", + task_list_text=task_list_raw[:200] if task_list_raw else "", ) - except Exception: - pass - # 直接返回空内容,后续流程会跳过 - return "", "", 0, 0, 0.0 + except Exception as e: + try: + analyser._log_kv( + "错误", + "记录备用观看任务检测日志失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + # 设置标志,让调用方知道这是观看任务 + try: + analyser._is_watch_task_detected = True + except Exception as e: + try: + analyser._log_kv( + "错误", + "设置备用观看任务标志失败", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + # 直接返回空内容,后续流程会跳过 + return "", "", 0, 0, 0.0 except Exception as fallback_error: # 如果备用并行执行也失败,使用串行执行作为最后兜底 try: diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index af3b847..22ecf3a 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -598,7 +598,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 try: - with ThreadPoolExecutor(max_workers=6) as executor: + # 使用动态线程池大小,根据CPU核心数优化 + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: future_task_list = executor.submit(ocr_task_list) future_content = executor.submit(ocr_content) future_countdown_mm = executor.submit(ocr_countdown_mm) @@ -872,7 +875,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass return None - with ThreadPoolExecutor(max_workers=6) as executor: + # 使用动态线程池大小 + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: future_task_list = executor.submit(ocr_task_list_fallback) future_content = executor.submit(ocr_content_fallback) future_countdown_mm = executor.submit(ocr_countdown_mm_fallback) diff --git a/douyin/fudai/finder/__init__.py b/douyin/fudai/finder/__init__.py index e636fda..7a58e88 100644 --- a/douyin/fudai/finder/__init__.py +++ b/douyin/fudai/finder/__init__.py @@ -54,6 +54,12 @@ __all__ = [ + + + + + + diff --git a/douyin/logging/action_tracker.py b/douyin/logging/action_tracker.py index 596d6a1..3342951 100644 --- a/douyin/logging/action_tracker.py +++ b/douyin/logging/action_tracker.py @@ -45,6 +45,12 @@ __all__ = ["track_action"] + + + + + + diff --git a/douyin/reservation/core/__init__.py b/douyin/reservation/core/__init__.py index 5fd5678..d6b88f2 100644 --- a/douyin/reservation/core/__init__.py +++ b/douyin/reservation/core/__init__.py @@ -64,6 +64,12 @@ __all__ = [ + + + + + + diff --git a/douyin_guaji.code-workspace b/douyin_guaji.code-workspace index 66d9d5d..5a3c7ef 100644 --- a/douyin_guaji.code-workspace +++ b/douyin_guaji.code-workspace @@ -67,6 +67,12 @@ + + + + + + diff --git a/example_filter_usage.py b/example_filter_usage.py deleted file mode 100644 index e69de29..0000000 diff --git a/gui/components/__init__.py b/gui/components/__init__.py index 2cbb5b4..b5ef61f 100644 --- a/gui/components/__init__.py +++ b/gui/components/__init__.py @@ -34,6 +34,12 @@ + + + + + + diff --git a/gui/components/config_manager.py b/gui/components/config_manager.py index 4854403..180fa08 100644 --- a/gui/components/config_manager.py +++ b/gui/components/config_manager.py @@ -74,6 +74,12 @@ def save_ui_to_config( + + + + + + diff --git a/gui/components/device_selector.py b/gui/components/device_selector.py index 31a8ec6..ab3b836 100644 --- a/gui/components/device_selector.py +++ b/gui/components/device_selector.py @@ -84,6 +84,12 @@ def create_device_selector( + + + + + + diff --git a/gui/components/image_viewer.py b/gui/components/image_viewer.py index c3667c3..fb97d14 100644 --- a/gui/components/image_viewer.py +++ b/gui/components/image_viewer.py @@ -70,6 +70,12 @@ def create_image_viewer( + + + + + + diff --git a/gui/components/log_color_config_fixed.py b/gui/components/log_color_config_fixed.py index 1e105de..7bfa900 100644 --- a/gui/components/log_color_config_fixed.py +++ b/gui/components/log_color_config_fixed.py @@ -200,3 +200,9 @@ def apply_operation_color( + + + + + + diff --git a/gui/components/main_window.py b/gui/components/main_window.py index 56e7847..716b95a 100644 --- a/gui/components/main_window.py +++ b/gui/components/main_window.py @@ -66,6 +66,12 @@ def create_main_window( + + + + + + diff --git a/gui/components/ocr_panel.py b/gui/components/ocr_panel.py index 13d84ed..beb3a35 100644 --- a/gui/components/ocr_panel.py +++ b/gui/components/ocr_panel.py @@ -67,6 +67,12 @@ def create_ocr_panel( + + + + + + diff --git a/gui/web_components/__init__.py b/gui/web_components/__init__.py index 88e529e..743413b 100644 --- a/gui/web_components/__init__.py +++ b/gui/web_components/__init__.py @@ -34,6 +34,12 @@ + + + + + + diff --git a/gui/web_components/proc_runner.py b/gui/web_components/proc_runner.py index 2ca62da..e5bedb5 100644 --- a/gui/web_components/proc_runner.py +++ b/gui/web_components/proc_runner.py @@ -42,6 +42,12 @@ __all__ = ["ProcRunner"] + + + + + + diff --git a/install_scrcpy.bat b/install_scrcpy.bat index 10421bc..32c1518 100644 --- a/install_scrcpy.bat +++ b/install_scrcpy.bat @@ -119,3 +119,8 @@ if %errorlevel% == 0 ( ) goto :eof + + + + + diff --git a/manage_logs.py b/manage_logs.py index ff22fb0..a031928 100644 --- a/manage_logs.py +++ b/manage_logs.py @@ -249,3 +249,8 @@ def main(): if __name__ == "__main__": main() + + + + + diff --git a/ocr_compare_results.csv b/ocr_compare_results.csv deleted file mode 100644 index 6ecb6d8..0000000 --- a/ocr_compare_results.csv +++ /dev/null @@ -1,2 +0,0 @@ -path,whole_time,whole_text,crop_time,crop_text -pic\debug_captures\2025-12-28\20251228_190754_ocr_绂忚浠诲姟鍒楄〃_after_ocr_mode_0_used_img2_False_avg_confidence_0.9496.png,0.0,,0.0, diff --git a/operations/ocr_operations.py b/operations/ocr_operations.py index 02e07f5..40850f9 100644 --- a/operations/ocr_operations.py +++ b/operations/ocr_operations.py @@ -14,7 +14,15 @@ from typing import Any, Optional 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") + +# 优化OMP_NUM_THREADS:允许底层库使用多线程,但不要设置太高避免线程竞争 +# 设置为CPU核心数的一半,平衡性能和资源使用 +import os as os_module +cpu_count = os_module.cpu_count() or 4 +# 对于OCR任务,每个线程内部会使用多个OMP线程,所以设置为2-4比较合适 +# 如果CPU核心数>=8,设置为4;否则设置为2 +optimal_omp_threads = min(4, max(2, cpu_count // 3)) +os.environ.setdefault("OMP_NUM_THREADS", str(optimal_omp_threads)) class OCRProcessor: diff --git a/operations/scrcpy_screenshot.py b/operations/scrcpy_screenshot.py index eb080eb..6a42a17 100644 --- a/operations/scrcpy_screenshot.py +++ b/operations/scrcpy_screenshot.py @@ -99,3 +99,8 @@ def get_scrcpy_screenshot(device_id: str, output_path: str) -> bool: scrcpy = ScrcpyScreenshot() return scrcpy.get_screenshot(device_id, output_path) + + + + + diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index 4974e83..0076e00 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -3,6 +3,7 @@ 包含截图、图片裁剪等截图相关操作。 支持后台截图服务和多线程优化。 """ +# pyright: reportOptionalMemberAccess=false from __future__ import annotations @@ -70,11 +71,10 @@ class ScreenshotOperations: try: import path_config out_dir = path_config.get_pic_dir() - except Exception: + except Exception: # type: ignore # 回退到旧路径(向后兼容) - import path_config - out_dir = path_config.get_pic_dir() - else: + out_dir = os.path.join(os.path.dirname(__file__), "pic") + else: # type: ignore out_dir = os.path.join(os.path.dirname(__file__), "target_pic") if not os.path.exists(out_dir): os.makedirs(out_dir) diff --git a/run_test.py b/run_test.py new file mode 100644 index 0000000..eb3caf9 --- /dev/null +++ b/run_test.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import os +import sys +import subprocess + +# 查找目标文件 +target_dir = "pic/debug_captures/2025-12-31" +if os.path.exists(target_dir): + files = os.listdir(target_dir) + # 查找包含关键字的文件 + target_file = None + for f in files: + if "152118" in f and "福袋倒计时_分钟" in f and "识别后" in f and "390,1110" in f: + target_file = f + break + + if target_file: + full_path = os.path.join(target_dir, target_file) + print(f"找到文件: {target_file}") + print(f"完整路径: {full_path}") + print("\n开始运行测试...\n") + + # 运行测试脚本 + cmd = [sys.executable, "test_real_parallel_ocr.py", full_path] + subprocess.run(cmd, encoding='utf-8') + else: + print("未找到目标文件") + print("可用文件列表(前10个):") + for f in files[:10]: + if "152118" in f: + print(f" {f}") +else: + print(f"目录不存在: {target_dir}") + diff --git a/screenshot_service_analysis.md b/screenshot_service_analysis.md deleted file mode 100644 index 7b6189a..0000000 --- a/screenshot_service_analysis.md +++ /dev/null @@ -1,121 +0,0 @@ -# 后台截图服务状态分析报告 - -## 📊 检查结果总结 - -### ✅ 服务启动记录 -从日志中找到了以下服务启动记录: -- **2025-12-31 01:22:25** - 后台截图服务启动成功 -- **2025-12-31 01:28:54** - 后台截图服务启动成功 -- **2025-12-31 10:40:10** - 后台截图服务启动成功 -- **2025-12-31 11:17:09** - 后台截图服务启动成功(最近一次) - -### ❌ 当前状态 -根据 `check_screenshot_service_status.py` 的检查结果: - -``` -服务状态: - 运行中: False - 设备ID: None - 最后截图时间: 2025-12-31 11:35:17(约10秒前) - 缓存状态: 已过期 - 最后成功: False - 后台线程: 未创建 -``` - -## 🔍 问题分析 - -### 1. 服务已停止 -- **现象**: 服务状态显示 `running: False` -- **原因**: - - 程序可能已退出 - - 服务线程可能异常退出 - - 设备ID变更导致服务重启失败 - -### 2. 设备ID为空 -- **现象**: `device_id: None` -- **影响**: 无法启动新的截图服务 -- **可能原因**: - - 程序启动时未正确设置设备ID - - 设备连接断开 - -### 3. 最后一次截图失败 -- **现象**: `last_success: False` -- **时间**: 11:35:17(约10秒前) -- **可能原因**: - - ADB连接问题 - - 设备端截图失败 - - 文件写入失败 - -## 💡 解决方案 - -### 方案1: 重启程序(推荐) -1. 确保设备已连接:`adb devices` -2. 重新启动主程序,确保设备ID正确设置 -3. 服务会自动启动 - -### 方案2: 手动启动服务 -```python -from operations.screenshot_service import ScreenshotService -service = ScreenshotService.get_instance() -device_id = "你的设备ID" # 从 adb devices 获取 -service.start(device_id, interval=3.5) -``` - -### 方案3: 检查设备连接 -```bash -# 检查设备 -adb devices - -# 测试截图 -adb exec-out screencap -p > test.png -``` - -## 📈 性能优化效果 - -虽然服务当前未运行,但从之前的优化来看: - -### 优化前 -- 单次截图: ~3.2秒 -- 无缓存机制 - -### 优化后 -- 单次截图: ~2.0秒(流式读取优化) -- 缓存命中: <10ms -- 后台间隔: 3.5秒 -- 缓存有效期: 4.0秒 - -## 🎯 建议 - -1. **立即行动**: 重启程序,确保设备ID正确设置 -2. **监控日志**: 关注是否有"后台截图服务启动成功"的日志 -3. **验证服务**: 运行 `python check_screenshot_service_status.py` 确认服务运行 -4. **检查性能**: 观察截图耗时是否显著降低(缓存命中时 <10ms) - -## 📝 验证步骤 - -1. 运行诊断工具: - ```bash - python diagnose_screenshot_service.py - ``` - -2. 检查服务状态: - ```bash - python check_screenshot_service_status.py - ``` - -3. 查看最新日志: - ```bash - # 查看最后50行日志 - tail -50 logs/actions.log - ``` - -## ✅ 成功标志 - -服务正常运行时应看到: -- `运行中: True` -- `设备ID: 你的设备ID(如 MB75DEFQZHZTGMLJ)` -- `最后截图时间: 最近几秒内` -- `缓存状态: 有效` -- `最后成功: True` -- `后台线程存活: True` - diff --git a/test_full_screenshot_flow.py b/test_full_screenshot_flow.py deleted file mode 100644 index 10cb066..0000000 --- a/test_full_screenshot_flow.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -"""测试完整的截图流程""" - -import time -from operations.screenshot_service import ScreenshotService -from operations.screenshot_operations import ScreenshotOperations - -def test_screenshot_flow(device_id=None): - """测试截图流程""" - print("=== 截图流程测试 ===") - - if not device_id: - # 尝试从环境变量或其他地方获取设备ID - import os - device_id = os.environ.get("ANDROID_DEVICE_ID") - if not device_id: - print("[ERROR] 未找到设备ID,请设置环境变量 ANDROID_DEVICE_ID") - return - - print(f"设备ID: {device_id}") - - # 1. 测试直接截图 - print("\n1. 测试直接截图...") - ops = ScreenshotOperations() - start_time = time.time() - result1 = ops.get_screenshot(device_id, use_service=False) - time1 = (time.time() - start_time) * 1000 - print(f"直接截图: 结果={result1}, 时间={time1:.0f}ms") - print("\n2. 启动后台截图服务...") - service = ScreenshotService.get_instance() - service.start(device_id, interval=1.5) - print("服务启动完成,等待第一次截图...") - - # 等待服务完成第一次截图 - time.sleep(3) - - # 3. 测试服务模式(应该使用缓存) - print("\n3. 测试服务模式(应该使用缓存)...") - start_time = time.time() - result2 = ops.get_screenshot(device_id, use_service=True) - time2 = (time.time() - start_time) * 1000 - print(f"服务模式截图: 结果={result2}, 时间={time2:.0f}ms") - # 4. 再次测试缓存命中 - print("\n4. 再次测试缓存命中...") - start_time = time.time() - result3 = ops.get_screenshot(device_id, use_service=True) - time3 = (time.time() - start_time) * 1000 - print(f"缓存命中截图: 结果={result3}, 时间={time3:.0f}ms") - # 5. 显示服务状态 - print("\n5. 服务状态信息:") - cache_info = service.get_cache_info() - print(f" 运行状态: {cache_info['running']}") - if cache_info['last_screenshot_time'] > 0: - time_since = time.time() - cache_info['last_screenshot_time'] - print(f" 上次截图时间: {time_since:.1f}秒前") - print(f" 缓存有效: {time_since < cache_info['cache_valid_duration']}") - - print("\n=== 测试完成 ===") - -if __name__ == "__main__": - test_screenshot_flow() diff --git a/test_hw_output.png b/test_hw_output.png new file mode 100644 index 0000000..b1943cc Binary files /dev/null and b/test_hw_output.png differ diff --git a/test_log_rotation.py b/test_log_rotation.py deleted file mode 100644 index 2e39e01..0000000 --- a/test_log_rotation.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python3 -""" -简单测试日志轮转功能 -""" - -import sys -import os - -# 添加项目路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from douyin.logging.douyin_logging import get_log_stats, path_config - -def main(): - print("=== 日志轮转功能测试 ===") - - try: - # 获取日志目录 - logs_dir = path_config.get_logs_dir() - print(f"日志目录: {logs_dir}") - - # 获取统计信息 - stats = get_log_stats(logs_dir, 'unified') - - print("统计信息:") - print(f" 文件数: {stats['total_files']}") - print(f" 总大小: {stats['total_size_mb']:.1f}MB") - print(f" 压缩文件: {stats['compressed_files']}") - if stats['compression_ratio'] > 0: - print(f" 压缩率: {stats['compression_ratio']*100:.1f}%") - print(f" 最旧文件: {stats['oldest_file'] or 'N/A'}") - print(f" 最新文件: {stats['newest_file'] or 'N/A'}") - - print("\n[OK] 日志轮转功能测试完成!") - - except Exception as e: - print(f"[ERROR] 测试失败: {e}") - import traceback - traceback.print_exc() - -if __name__ == "__main__": - main() diff --git a/test_main_startup.py b/test_main_startup.py deleted file mode 100644 index 9735417..0000000 --- a/test_main_startup.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -测试主程序启动截图服务的过程 -""" - -import sys -import os -sys.path.insert(0, os.path.dirname(__file__)) - -def test_main_startup(): - print("Testing main startup process...") - - # 模拟主程序中的截图服务启动过程 - try: - print("Step 1: Import ScreenshotService") - from operations.screenshot_service import ScreenshotService - print("OK: Import successful") - - print("Step 2: Get instance") - service = ScreenshotService.get_instance() - print("OK: Got instance") - - print("Step 3: Check if device_id exists") - analyser_device_id = "MB75DEFQZHZTGMLJ" # 从日志中看到的设备ID - print(f"Device ID: {analyser_device_id}") - - if analyser_device_id: - print("Step 4: Start service") - service.start(analyser_device_id, interval=1.5) - print("OK: Service started") - - # 等待一下看看日志 - import time - time.sleep(2) - - print("Step 5: Check service status") - info = service.get_cache_info() - print(f"Service info: {info}") - - print("Step 6: Stop service") - service.stop() - print("OK: Service stopped") - - else: - print("ERROR: No device_id") - - except Exception as e: - import traceback - print(f"ERROR during startup: {e}") - traceback.print_exc() - -if __name__ == "__main__": - test_main_startup() - - diff --git a/test_ocr_multithread.py b/test_ocr_multithread.py new file mode 100644 index 0000000..dd0ffa0 --- /dev/null +++ b/test_ocr_multithread.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +测试OCR多线程优化效果 +""" + +import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from operations.screenshot_service import get_optimal_workers + +def test_ocr_multithread_config(): + """测试OCR多线程配置""" + print("=" * 70) + print("OCR多线程配置检查") + print("=" * 70) + print() + + # 1. CPU信息 + cpu_count = os.cpu_count() or 4 + print(f"1. CPU信息") + print("-" * 70) + print(f" CPU核心数: {cpu_count}") + print() + + # 2. OMP线程数配置 + print("2. OMP线程数配置(底层库多线程)") + print("-" * 70) + omp_threads = os.environ.get("OMP_NUM_THREADS", "未设置") + print(f" OMP_NUM_THREADS: {omp_threads}") + + # 计算推荐的OMP线程数 + optimal_omp_threads = min(4, max(2, cpu_count // 3)) + print(f" 推荐值: {optimal_omp_threads} (根据CPU核心数动态计算)") + print() + + # 3. 线程池大小配置 + print("3. 线程池大小配置(任务级多线程)") + print("-" * 70) + optimal_workers = get_optimal_workers() + print(f" 推荐线程池大小: {optimal_workers} (根据CPU核心数动态计算)") + print(f" 说明: 用于并行执行多个OCR任务") + print() + + # 4. 优化说明 + print("4. 优化说明") + print("-" * 70) + print(" 优化前:") + print(" - OMP_NUM_THREADS=1 (限制底层库只能使用1个线程)") + print(" - 线程池大小固定为6 (未充分利用多核CPU)") + print() + print(" 优化后:") + print(f" - OMP_NUM_THREADS={optimal_omp_threads} (允许底层库使用多线程)") + print(f" - 线程池大小={optimal_workers} (根据CPU核心数动态调整)") + print() + print(" 预期效果:") + print(" - 底层库(PaddleOCR/EasyOCR)可以并行处理图像") + print(" - 多个OCR任务可以并行执行") + print(" - 充分利用多核CPU资源") + print(" - 预计性能提升: 30-50% (取决于任务数量和CPU核心数)") + print() + + # 5. 验证OCR引擎是否已初始化 + print("5. OCR引擎状态") + print("-" * 70) + try: + from operations.ocr_operations import _ocr_processor + if _ocr_processor.ocr is not None: + print(f" OCR引擎: {_ocr_processor.ocr_type}") + print(" 状态: 已初始化") + else: + print(" 状态: 未初始化(延迟初始化)") + except Exception as e: + print(f" 状态: 检查失败 - {e}") + print() + + print("=" * 70) + print("检查完成") + print("=" * 70) + +def test_ocr_performance(): + """测试OCR性能(需要实际运行OCR)""" + print() + print("=" * 70) + print("OCR性能测试") + print("=" * 70) + print() + print("提示: 此测试需要实际运行OCR任务") + print(" 可以在实际使用中观察OCR耗时变化") + print() + print("测试方法:") + print("1. 运行程序,观察OCR任务的耗时") + print("2. 对比优化前后的性能差异") + print("3. 查看日志中的OCR耗时信息") + print() + +if __name__ == "__main__": + test_ocr_multithread_config() + test_ocr_performance() + + diff --git a/test_ocr_speed.py b/test_ocr_speed.py new file mode 100644 index 0000000..a5414ce --- /dev/null +++ b/test_ocr_speed.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +测试OCR识别速度 +""" + +import os +import sys +import time +from pathlib import Path + +def test_ocr_speed(image_path: str, iterations: int = 5): + """测试OCR识别速度""" + print("=" * 70) + print("OCR速度测试") + print("=" * 70) + print() + + # 检查图片文件是否存在 + if not os.path.exists(image_path): + print(f"[ERROR] 图片文件不存在: {image_path}") + return + + file_size = os.path.getsize(image_path) / 1024 # KB + print(f"测试图片: {image_path}") + print(f"文件大小: {file_size:.2f} KB") + print(f"测试次数: {iterations} 次") + print() + + # 获取图片信息 + try: + from PIL import Image + img = Image.open(image_path) + width, height = img.size + print(f"图片尺寸: {width}x{height}") + print(f"图片模式: {img.mode}") + + # 计算图片像素数 + total_pixels = width * height + print(f"总像素数: {total_pixels:,}") + + # 判断图片大小 + if total_pixels > 2000000: # 大于200万像素 + print(f" [提示] 图片较大,OCR处理可能需要较长时间") + print(f" 建议: 先裁剪到目标区域(如200x200)再OCR,可以显著提升速度") + print() + except Exception as e: + print(f"[WARNING] 无法读取图片信息: {e}") + print() + + # 检查OCR引擎 + print("1. OCR引擎信息") + print("-" * 70) + try: + from operations.ocr_operations import _ocr_processor + _ocr_processor._ensure_ocr() + + if _ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + return + + print(f" OCR引擎: {_ocr_processor.ocr_type}") + print(f" OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}") + print() + except Exception as e: + print(f"[ERROR] OCR引擎检查失败: {e}") + return + + # 测试OCR速度 + print("2. OCR速度测试") + print("-" * 70) + + times = [] + results = [] + + for i in range(iterations): + try: + # 导入OCR操作 + from Underlying_Operations import underlying_operations + ops = underlying_operations() + + # 确保OCR已初始化 + ops._ensure_ocr() + + # 执行OCR(使用analyse_pic_digits,因为这是数字识别) + start_time = time.time() + + # 直接使用图片路径进行OCR + # 注意:如果图片很大,OCR会处理整个图片,这可能会很慢 + # 建议使用预处理后的小图片进行测试 + result = ops.analyse_pic_digits( + "测试图片", + change_color=1, # 数字识别模式 + pic_path=image_path + ) + + # 记录各个阶段的耗时(如果可能) + # 注意:analyse_pic_digits 内部会进行图像预处理和OCR识别 + + elapsed = (time.time() - start_time) * 1000 # 转换为毫秒 + times.append(elapsed) + results.append(result) + + print(f" 第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {result[:50] if result else '(空)'}") + + except Exception as e: + print(f" 第 {i+1} 次: 失败 - {e}") + import traceback + traceback.print_exc() + + print() + + # 统计结果 + if times: + print("3. 性能统计") + print("-" * 70) + avg_time = sum(times) / len(times) + min_time = min(times) + max_time = max(times) + + print(f" 平均耗时: {avg_time:.0f}ms") + print(f" 最快耗时: {min_time:.0f}ms") + print(f" 最慢耗时: {max_time:.0f}ms") + print(f" 耗时范围: {max_time - min_time:.0f}ms") + print() + + # 识别结果统计 + print("4. 识别结果") + print("-" * 70) + unique_results = list(set(results)) + for i, result in enumerate(unique_results, 1): + count = results.count(result) + print(f" 结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)") + print() + + # 性能评估 + print("5. 性能评估") + print("-" * 70) + if avg_time < 500: + print(" [优秀] OCR速度很快 (< 500ms)") + elif avg_time < 1000: + print(" [良好] OCR速度良好 (500-1000ms)") + elif avg_time < 2000: + print(" [一般] OCR速度一般 (1000-2000ms)") + elif avg_time < 5000: + print(" [较慢] OCR速度较慢 (2000-5000ms)") + else: + print(" [很慢] OCR速度很慢 (> 5000ms)") + print(" 提示: 如果图片很大,建议先裁剪到目标区域再OCR") + + # 多线程效果评估 + cpu_count = os.cpu_count() or 4 + omp_threads = int(os.environ.get('OMP_NUM_THREADS', '1')) + print(f" CPU核心数: {cpu_count}") + print(f" OMP线程数: {omp_threads}") + if omp_threads > 1: + print(f" [优化] 已启用底层多线程 (OMP_NUM_THREADS={omp_threads})") + else: + print(f" [提示] 未启用底层多线程,可以优化") + print() + else: + print("[ERROR] 所有测试都失败了") + + print("=" * 70) + print("测试完成") + print("=" * 70) + +def main(): + """主函数""" + # 默认图片路径 + default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" + + # 从命令行参数获取图片路径 + if len(sys.argv) > 1: + image_path = sys.argv[1] + else: + image_path = default_image + + # 获取测试次数 + iterations = 5 + if len(sys.argv) > 2: + try: + iterations = int(sys.argv[2]) + except: + pass + + # 转换为绝对路径 + if not os.path.isabs(image_path): + # 尝试相对于项目根目录 + project_root = os.path.dirname(os.path.abspath(__file__)) + image_path = os.path.join(project_root, image_path) + + test_ocr_speed(image_path, iterations) + +if __name__ == "__main__": + main() + diff --git a/test_ocr_speed_optimized.py b/test_ocr_speed_optimized.py new file mode 100644 index 0000000..4e20d06 --- /dev/null +++ b/test_ocr_speed_optimized.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +测试OCR识别速度(优化版 - 支持裁剪区域测试) +""" + +import os +import sys +import time +from typing import Optional +from PIL import Image + +def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iterations: int = 5): + """在指定区域测试OCR速度""" + print("=" * 70) + print("OCR速度测试(区域优化版)") + print("=" * 70) + print() + + # 检查图片文件是否存在 + if not os.path.exists(image_path): + print(f"[ERROR] 图片文件不存在: {image_path}") + return + + # 加载图片 + try: + img = Image.open(image_path) + original_size = img.size + print(f"原始图片: {image_path}") + print(f"原始尺寸: {original_size[0]}x{original_size[1]}") + print(f"原始像素数: {original_size[0] * original_size[1]:,}") + print() + except Exception as e: + print(f"[ERROR] 无法加载图片: {e}") + return + + # 如果指定了区域,裁剪图片 + if region: + x1, y1, x2, y2 = region + img = img.crop((x1, y1, x2, y2)) + print(f"裁剪区域: ({x1}, {y1}) - ({x2}, {y2})") + print(f"裁剪后尺寸: {img.size[0]}x{img.size[1]}") + print(f"裁剪后像素数: {img.size[0] * img.size[1]:,}") + print() + + # 保存裁剪后的临时图片 + import tempfile + temp_dir = tempfile.gettempdir() + temp_image = os.path.join(temp_dir, "ocr_test_crop.png") + img.save(temp_image) + test_image_path = temp_image + else: + test_image_path = image_path + + # 测试OCR速度 + print("开始OCR速度测试...") + print("-" * 70) + + try: + from operations.ocr_operations import _ocr_processor + _ocr_processor._ensure_ocr() + + if _ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + return + + print(f"OCR引擎: {_ocr_processor.ocr_type}") + print(f"OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}") + print() + except Exception as e: + print(f"[ERROR] OCR引擎检查失败: {e}") + return + + # 执行多次测试 + times = [] + results = [] + + for i in range(iterations): + try: + import numpy as np + + # 准备图像 + if img.mode != 'RGB': + img_rgb = img.convert('RGB') + else: + img_rgb = img + + # 转换为numpy数组 + img_np = np.array(img_rgb) + + # 执行OCR + start_time = time.time() + + if _ocr_processor.ocr_type == "easyocr": + result = _ocr_processor.ocr.readtext(img_np) + else: + result = _ocr_processor.ocr.ocr(img_np) + + elapsed = (time.time() - start_time) * 1000 # 转换为毫秒 + + # 提取文本 + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + + times.append(elapsed) + results.append(text) + + print(f"第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {text[:50] if text else '(空)'}") + + except Exception as e: + print(f"第 {i+1} 次: 失败 - {e}") + import traceback + traceback.print_exc() + + print() + + # 统计结果 + if times: + print("性能统计") + print("-" * 70) + avg_time = sum(times) / len(times) + min_time = min(times) + max_time = max(times) + + print(f"平均耗时: {avg_time:.0f}ms ({avg_time/1000:.2f}秒)") + print(f"最快耗时: {min_time:.0f}ms ({min_time/1000:.2f}秒)") + print(f"最慢耗时: {max_time:.0f}ms ({max_time/1000:.2f}秒)") + print(f"耗时范围: {max_time - min_time:.0f}ms") + print() + + # 识别结果 + print("识别结果") + print("-" * 70) + unique_results = list(set(results)) + for i, result in enumerate(unique_results, 1): + count = results.count(result) + print(f"结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)") + print() + + # 性能对比 + if region: + original_pixels = original_size[0] * original_size[1] + crop_pixels = img.size[0] * img.size[1] + reduction = (1 - crop_pixels / original_pixels) * 100 + print("性能对比") + print("-" * 70) + print(f"原始图片像素: {original_pixels:,}") + print(f"裁剪后像素: {crop_pixels:,}") + print(f"像素减少: {reduction:.1f}%") + print(f"预计原始图片OCR耗时: {avg_time * (original_pixels / crop_pixels):.0f}ms") + print() + + # 清理临时文件 + if region and os.path.exists(test_image_path): + try: + os.remove(test_image_path) + except: + pass + + print("=" * 70) + print("测试完成") + print("=" * 70) + +def main(): + """主函数""" + # 默认图片路径 + default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" + + # 从命令行参数获取图片路径 + if len(sys.argv) > 1: + image_path = sys.argv[1] + else: + image_path = default_image + + # 转换为绝对路径 + if not os.path.isabs(image_path): + project_root = os.path.dirname(os.path.abspath(__file__)) + image_path = os.path.join(project_root, image_path) + + # 从文件名提取区域信息(如果文件名包含坐标) + region = None + if "(480,1110)-(570,1230)" in image_path: + # 提取坐标 + region = (480, 1110, 570, 1230) + print("[INFO] 检测到文件名中的坐标信息,将使用裁剪区域进行测试") + print() + + # 获取测试次数 + iterations = 5 + if len(sys.argv) > 2: + try: + iterations = int(sys.argv[2]) + except: + pass + + # 先测试完整图片 + print("=" * 70) + print("测试1: 完整图片OCR") + print("=" * 70) + test_ocr_on_region(image_path, region=None, iterations=iterations) + + # 如果检测到区域信息,再测试裁剪区域 + if region: + print() + print("=" * 70) + print("测试2: 裁剪区域OCR(推荐)") + print("=" * 70) + test_ocr_on_region(image_path, region=region, iterations=iterations) + +if __name__ == "__main__": + main() + + diff --git a/test_parallel_ocr_performance.py b/test_parallel_ocr_performance.py new file mode 100644 index 0000000..ee4dfd6 --- /dev/null +++ b/test_parallel_ocr_performance.py @@ -0,0 +1,384 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +测试并行OCR性能,对比优化前后的提升 +""" + +import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from PIL import Image +import numpy as np + +def test_serial_ocr(image_path: str, num_tasks: int = 3): + """测试串行OCR(优化前的方式)""" + print("=" * 70) + print("测试1: 串行OCR(优化前)") + print("=" * 70) + print(f"任务数量: {num_tasks}") + print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}") + print() + + # 加载图片 + try: + img = Image.open(image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + img_np = np.array(img) + print(f"图片尺寸: {img.size[0]}x{img.size[1]}") + print() + except Exception as e: + print(f"[ERROR] 无法加载图片: {e}") + return None + + # 初始化OCR + try: + from operations.ocr_operations import _ocr_processor + _ocr_processor._ensure_ocr() + + if _ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + return None + + print(f"OCR引擎: {_ocr_processor.ocr_type}") + print() + except Exception as e: + print(f"[ERROR] OCR引擎初始化失败: {e}") + return None + + # 串行执行OCR任务 + start_time = time.time() + results = [] + + print("开始串行OCR测试...") + for i in range(num_tasks): + task_start = time.time() + + try: + if _ocr_processor.ocr_type == "easyocr": + result = _ocr_processor.ocr.readtext(img_np) + else: + result = _ocr_processor.ocr.ocr(img_np) + + # 提取文本 + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + + task_elapsed = (time.time() - task_start) * 1000 + results.append(text) + print(f" 任务 {i+1}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {text[:30] if text else '(空)'}") + except Exception as e: + print(f" 任务 {i+1}/{num_tasks}: 失败 - {e}") + results.append(None) + + total_elapsed = (time.time() - start_time) * 1000 + + print() + print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms") + print() + + return total_elapsed + +def test_parallel_ocr(image_path: str, num_tasks: int = 3): + """测试并行OCR(优化后的方式)""" + print("=" * 70) + print("测试2: 并行OCR(优化后)") + print("=" * 70) + print(f"任务数量: {num_tasks}") + print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}") + + # 获取最优线程数 + try: + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + print(f"线程池大小: {optimal_workers}") + except: + optimal_workers = 6 + print(f"线程池大小: {optimal_workers} (默认)") + print() + + # 加载图片 + try: + img = Image.open(image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + img_np = np.array(img) + print(f"图片尺寸: {img.size[0]}x{img.size[1]}") + print() + except Exception as e: + print(f"[ERROR] 无法加载图片: {e}") + return None + + # 初始化OCR + try: + from operations.ocr_operations import _ocr_processor + _ocr_processor._ensure_ocr() + + if _ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + return None + + print(f"OCR引擎: {_ocr_processor.ocr_type}") + print() + except Exception as e: + print(f"[ERROR] OCR引擎初始化失败: {e}") + return None + + # 定义OCR任务函数 + def ocr_task(task_id): + """单个OCR任务""" + try: + if _ocr_processor.ocr_type == "easyocr": + result = _ocr_processor.ocr.readtext(img_np) + else: + result = _ocr_processor.ocr.ocr(img_np) + + # 提取文本 + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + + return text + except Exception as e: + print(f" 任务 {task_id} 失败: {e}") + return None + + # 并行执行OCR任务 + start_time = time.time() + results = [] + + print("开始并行OCR测试...") + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: + # 提交所有任务 + futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} + + # 收集结果 + task_times = {} + for future in futures: + task_id = futures[future] + task_start = time.time() + try: + result = future.result() + task_elapsed = (time.time() - task_start) * 1000 + task_times[task_id] = task_elapsed + results.append(result) + print(f" 任务 {task_id}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {result[:30] if result else '(空)'}") + except Exception as e: + print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}") + results.append(None) + + total_elapsed = (time.time() - start_time) * 1000 + + print() + print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + if task_times: + avg_task_time = sum(task_times.values()) / len(task_times) + print(f"平均每个任务: {avg_task_time:.0f}ms") + print(f"并行效率: {avg_task_time * num_tasks / total_elapsed:.1f}x (理想情况下应该接近{num_tasks}x)") + print() + + return total_elapsed + +def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): + """测试并行OCR(使用旧的配置:OMP_NUM_THREADS=1, max_workers=6)""" + print("=" * 70) + print("测试3: 并行OCR(旧配置:OMP=1, 线程池=6)") + print("=" * 70) + print(f"任务数量: {num_tasks}") + + # 临时设置旧配置 + old_omp = os.environ.get('OMP_NUM_THREADS', '4') + os.environ['OMP_NUM_THREADS'] = '1' + print(f"OMP_NUM_THREADS: 1 (临时设置)") + print(f"线程池大小: 6 (固定)") + print() + + # 加载图片 + try: + img = Image.open(image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + img_np = np.array(img) + print(f"图片尺寸: {img.size[0]}x{img.size[1]}") + print() + except Exception as e: + print(f"[ERROR] 无法加载图片: {e}") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + # 重新初始化OCR(使用新的OMP设置) + try: + from operations.ocr_operations import _ocr_processor + # 注意:OCR引擎已经初始化,OMP设置可能不会立即生效 + # 但我们可以测试线程池的效果 + print(f"OCR引擎: {_ocr_processor.ocr_type}") + print("注意: OMP设置可能需要重启程序才能完全生效") + print() + except Exception as e: + print(f"[ERROR] OCR引擎检查失败: {e}") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + # 定义OCR任务函数 + def ocr_task(task_id): + """单个OCR任务""" + try: + if _ocr_processor.ocr_type == "easyocr": + result = _ocr_processor.ocr.readtext(img_np) + else: + result = _ocr_processor.ocr.ocr(img_np) + + # 提取文本 + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + + return text + except Exception as e: + print(f" 任务 {task_id} 失败: {e}") + return None + + # 并行执行OCR任务(使用旧的线程池大小) + start_time = time.time() + results = [] + + print("开始并行OCR测试(旧配置)...") + with ThreadPoolExecutor(max_workers=6) as executor: + # 提交所有任务 + futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} + + # 收集结果 + task_times = {} + for future in futures: + task_id = futures[future] + task_start = time.time() + try: + result = future.result() + task_elapsed = (time.time() - task_start) * 1000 + task_times[task_id] = task_elapsed + results.append(result) + print(f" 任务 {task_id}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {result[:30] if result else '(空)'}") + except Exception as e: + print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}") + results.append(None) + + total_elapsed = (time.time() - start_time) * 1000 + + # 恢复OMP设置 + os.environ['OMP_NUM_THREADS'] = old_omp + + print() + print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + if task_times: + avg_task_time = sum(task_times.values()) / len(task_times) + print(f"平均每个任务: {avg_task_time:.0f}ms") + print() + + return total_elapsed + +def main(): + """主函数""" + # 默认图片路径 + default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" + + # 从命令行参数获取图片路径 + if len(sys.argv) > 1: + image_path = sys.argv[1] + else: + image_path = default_image + + # 转换为绝对路径 + if not os.path.isabs(image_path): + project_root = os.path.dirname(os.path.abspath(__file__)) + image_path = os.path.join(project_root, image_path) + + # 检查文件是否存在 + if not os.path.exists(image_path): + print(f"[ERROR] 图片文件不存在: {image_path}") + return + + # 获取任务数量(默认3个,减少测试时间) + num_tasks = 3 + if len(sys.argv) > 2: + try: + num_tasks = int(sys.argv[2]) + except: + pass + + print("=" * 70) + print("并行OCR性能对比测试") + print("=" * 70) + print() + print(f"测试图片: {os.path.basename(image_path)}") + print(f"任务数量: {num_tasks}") + print() + + # 获取当前配置信息 + cpu_count = os.cpu_count() or 4 + omp_threads = os.environ.get('OMP_NUM_THREADS', '未设置') + print(f"系统信息:") + print(f" CPU核心数: {cpu_count}") + print(f" OMP_NUM_THREADS: {omp_threads}") + try: + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + print(f" 推荐线程池大小: {optimal_workers}") + except: + pass + print() + print() + + # 测试1: 串行OCR + serial_time = test_serial_ocr(image_path, num_tasks) + + print() + print() + + # 测试2: 并行OCR(优化后) + parallel_time = test_parallel_ocr(image_path, num_tasks) + + print() + print() + + # 测试3: 并行OCR(旧配置) + parallel_old_time = test_parallel_ocr_old_config(image_path, num_tasks) + + # 性能对比总结 + print() + print("=" * 70) + print("性能对比总结") + print("=" * 70) + print() + + if serial_time and parallel_time: + speedup = serial_time / parallel_time + print(f"串行OCR: {serial_time:.0f}ms ({serial_time/1000:.2f}秒)") + print(f"并行OCR: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)") + print(f"性能提升: {speedup:.2f}x ({(1 - parallel_time/serial_time)*100:.1f}% 时间减少)") + print() + + if parallel_old_time and parallel_time: + speedup_vs_old = parallel_old_time / parallel_time + print(f"旧配置并行: {parallel_old_time:.0f}ms ({parallel_old_time/1000:.2f}秒)") + print(f"新配置并行: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)") + print(f"配置优化提升: {speedup_vs_old:.2f}x ({(1 - parallel_time/parallel_old_time)*100:.1f}% 时间减少)") + print() + + if serial_time and parallel_time and parallel_old_time: + total_speedup = serial_time / parallel_time + print(f"总体优化效果:") + print(f" 串行 → 并行: {serial_time/parallel_time:.2f}x") + print(f" 旧配置 → 新配置: {parallel_old_time/parallel_time:.2f}x") + print(f" 串行 → 新配置: {total_speedup:.2f}x") + print() + + print("=" * 70) + print("测试完成") + print("=" * 70) + +if __name__ == "__main__": + main() + diff --git a/test_parallel_ocr_quick.py b/test_parallel_ocr_quick.py new file mode 100644 index 0000000..8382233 --- /dev/null +++ b/test_parallel_ocr_quick.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +快速测试并行OCR性能(只测试并行,不测试串行) +""" + +import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from PIL import Image +import numpy as np + +def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3): + """快速测试并行OCR""" + print("=" * 70) + print("并行OCR性能测试(快速版)") + print("=" * 70) + print() + + # 检查文件 + if not os.path.exists(image_path): + print(f"[ERROR] 图片文件不存在: {image_path}") + return None + + # 加载图片 + try: + img = Image.open(image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + img_np = np.array(img) + print(f"图片: {os.path.basename(image_path)}") + print(f"尺寸: {img.size[0]}x{img.size[1]}") + print(f"任务数: {num_tasks}") + print() + except Exception as e: + print(f"[ERROR] 无法加载图片: {e}") + return None + + # 初始化OCR + try: + from operations.ocr_operations import _ocr_processor + _ocr_processor._ensure_ocr() + + if _ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + return None + + print(f"OCR引擎: {_ocr_processor.ocr_type}") + print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}") + + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + print(f"线程池大小: {optimal_workers}") + print() + except Exception as e: + print(f"[ERROR] OCR引擎初始化失败: {e}") + return None + + # 定义OCR任务 + def ocr_task(task_id): + try: + if _ocr_processor.ocr_type == "easyocr": + result = _ocr_processor.ocr.readtext(img_np) + else: + result = _ocr_processor.ocr.ocr(img_np) + + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + return text + except Exception as e: + return f"错误: {e}" + + # 执行并行OCR + print("开始并行OCR测试...") + start_time = time.time() + + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: + futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} + results = [] + + for future in futures: + task_id = futures[future] + try: + result = future.result() + results.append(result) + print(f" 任务 {task_id}: 完成, 结果: {result[:30] if result else '(空)'}") + except Exception as e: + print(f" 任务 {task_id}: 失败 - {e}") + results.append(None) + + total_elapsed = (time.time() - start_time) * 1000 + + print() + print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms") + print() + + # 估算串行时间(基于单次OCR耗时) + print("性能估算:") + print("-" * 70) + single_task_time = total_elapsed / num_tasks + estimated_serial_time = single_task_time * num_tasks + speedup = estimated_serial_time / total_elapsed if total_elapsed > 0 else 0 + + print(f"估算串行时间: {estimated_serial_time:.0f}ms ({estimated_serial_time/1000:.2f}秒)") + print(f"实际并行时间: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + print(f"性能提升: {speedup:.2f}x (节省 {(1 - total_elapsed/estimated_serial_time)*100:.1f}% 时间)") + print() + + return total_elapsed + +def main(): + """主函数""" + default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" + + if len(sys.argv) > 1: + image_path = sys.argv[1] + else: + image_path = default_image + + if not os.path.isabs(image_path): + project_root = os.path.dirname(os.path.abspath(__file__)) + image_path = os.path.join(project_root, image_path) + + num_tasks = 3 + if len(sys.argv) > 2: + try: + num_tasks = int(sys.argv[2]) + except: + pass + + test_parallel_ocr_quick(image_path, num_tasks) + + print("=" * 70) + print("测试完成") + print("=" * 70) + +if __name__ == "__main__": + main() + + diff --git a/test_parallel_ocr_simple.py b/test_parallel_ocr_simple.py new file mode 100644 index 0000000..58bd60a --- /dev/null +++ b/test_parallel_ocr_simple.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +简化版并行OCR性能对比测试 +直接使用提供的图片进行测试 +""" + +import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from PIL import Image +import numpy as np + +def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_tasks=6): + """使用指定配置测试OCR""" + print(f"\n{'='*70}") + print(f"{config_name}") + print(f"{'='*70}") + print(f"OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}, 任务数={num_tasks}") + print() + + # 设置OMP + old_omp = os.environ.get('OMP_NUM_THREADS', '4') + os.environ['OMP_NUM_THREADS'] = str(omp_threads) + + # 加载图片 + try: + img = Image.open(image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + img_np = np.array(img) + print(f"图片: {os.path.basename(image_path)}") + print(f"尺寸: {img.size[0]}x{img.size[1]} 像素") + print() + except Exception as e: + print(f"[ERROR] 无法加载图片: {e}") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + # 初始化OCR + try: + from operations.ocr_operations import OCRProcessor + ocr_processor = OCRProcessor() + ocr_processor._ensure_ocr() + + if ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + print(f"OCR引擎: {ocr_processor.ocr_type}") + print() + except Exception as e: + print(f"[ERROR] OCR引擎初始化失败: {e}") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + # OCR任务函数 + def ocr_task(task_id): + try: + start = time.time() + if ocr_processor.ocr_type == "easyocr": + result = ocr_processor.ocr.readtext(img_np) + else: + result = ocr_processor.ocr.ocr(img_np) + + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + elapsed = (time.time() - start) * 1000 + return {'task_id': task_id, 'text': text, 'time': elapsed, 'success': True} + except Exception as e: + return {'task_id': task_id, 'text': '', 'time': 0, 'success': False, 'error': str(e)} + + # 执行并行OCR + print("开始并行OCR测试...") + start_time = time.time() + results = [] + + with ThreadPoolExecutor(max_workers=max_workers) as executor: + futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} + + for future in futures: + try: + result = future.result() + results.append(result) + status = "✓" if result['success'] else "✗" + print(f" {status} 任务{result['task_id']}: {result['time']:.0f}ms, 结果: {result['text'][:20] if result['text'] else '(空)'}") + except Exception as e: + print(f" ✗ 任务失败: {e}") + + total_elapsed = (time.time() - start_time) * 1000 + + # 恢复OMP设置 + os.environ['OMP_NUM_THREADS'] = old_omp + + # 统计 + successful = [r for r in results if r['success']] + total_task_time = sum(r['time'] for r in successful) + avg_task_time = total_task_time / len(successful) if successful else 0 + + print() + print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + print(f"任务总耗时: {total_task_time:.0f}ms") + print(f"平均每个任务: {avg_task_time:.0f}ms") + if total_task_time > 0: + efficiency = total_task_time / total_elapsed + print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)") + print() + + return { + 'total_time': total_elapsed, + 'avg_task_time': avg_task_time, + 'config': config_name + } + +def main(): + """主函数""" + default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" + + if len(sys.argv) > 1: + image_path = sys.argv[1] + else: + image_path = default_image + + if not os.path.isabs(image_path): + project_root = os.path.dirname(os.path.abspath(__file__)) + image_path = os.path.join(project_root, image_path) + + if not os.path.exists(image_path): + print(f"[ERROR] 图片文件不存在: {image_path}") + return + + print("=" * 70) + print("并行OCR性能对比测试(简化版)") + print("=" * 70) + print() + print(f"测试图片: {os.path.basename(image_path)}") + + # 获取系统信息 + cpu_count = os.cpu_count() or 4 + print(f"CPU核心数: {cpu_count}") + try: + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + print(f"推荐线程池大小: {optimal_workers}") + except: + optimal_workers = 6 + + num_tasks = 6 + print(f"测试任务数: {num_tasks}") + print() + + # 测试1: 优化前 + result_old = test_ocr_with_config( + image_path, + "优化前配置 (OMP=1, workers=6)", + omp_threads=1, + max_workers=6, + num_tasks=num_tasks + ) + + time.sleep(1) # 等待系统稳定 + + # 测试2: 优化后 + result_new = test_ocr_with_config( + image_path, + "优化后配置 (OMP=4, workers=10)", + omp_threads=4, + max_workers=optimal_workers, + num_tasks=num_tasks + ) + + # 对比结果 + print() + print("=" * 70) + print("性能对比总结") + print("=" * 70) + print() + + if result_old and result_new: + old_time = result_old['total_time'] + new_time = result_new['total_time'] + speedup = old_time / new_time if new_time > 0 else 0 + + print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)") + print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)") + print(f"性能提升: {speedup:.2f}x") + print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%") + print() + + old_avg = result_old['avg_task_time'] + new_avg = result_new['avg_task_time'] + print(f"优化前平均任务耗时: {old_avg:.0f}ms") + print(f"优化后平均任务耗时: {new_avg:.0f}ms") + if new_avg > 0: + print(f"单任务性能提升: {old_avg/new_avg:.2f}x") + + print() + print("=" * 70) + print("测试完成") + print("=" * 70) + +if __name__ == "__main__": + main() + diff --git a/test_real_parallel_ocr.py b/test_real_parallel_ocr.py new file mode 100644 index 0000000..e1844ab --- /dev/null +++ b/test_real_parallel_ocr.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +真实场景并行OCR性能对比测试 +模拟实际使用中的多区域并行OCR识别 +""" + +import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from PIL import Image +import numpy as np +import tempfile + +def create_test_regions(full_image_path): + """从完整截图中创建多个测试区域(模拟真实OCR场景)""" + try: + img = Image.open(full_image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + + width, height = img.size + + # 判断是否是完整截图(1080x2400)还是裁剪区域 + is_full_screenshot = width >= 1000 and height >= 2000 + + if is_full_screenshot: + # 完整截图:创建多个测试区域 + # 模拟真实的OCR区域(基于福袋详情页的常见区域) + regions = { + "福袋倒计时_分钟": (400, 1050, 500, 1150), # 倒计时分钟区域 + "福袋倒计时_秒": (480, 1110, 570, 1230), # 倒计时秒区域(用户提供的区域) + "福袋内容": (50, 800, 500, 1000), # 福袋内容区域 + "福袋价值": (200, 1300, 400, 1400), # 价值区域 + "任务列表": (50, 600, 500, 750), # 任务列表区域 + "参与按钮": (300, 1500, 800, 1600), # 按钮状态区域 + } + else: + # 裁剪区域:使用当前图片作为测试区域之一,创建其他相似大小的区域 + # 从文件名提取坐标信息(如果存在) + coords_from_filename = None + if "(480,1110)-(570,1230)" in full_image_path: + coords_from_filename = (480, 1110, 570, 1230) + + # 创建多个相似大小的测试区域 + # 如果图片较小,创建多个相同大小的区域用于测试 + # 这些区域会在完整截图的合理位置 + regions = {} + + # 使用当前图片作为第一个区域 + if coords_from_filename: + x1, y1, x2, y2 = coords_from_filename + regions["福袋倒计时_秒"] = (x1, y1, x2, y2) + # 创建其他相邻区域 + offset_x = x2 - x1 + offset_y = y2 - y1 + regions["福袋倒计时_分钟"] = (x1 - offset_x - 20, y1, x1 - 20, y2) + regions["福袋内容"] = (x1, y1 - offset_y - 20, x2, y1 - 20) + regions["福袋价值"] = (x1, y2 + 20, x2, y2 + offset_y + 20) + else: + # 如果无法从文件名提取坐标,使用图片本身作为唯一测试区域 + # 创建多个相同大小的区域(通过复制当前图片) + regions["区域1"] = (0, 0, width, height) + regions["区域2"] = (0, 0, width, height) # 相同区域,用于测试并行 + regions["区域3"] = (0, 0, width, height) # 相同区域,用于测试并行 + regions["区域4"] = (0, 0, width, height) # 相同区域,用于测试并行 + regions["区域5"] = (0, 0, width, height) # 相同区域,用于测试并行 + regions["区域6"] = (0, 0, width, height) # 相同区域,用于测试并行 + + # 裁剪并保存区域图片 + region_images = {} + temp_dir = tempfile.gettempdir() + + for name, (x1, y1, x2, y2) in regions.items(): + try: + # 确保坐标在图片范围内 + x1 = max(0, min(x1, img.width)) + y1 = max(0, min(y1, img.height)) + x2 = max(x1, min(x2, img.width)) + y2 = max(y1, min(y2, img.height)) + + if x2 > x1 and y2 > y1: + crop_img = img.crop((x1, y1, x2, y2)) + temp_path = os.path.join(temp_dir, f"ocr_test_{name}.png") + crop_img.save(temp_path) + region_images[name] = { + 'path': temp_path, + 'size': crop_img.size, + 'coords': (x1, y1, x2, y2) + } + except (ValueError, OSError, IOError) as e: + print(f"[WARNING] 无法裁剪区域 {name}: {e}") + + return region_images, img.size + except (OSError, IOError, ValueError) as e: + print(f"[ERROR] 无法处理图片: {e}") + return {}, None + +def ocr_single_region(image_path, region_name, ocr_processor): + """对单个区域进行OCR识别""" + try: + img = Image.open(image_path) + if img.mode != 'RGB': + img = img.convert('RGB') + img_np = np.array(img) + + start_time = time.time() + + if ocr_processor.ocr_type == "easyocr": + result = ocr_processor.ocr.readtext(img_np) + else: + result = ocr_processor.ocr.ocr(img_np) + + elapsed = (time.time() - start_time) * 1000 + + # 提取文本 + from Underlying_Operations import underlying_operations + ops = underlying_operations() + text = ops.extract_ocr_content(result) + + return { + 'region': region_name, + 'text': text, + 'time': elapsed, + 'success': True + } + except (OSError, IOError, ValueError, AttributeError) as e: + return { + 'region': region_name, + 'text': '', + 'time': 0, + 'success': False, + 'error': str(e) + } + +def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers): + """测试真实场景的并行OCR""" + print(f"\n{'='*70}") + print(f"测试: {config_name}") + print(f"{'='*70}") + print(f"配置: OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}") + print(f"区域数量: {len(region_images)}") + print() + + # 设置OMP线程数 + old_omp = os.environ.get('OMP_NUM_THREADS', '4') + os.environ['OMP_NUM_THREADS'] = str(omp_threads) + + # 初始化OCR(使用新的OMP设置) + try: + from operations.ocr_operations import OCRProcessor + ocr_processor = OCRProcessor() + # 访问受保护方法以初始化OCR引擎(测试代码中需要) + # 使用 getattr 来避免 pylance 警告 + ensure_ocr = getattr(ocr_processor, '_ensure_ocr') + ensure_ocr() + + if ocr_processor.ocr is None: + print("[ERROR] OCR引擎未初始化") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + print(f"OCR引擎: {ocr_processor.ocr_type}") + print() + except (ImportError, AttributeError, RuntimeError) as e: + print(f"[ERROR] OCR引擎初始化失败: {e}") + os.environ['OMP_NUM_THREADS'] = old_omp + return None + + # 显示区域信息 + print("OCR区域信息:") + for name, info in region_images.items(): + print(f" {name}: {info['size'][0]}x{info['size'][1]} 像素, 坐标: {info['coords']}") + print() + + # 并行执行OCR + print("开始并行OCR识别...") + start_time = time.time() + results = [] + + def ocr_task(name, path): + return ocr_single_region(path, name, ocr_processor) + + with ThreadPoolExecutor(max_workers=max_workers) as executor: + # 提交所有任务 + futures = { + executor.submit(ocr_task, name, info['path']): name + for name, info in region_images.items() + } + + # 收集结果 + for future in futures: + region_name = futures[future] + try: + result = future.result() + results.append(result) + status = "✓" if result['success'] else "✗" + print(f" {status} {region_name}: {result['time']:.0f}ms, 结果: {result['text'][:30] if result['text'] else '(空)'}") + except (RuntimeError, AttributeError, KeyError) as e: + print(f" ✗ {region_name}: 失败 - {e}") + results.append({ + 'region': region_name, + 'text': '', + 'time': 0, + 'success': False, + 'error': str(e) + }) + + total_elapsed = (time.time() - start_time) * 1000 + + # 恢复OMP设置 + os.environ['OMP_NUM_THREADS'] = old_omp + + # 统计结果 + successful_results = [r for r in results if r['success']] + total_task_time = sum(r['time'] for r in successful_results) + avg_task_time = total_task_time / len(successful_results) if successful_results else 0 + + print() + print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") + print(f"任务总耗时: {total_task_time:.0f}ms") + print(f"平均每个任务: {avg_task_time:.0f}ms") + if total_task_time > 0: + efficiency = total_task_time / total_elapsed + print(f"并行效率: {efficiency:.2f}x (理想值: {len(region_images):.1f}x)") + print() + + return { + 'total_time': total_elapsed, + 'task_times': [r['time'] for r in successful_results], + 'results': results, + 'config': config_name + } + +def main(): + """主函数""" + # 默认图片路径(完整截图) + default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" + + if len(sys.argv) > 1: + image_path = sys.argv[1] + else: + image_path = default_image + + if not os.path.isabs(image_path): + project_root = os.path.dirname(os.path.abspath(__file__)) + image_path = os.path.join(project_root, image_path) + + if not os.path.exists(image_path): + print(f"[ERROR] 图片文件不存在: {image_path}") + return + + print("=" * 70) + print("真实场景并行OCR性能对比测试") + print("=" * 70) + print() + print(f"测试图片: {os.path.basename(image_path)}") + print() + + # 创建测试区域 + print("准备测试区域...") + region_images, full_size = create_test_regions(image_path) + + if not region_images: + print("[ERROR] 无法创建测试区域") + return + + if full_size is not None: + print(f"完整截图尺寸: {full_size[0]}x{full_size[1]}") + else: + print("完整截图尺寸: 未知") + print(f"成功创建 {len(region_images)} 个测试区域") + print() + + # 获取系统信息 + cpu_count = os.cpu_count() or 4 + print("系统信息:") + print(f" CPU核心数: {cpu_count}") + try: + from operations.screenshot_service import get_optimal_workers + optimal_workers = get_optimal_workers() + print(f" 推荐线程池大小: {optimal_workers}") + except (ImportError, AttributeError): + optimal_workers = 6 + print() + + # 测试1: 优化前配置(OMP=1, workers=6) + result_old = test_parallel_ocr_real( + region_images, + "优化前配置", + omp_threads=1, + max_workers=6 + ) + + # 等待一下,让系统稳定 + time.sleep(1) + + # 测试2: 优化后配置(OMP=4, workers=10) + result_new = test_parallel_ocr_real( + region_images, + "优化后配置", + omp_threads=4, + max_workers=optimal_workers + ) + + # 性能对比总结 + print() + print("=" * 70) + print("性能对比总结") + print("=" * 70) + print() + + if result_old and result_new: + old_time = result_old['total_time'] + new_time = result_new['total_time'] + speedup = old_time / new_time if new_time > 0 else 0 + + print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)") + print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)") + print(f"性能提升: {speedup:.2f}x") + print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%") + print() + + # 详细对比 + if result_old['task_times'] and result_new['task_times']: + old_avg = sum(result_old['task_times']) / len(result_old['task_times']) + new_avg = sum(result_new['task_times']) / len(result_new['task_times']) + + print("任务级性能对比:") + print(f" 优化前平均任务耗时: {old_avg:.0f}ms") + print(f" 优化后平均任务耗时: {new_avg:.0f}ms") + print(f" 单任务性能提升: {old_avg/new_avg:.2f}x") + print() + + # 识别结果对比 + print("识别结果对比:") + for old_result in result_old['results']: + region_name = old_result['region'] + new_result = next((r for r in result_new['results'] if r['region'] == region_name), None) + + if old_result['success'] and new_result and new_result['success']: + old_text = old_result['text'][:20] if old_result['text'] else '(空)' + new_text = new_result['text'][:20] if new_result['text'] else '(空)' + match = "✓" if old_text == new_text else "✗" + print(f" {match} {region_name}: 结果一致") + + # 清理临时文件 + print() + print("清理临时文件...") + for info in region_images.values(): + try: + if os.path.exists(info['path']): + os.remove(info['path']) + except (OSError, PermissionError): + pass + + print() + print("=" * 70) + print("测试完成") + print("=" * 70) + +if __name__ == "__main__": + main() + diff --git a/tools/README_Region_Selector.md b/tools/README_Region_Selector.md index 6ec3ea4..06bd450 100644 --- a/tools/README_Region_Selector.md +++ b/tools/README_Region_Selector.md @@ -128,3 +128,9 @@ python region_selector.py path/to/image.png + + + + + + diff --git a/tools/analyze_optimization_effect.py b/tools/analyze_optimization_effect.py index dcce3df..2778e4a 100644 --- a/tools/analyze_optimization_effect.py +++ b/tools/analyze_optimization_effect.py @@ -134,3 +134,9 @@ if __name__ == '__main__': + + + + + + diff --git a/tools/analyze_screenshot_logs.py b/tools/analyze_screenshot_logs.py index 32fb611..0ef3e1b 100644 --- a/tools/analyze_screenshot_logs.py +++ b/tools/analyze_screenshot_logs.py @@ -134,3 +134,9 @@ if __name__ == '__main__': + + + + + + diff --git a/tools/check_screenshot_optimization.py b/tools/check_screenshot_optimization.py index 82a27ed..f6e92ed 100644 --- a/tools/check_screenshot_optimization.py +++ b/tools/check_screenshot_optimization.py @@ -285,3 +285,9 @@ if __name__ == '__main__': + + + + + + diff --git a/tools/check_system_config.py b/tools/check_system_config.py index 6660fc8..f4e3d69 100644 --- a/tools/check_system_config.py +++ b/tools/check_system_config.py @@ -295,3 +295,9 @@ if __name__ == '__main__': + + + + + + diff --git a/x_template_lab.py b/x_template_lab.py deleted file mode 100644 index 975274e..0000000 --- a/x_template_lab.py +++ /dev/null @@ -1,550 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -x图标模板匹配阈值优化测试脚本 -测试不同阈值参数对模板匹配结果的影响 -""" - -import sys -import os -import cv2 -import numpy as np -from pathlib import Path -import glob -from collections import defaultdict - -# 设置UTF-8编码 -if sys.platform == 'win32': - sys.stdout.reconfigure(encoding='utf-8') - -# 测试图片路径(自动扫描debug_captures文件夹) -DEBUG_CAPTURES_DIR = r"pic/debug_captures" -TEMPLATE_PATH = r"assets/x.png" - -# ROI坐标(基于1080x2400分辨率) -ROI_X1, ROI_Y1 = 972, 147 -ROI_X2, ROI_Y2 = 1047, 216 - -def load_image(image_path): - """加载图片(支持中文路径)""" - if not os.path.exists(image_path): - raise FileNotFoundError(f"图片不存在: {image_path}") - - # 使用numpy读取,支持中文路径 - img_array = np.fromfile(image_path, dtype=np.uint8) - img = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE) - if img is None: - raise ValueError(f"无法读取图片: {image_path}") - return img - -def crop_roi(img, x1, y1, x2, y2): - """裁剪ROI区域""" - h, w = img.shape[:2] - # 如果图片尺寸不是1080x2400,需要缩放坐标 - if w != 1080 or h != 2400: - scale_x = w / 1080.0 - scale_y = h / 2400.0 - x1 = int(x1 * scale_x) - y1 = int(y1 * scale_y) - x2 = int(x2 * scale_x) - y2 = int(y2 * scale_y) - - roi = img[y1:y2, x1:x2] - return roi - -def test_fixed_threshold_binary(roi_img, template, threshold_values): - """测试固定阈值二值化的不同阈值""" - results = [] - for thresh in threshold_values: - try: - _, roi_bin = cv2.threshold(roi_img, thresh, 255, cv2.THRESH_BINARY) - _, tpl_bin = cv2.threshold(template, thresh, 255, cv2.THRESH_BINARY) - - # 确保模板尺寸匹配 - th, tw = tpl_bin.shape[:2] - rh, rw = roi_bin.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("固定阈值二值化", thresh, float(max_val or 0.0))) - except Exception as e: - results.append(("固定阈值二值化", thresh, 0.0)) - return results - -def test_adaptive_threshold(roi_img, template, block_sizes, c_values): - """测试自适应二值化的不同参数""" - results = [] - for block_size in block_sizes: - for c in c_values: - try: - roi_bin = cv2.adaptiveThreshold( - roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, - cv2.THRESH_BINARY, block_size, c - ) - tpl_bin = cv2.adaptiveThreshold( - template, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, - cv2.THRESH_BINARY, block_size, c - ) - - # 确保模板尺寸匹配 - th, tw = tpl_bin.shape[:2] - rh, rw = roi_bin.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("自适应二值化", f"blockSize={block_size}, C={c}", float(max_val or 0.0))) - except Exception as e: - results.append(("自适应二值化", f"blockSize={block_size}, C={c}", 0.0)) - return results - -def test_canny_edges(roi_img, template, low_thresholds, high_thresholds): - """测试Canny边缘检测的不同阈值组合""" - results = [] - for low in low_thresholds: - for high in high_thresholds: - if high <= low: - continue - try: - roi_edges = cv2.Canny(roi_img, low, high) - tpl_edges = cv2.Canny(template, low, high) - - # 确保模板尺寸匹配 - th, tw = tpl_edges.shape[:2] - rh, rw = roi_edges.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_edges = cv2.resize(tpl_edges, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_edges, tpl_edges, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("Canny边缘检测", f"low={low}, high={high}", float(max_val or 0.0))) - except Exception as e: - results.append(("Canny边缘检测", f"low={low}, high={high}", 0.0)) - return results - -def test_template_methods(roi_img, template, method_name="固定阈值二值化", thresh=180): - """测试不同的模板匹配方法""" - # 预处理 - _, roi_bin = cv2.threshold(roi_img, thresh, 255, cv2.THRESH_BINARY) - _, tpl_bin = cv2.threshold(template, thresh, 255, cv2.THRESH_BINARY) - - # 确保模板尺寸匹配 - th, tw = tpl_bin.shape[:2] - rh, rw = roi_bin.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - methods = [ - ("TM_CCOEFF_NORMED", cv2.TM_CCOEFF_NORMED), - ("TM_CCORR_NORMED", cv2.TM_CCORR_NORMED), - ("TM_SQDIFF_NORMED", cv2.TM_SQDIFF_NORMED), - ] - - results = [] - for name, method in methods: - try: - res = cv2.matchTemplate(roi_bin, tpl_bin, method) - if method == cv2.TM_SQDIFF_NORMED: - _min_val, _max_val, min_loc, _max_loc = cv2.minMaxLoc(res) - score = 1.0 - float(_min_val or 0.0) # SQDIFF越小越好,转换为越大越好 - else: - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - score = float(max_val or 0.0) - results.append((name, score)) - except Exception as e: - results.append((name, 0.0)) - return results - -def test_advanced_preprocessing(roi_img, template): - """测试高级预处理方法""" - results = [] - - # 1. 反转图像 + 二值化 - try: - roi_inv = 255 - roi_img - tpl_inv = 255 - template - _, roi_bin_inv = cv2.threshold(roi_inv, 180, 255, cv2.THRESH_BINARY) - _, tpl_bin_inv = cv2.threshold(tpl_inv, 180, 255, cv2.THRESH_BINARY) - - th, tw = tpl_bin_inv.shape[:2] - rh, rw = roi_bin_inv.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_bin_inv = cv2.resize(tpl_bin_inv, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_bin_inv, tpl_bin_inv, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("反转+二值化", "thresh=180", float(max_val or 0.0))) - except Exception: - results.append(("反转+二值化", "thresh=180", 0.0)) - - # 2. 直方图均衡化 - try: - roi_eq = cv2.equalizeHist(roi_img) - tpl_eq = cv2.equalizeHist(template) - - th, tw = tpl_eq.shape[:2] - rh, rw = roi_eq.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_eq = cv2.resize(tpl_eq, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_eq, tpl_eq, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("直方图均衡化", "", float(max_val or 0.0))) - except Exception: - results.append(("直方图均衡化", "", 0.0)) - - # 3. 对比度增强(CLAHE) - try: - clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) - roi_clahe = clahe.apply(roi_img) - tpl_clahe = clahe.apply(template) - - th, tw = tpl_clahe.shape[:2] - rh, rw = roi_clahe.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_clahe = cv2.resize(tpl_clahe, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_clahe, tpl_clahe, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("CLAHE对比度增强", "clipLimit=2.0", float(max_val or 0.0))) - except Exception: - results.append(("CLAHE对比度增强", "clipLimit=2.0", 0.0)) - - # 4. 高斯模糊 + 边缘检测 - try: - roi_blur = cv2.GaussianBlur(roi_img, (3, 3), 0) - tpl_blur = cv2.GaussianBlur(template, (3, 3), 0) - roi_edges = cv2.Canny(roi_blur, 50, 150) - tpl_edges = cv2.Canny(tpl_blur, 50, 150) - - th, tw = tpl_edges.shape[:2] - rh, rw = roi_edges.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_edges = cv2.resize(tpl_edges, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_edges, tpl_edges, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("高斯模糊+边缘检测", "blur(3,3), canny(50,150)", float(max_val or 0.0))) - except Exception: - results.append(("高斯模糊+边缘检测", "blur(3,3), canny(50,150)", 0.0)) - - # 5. 形态学操作(开运算) - try: - _, roi_bin = cv2.threshold(roi_img, 180, 255, cv2.THRESH_BINARY) - _, tpl_bin = cv2.threshold(template, 180, 255, cv2.THRESH_BINARY) - kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) - roi_morph = cv2.morphologyEx(roi_bin, cv2.MORPH_OPEN, kernel) - tpl_morph = cv2.morphologyEx(tpl_bin, cv2.MORPH_OPEN, kernel) - - th, tw = tpl_morph.shape[:2] - rh, rw = roi_morph.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_morph = cv2.resize(tpl_morph, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_morph, tpl_morph, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("形态学开运算", "kernel(3,3)", float(max_val or 0.0))) - except Exception: - results.append(("形态学开运算", "kernel(3,3)", 0.0)) - - # 6. 形态学操作(闭运算) - try: - _, roi_bin = cv2.threshold(roi_img, 180, 255, cv2.THRESH_BINARY) - _, tpl_bin = cv2.threshold(template, 180, 255, cv2.THRESH_BINARY) - kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) - roi_morph = cv2.morphologyEx(roi_bin, cv2.MORPH_CLOSE, kernel) - tpl_morph = cv2.morphologyEx(tpl_bin, cv2.MORPH_CLOSE, kernel) - - th, tw = tpl_morph.shape[:2] - rh, rw = roi_morph.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - tpl_morph = cv2.resize(tpl_morph, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - res = cv2.matchTemplate(roi_morph, tpl_morph, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("形态学闭运算", "kernel(3,3)", float(max_val or 0.0))) - except Exception: - results.append(("形态学闭运算", "kernel(3,3)", 0.0)) - - # 7. 原始图像(作为基准) - try: - th, tw = template.shape[:2] - rh, rw = roi_img.shape[:2] - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - template_scaled = cv2.resize(template, (max(1, int(tw * scale)), max(1, int(th * scale)))) - else: - template_scaled = template - - res = cv2.matchTemplate(roi_img, template_scaled, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results.append(("原始图像", "", float(max_val or 0.0))) - except Exception: - results.append(("原始图像", "", 0.0)) - - return results - -def find_test_images(): - """查找所有直播间图标测试图片""" - pattern = os.path.join(DEBUG_CAPTURES_DIR, "**", "*直播间图标*.png") - images = glob.glob(pattern, recursive=True) - return images - -def test_single_image(image_path, template): - """测试单张图片的所有方法,返回结果字典""" - results = {} - - try: - # 加载图片 - test_img = load_image(image_path) - - # 裁剪ROI - roi_img = crop_roi(test_img, ROI_X1, ROI_Y1, ROI_X2, ROI_Y2) - - # 确保模板尺寸匹配 - th, tw = template.shape[:2] - rh, rw = roi_img.shape[:2] - template_scaled = template.copy() - if th > rh or tw > rw: - scale = min(rh / max(th, 1), rw / max(tw, 1)) - template_scaled = cv2.resize(template_scaled, (max(1, int(tw * scale)), max(1, int(th * scale)))) - - # 1. 测试固定阈值二值化 - threshold_values = list(range(100, 250, 10)) - for thresh in threshold_values: - try: - _, roi_bin = cv2.threshold(roi_img, thresh, 255, cv2.THRESH_BINARY) - _, tpl_bin = cv2.threshold(template_scaled, thresh, 255, cv2.THRESH_BINARY) - - th_t, tw_t = tpl_bin.shape[:2] - rh_t, rw_t = roi_bin.shape[:2] - if th_t > rh_t or tw_t > rw_t: - scale = min(rh_t / max(th_t, 1), rw_t / max(tw_t, 1)) - tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw_t * scale)), max(1, int(th_t * scale)))) - - res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - key = f"固定阈值二值化_{thresh}" - results[key] = float(max_val or 0.0) - except: - results[f"固定阈值二值化_{thresh}"] = 0.0 - - # 2. 测试自适应二值化 - block_sizes = [3, 5, 7, 9, 11, 15] - c_values = [0, 1, 2, 3, 5] - for block_size in block_sizes: - for c in c_values: - try: - roi_bin = cv2.adaptiveThreshold( - roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, - cv2.THRESH_BINARY, block_size, c - ) - tpl_bin = cv2.adaptiveThreshold( - template_scaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, - cv2.THRESH_BINARY, block_size, c - ) - - th_t, tw_t = tpl_bin.shape[:2] - rh_t, rw_t = roi_bin.shape[:2] - if th_t > rh_t or tw_t > rw_t: - scale = min(rh_t / max(th_t, 1), rw_t / max(tw_t, 1)) - tpl_bin = cv2.resize(tpl_bin, (max(1, int(tw_t * scale)), max(1, int(th_t * scale)))) - - res = cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - key = f"自适应二值化_bs{block_size}_c{c}" - results[key] = float(max_val or 0.0) - except: - results[f"自适应二值化_bs{block_size}_c{c}"] = 0.0 - - # 3. 测试Canny边缘检测 - low_thresholds = [20, 30, 40, 50, 60] - high_thresholds = [60, 80, 100, 120, 150, 180] - for low in low_thresholds: - for high in high_thresholds: - if high <= low: - continue - try: - roi_edges = cv2.Canny(roi_img, low, high) - tpl_edges = cv2.Canny(template_scaled, low, high) - - th_t, tw_t = tpl_edges.shape[:2] - rh_t, rw_t = roi_edges.shape[:2] - if th_t > rh_t or tw_t > rw_t: - scale = min(rh_t / max(th_t, 1), rw_t / max(tw_t, 1)) - tpl_edges = cv2.resize(tpl_edges, (max(1, int(tw_t * scale)), max(1, int(th_t * scale)))) - - res = cv2.matchTemplate(roi_edges, tpl_edges, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - key = f"Canny边缘检测_low{low}_high{high}" - results[key] = float(max_val or 0.0) - except: - results[f"Canny边缘检测_low{low}_high{high}"] = 0.0 - - # 4. 测试高级预处理方法 - advanced_results = test_advanced_preprocessing(roi_img, template_scaled) - for method, params, score in advanced_results: - key = f"{method}_{params}" if params else method - results[key] = score - - # 5. 测试原始图像 - try: - res = cv2.matchTemplate(roi_img, template_scaled, cv2.TM_CCOEFF_NORMED) - _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) - results["原始图像"] = float(max_val or 0.0) - except: - results["原始图像"] = 0.0 - - except Exception as e: - print(f" 处理图片失败: {os.path.basename(image_path)} - {e}") - return {} - - return results - -def main(): - print("=" * 80) - print("x图标模板匹配阈值优化测试(多图片批量测试)") - print("=" * 80) - print() - - # 查找所有测试图片 - print(f"扫描测试图片目录: {DEBUG_CAPTURES_DIR}") - test_images = find_test_images() - print(f"找到 {len(test_images)} 张直播间图标图片") - - if len(test_images) == 0: - print("未找到测试图片!") - return - - # 加载模板 - print(f"\n加载模板: {TEMPLATE_PATH}") - try: - template = load_image(TEMPLATE_PATH) - print(f" 模板尺寸: {template.shape[1]}x{template.shape[0]}") - except Exception as e: - print(f" 错误: {e}") - return - - print("\n" + "=" * 80) - print("开始批量测试...") - print("=" * 80) - - # 统计所有方法在所有图片上的分数 - method_scores = defaultdict(list) # {method_name: [score1, score2, ...]} - - # 测试每张图片 - for i, image_path in enumerate(test_images, 1): - print(f"\n[{i}/{len(test_images)}] 测试: {os.path.basename(image_path)}") - results = test_single_image(image_path, template) - - # 收集分数 - for method, score in results.items(): - method_scores[method].append(score) - - # 计算平均分数 - print("\n" + "=" * 80) - print("【统计结果】所有方法的平均分数") - print("=" * 80) - - avg_scores = [] - for method, scores in method_scores.items(): - avg_score = sum(scores) / len(scores) if scores else 0.0 - max_score = max(scores) if scores else 0.0 - min_score = min(scores) if scores else 0.0 - avg_scores.append((method, avg_score, max_score, min_score, len(scores))) - - # 按平均分数排序 - avg_scores.sort(key=lambda x: x[1], reverse=True) - - print(f"{'排名':<6} {'方法':<35} {'平均分':<10} {'最高分':<10} {'最低分':<10} {'图片数':<8} {'状态':<10}") - print("-" * 100) - - for i, (method, avg_score, max_score, min_score, count) in enumerate(avg_scores[:30], 1): # 显示前30名 - status = "✓ 通过" if avg_score >= 0.72 else "✗ 未通过" - print(f"{i:<6} {method:<35} {avg_score:<10.4f} {max_score:<10.4f} {min_score:<10.4f} {count:<8} {status:<10}") - - # 推荐配置 - print("\n" + "=" * 80) - print("【推荐配置】") - print("=" * 80) - if avg_scores: - best_method, best_avg, best_max, best_min, best_count = avg_scores[0] - print(f"最佳方法: {best_method}") - print(f"平均分数: {best_avg:.4f}") - print(f"最高分数: {best_max:.4f}") - print(f"最低分数: {best_min:.4f}") - print(f"测试图片数: {best_count}") - print(f"是否通过阈值(0.72): {'是' if best_avg >= 0.72 else '否'}") - - # 解析最佳方法参数 - if "固定阈值二值化" in best_method: - thresh = best_method.split("_")[-1] - print(f"\n推荐配置:") - print(f" 方法: 固定阈值二值化") - print(f" 阈值: {thresh}") - print(f" 模板匹配方法: TM_CCOEFF_NORMED") - elif "自适应二值化" in best_method: - parts = best_method.split("_") - bs = parts[1].replace("bs", "") - c = parts[2].replace("c", "") - print(f"\n推荐配置:") - print(f" 方法: 自适应二值化") - print(f" blockSize: {bs}") - print(f" C: {c}") - print(f" 模板匹配方法: TM_CCOEFF_NORMED") - elif "Canny边缘检测" in best_method: - parts = best_method.split("_") - low = parts[1].replace("low", "") - high = parts[2].replace("high", "") - print(f"\n推荐配置:") - print(f" 方法: Canny边缘检测") - print(f" low: {low}") - print(f" high: {high}") - print(f" 模板匹配方法: TM_CCOEFF_NORMED") - else: - print(f"\n推荐配置:") - print(f" 方法: {best_method}") - print(f" 模板匹配方法: TM_CCOEFF_NORMED") - - print("\n测试完成!") - -if __name__ == "__main__": - main() -""" -x图标模板匹配阈值优化测试脚本 -测试不同阈值参数对模板匹配结果的影响 -""" - -import sys -import os -import cv2 -import numpy as np -from pathlib import Path -import glob -from collections import defaultdict - -# 设置UTF-8编码 -if sys.platform == 'win32': - sys.stdout.reconfigure(encoding='utf-8') - -# 测试图片路径(自动扫描debug_captures文件夹) -DEBUG_CAPTURES_DIR = r"pic/debug_captures" -TEMPLATE_PATH = r"assets/x.png" - -# ROI坐标(基于1080x2400分辨率) -ROI_X1, ROI_Y1 = 972, 147 -ROI_X2, ROI_Y2 = 1047, 216 -