feat: 添加工具以查找重复的异常处理,增强代码质量检查;新增验证 GUI 回退方式的自检脚本
This commit is contained in:
1 parent
982357927e
commit
43e39f4db6
16 files changed
+472
-180
No files matched your search
+53
-45
@@ -14,10 +14,13 @@ os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||||
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
|
||||
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
|
||||
|
||||
import time
|
||||
from PIL import Image, ImageFilter
|
||||
from PIL import UnidentifiedImageError
|
||||
import numpy as np
|
||||
import time as time_module
|
||||
|
||||
# alias for existing code that uses `time` name
|
||||
time = time_module
|
||||
from PIL import Image, ImageFilter # type: ignore[import]
|
||||
from PIL import UnidentifiedImageError # type: ignore[import]
|
||||
import numpy as np # type: ignore[import]
|
||||
import logging
|
||||
import re
|
||||
import random
|
||||
@@ -27,7 +30,6 @@ import contextlib
|
||||
|
||||
import base64
|
||||
from typing import Tuple, Optional, Any
|
||||
import time as time_module
|
||||
|
||||
# Pillow 版本兼容:使用 Image.Resampling 或回退到 Image 常量
|
||||
try:
|
||||
@@ -495,7 +497,7 @@ class underlying_operations:
|
||||
返回:
|
||||
是否成功获取截图
|
||||
"""
|
||||
start_ts = time.time()
|
||||
start_ts = time_module.time()
|
||||
# 如果启用服务模式,使用后台截图服务;若服务不可用或返回 False,则回退到直接截图
|
||||
if use_service:
|
||||
try:
|
||||
@@ -521,7 +523,7 @@ class underlying_operations:
|
||||
try:
|
||||
service_result = service.get_screenshot(device_id, force=False)
|
||||
if service_result:
|
||||
dur = (time.time() - start_ts) * 1000.0
|
||||
dur = (time_module.time() - start_ts) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id
|
||||
)
|
||||
@@ -555,7 +557,7 @@ class underlying_operations:
|
||||
|
||||
# 原有的直接截图逻辑(保持向后兼容),测量其耗时
|
||||
result = self._get_screenshot_direct(device_id, path)
|
||||
dur = (time.time() - start_ts) * 1000.0
|
||||
dur = (time_module.time() - start_ts) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s",
|
||||
dur,
|
||||
@@ -1405,9 +1407,9 @@ class underlying_operations:
|
||||
if change_color in (1, 2):
|
||||
img = img.convert("L")
|
||||
if change_color == 1:
|
||||
img = img.point(lambda x: 0 if x < 128 else 255)
|
||||
img = img.point(lambda x: 0 if int(x) < 128 else 255)
|
||||
else:
|
||||
img = img.point(lambda x: 0 if x < 180 else 255)
|
||||
img = img.point(lambda x: 0 if int(x) < 180 else 255)
|
||||
img = img.convert("RGB")
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
@@ -1680,18 +1682,21 @@ class underlying_operations:
|
||||
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
|
||||
try:
|
||||
logging.info(
|
||||
f"[OCR置信度] {picname}: "
|
||||
f"平均={ocr_confidence_info.get('avg_confidence', 0.0):.4f}, "
|
||||
f"最小={ocr_confidence_info.get('min_confidence', 0.0):.4f}, "
|
||||
f"最大={ocr_confidence_info.get('max_confidence', 0.0):.4f}, "
|
||||
f"项目数={ocr_confidence_info.get('item_count', 0)}"
|
||||
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
|
||||
picname,
|
||||
ocr_confidence_info.get("avg_confidence", 0.0),
|
||||
ocr_confidence_info.get("min_confidence", 0.0),
|
||||
ocr_confidence_info.get("max_confidence", 0.0),
|
||||
int(ocr_confidence_info.get("item_count", 0) or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info(
|
||||
f"[调试图像] OCR结果保存: {debug_path}, 文本: {ocr_result_preview}"
|
||||
"[调试图像] OCR结果保存: %s, 文本: %s",
|
||||
debug_path,
|
||||
ocr_result_preview,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1782,9 +1787,9 @@ class underlying_operations:
|
||||
# 数字识别更适合使用二值化处理
|
||||
img = img.convert("L")
|
||||
if change_color == 1:
|
||||
img = img.point(lambda x: 0 if x < 128 else 255)
|
||||
img = img.point(lambda x: 0 if int(x) < 128 else 255)
|
||||
elif change_color == 2:
|
||||
img = img.point(lambda x: 0 if x < 180 else 255)
|
||||
img = img.point(lambda x: 0 if int(x) < 180 else 255)
|
||||
img = img.convert("RGB")
|
||||
|
||||
w, h = img.size
|
||||
@@ -1959,18 +1964,21 @@ class underlying_operations:
|
||||
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
|
||||
try:
|
||||
logging.info(
|
||||
f"[OCR置信度] {picname}: "
|
||||
f"平均={ocr_confidence_info.get('avg_confidence', 0.0):.4f}, "
|
||||
f"最小={ocr_confidence_info.get('min_confidence', 0.0):.4f}, "
|
||||
f"最大={ocr_confidence_info.get('max_confidence', 0.0):.4f}, "
|
||||
f"项目数={ocr_confidence_info.get('item_count', 0)}"
|
||||
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
|
||||
picname,
|
||||
ocr_confidence_info.get("avg_confidence", 0.0),
|
||||
ocr_confidence_info.get("min_confidence", 0.0),
|
||||
ocr_confidence_info.get("max_confidence", 0.0),
|
||||
int(ocr_confidence_info.get("item_count", 0) or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info(
|
||||
f"[调试图像] OCR数字结果保存: {debug_path}, 数字: {digits_result}"
|
||||
"[调试图像] OCR数字结果保存: %s, 数字: %s",
|
||||
debug_path,
|
||||
digits_result,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -2241,7 +2249,7 @@ class underlying_operations:
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
def delay(self, seconds: float = 1):
|
||||
time.sleep(seconds)
|
||||
time_module.sleep(seconds)
|
||||
|
||||
def random_delay(self, min_seconds=1, max_seconds=100):
|
||||
"""等待随机的时长"""
|
||||
@@ -2467,12 +2475,12 @@ class underlying_operations:
|
||||
# 记录错误但不抛出异常,避免中断主流程
|
||||
error_msg = stderr_text.strip() if stderr_text else "权限不足"
|
||||
print(f"[警告] 滑动操作失败: {error_msg}")
|
||||
print(f"[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
|
||||
print("[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
|
||||
print(
|
||||
f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
|
||||
" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
|
||||
)
|
||||
print(f" 2. 使用已 root 的设备")
|
||||
print(f" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
|
||||
print(" 2. 使用已 root 的设备")
|
||||
print(" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
|
||||
# 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用)
|
||||
except subprocess.TimeoutExpired:
|
||||
print("[警告] 滑动操作超时")
|
||||
@@ -2496,11 +2504,11 @@ class underlying_operations:
|
||||
)
|
||||
|
||||
if "event" not in result.stdout.lower():
|
||||
raise Exception("无法找到触摸设备")
|
||||
raise FileNotFoundError("无法找到触摸设备")
|
||||
|
||||
# 简化实现:直接使用 input 命令的替代参数
|
||||
# 注意:sendevent 需要 root 权限,这里只是尝试
|
||||
raise Exception("sendevent 需要 root 权限,暂不支持")
|
||||
raise PermissionError("sendevent 需要 root 权限,暂不支持")
|
||||
|
||||
def _swipe_with_uiautomator(self, device_id, x1, y1, x2, y2):
|
||||
"""使用 uiautomator 滑动(如果可用)
|
||||
@@ -2524,7 +2532,7 @@ class underlying_operations:
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
raise Exception(
|
||||
raise RuntimeError(
|
||||
f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}"
|
||||
)
|
||||
|
||||
@@ -2555,14 +2563,14 @@ class underlying_operations:
|
||||
# 4. 发送 DOWN -> MOVE -> UP 事件序列
|
||||
|
||||
if "event" not in result.stdout.lower():
|
||||
raise Exception("无法找到触摸设备(需要 root 权限)")
|
||||
raise FileNotFoundError("无法找到触摸设备(需要 root 权限)")
|
||||
|
||||
# 注意:完整的 sendevent 实现非常复杂,需要:
|
||||
# - 设备特定的坐标转换
|
||||
# - 正确的事件序列(SYN_REPORT 等)
|
||||
# - 不同 Android 版本的事件格式可能不同
|
||||
|
||||
raise Exception("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
|
||||
raise PermissionError("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
|
||||
|
||||
def click(self, device_id, x=500, y=500):
|
||||
"""点击坐标位置"""
|
||||
@@ -2907,13 +2915,13 @@ class underlying_operations:
|
||||
success = True
|
||||
|
||||
# 给 IME 一点时间把文本真正“打进”输入框
|
||||
time.sleep(0.35)
|
||||
time_module.sleep(0.35)
|
||||
return success
|
||||
finally:
|
||||
# 尝试恢复原输入法,避免影响手动使用
|
||||
if restore_prev and prev and prev != adb_ime:
|
||||
# 再稍等一下,避免过早切回导致输入丢失
|
||||
time.sleep(0.25)
|
||||
time_module.sleep(0.25)
|
||||
self.restore_ime(device_id, prev)
|
||||
|
||||
def paste_text_at(self, device_id: str, x: int, y: int, text: str) -> bool:
|
||||
@@ -2929,10 +2937,10 @@ class underlying_operations:
|
||||
# 先确保输入框获得焦点
|
||||
try:
|
||||
self.click(device_id, int(x), int(y))
|
||||
time.sleep(0.2)
|
||||
time_module.sleep(0.2)
|
||||
# 有些输入框第一次点不进,补一次轻点
|
||||
self.click(device_id, int(x), int(y))
|
||||
time.sleep(0.15)
|
||||
time_module.sleep(0.15)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -2947,7 +2955,7 @@ class underlying_operations:
|
||||
# 1) 优先:剪贴板 + 粘贴键
|
||||
if self.set_clipboard_text(device_id, t):
|
||||
# 给系统一点时间刷新剪贴板
|
||||
time.sleep(0.15)
|
||||
time_module.sleep(0.15)
|
||||
if self.paste_from_clipboard(device_id):
|
||||
return True
|
||||
|
||||
@@ -3010,7 +3018,7 @@ class underlying_operations:
|
||||
import path_config
|
||||
|
||||
local_path = path_config.get_window_dump_path()
|
||||
start = time.time()
|
||||
start = time_module.time()
|
||||
while True:
|
||||
if self._uiautomator_dump(device_id, local_path):
|
||||
try:
|
||||
@@ -3043,9 +3051,9 @@ class underlying_operations:
|
||||
self.click(device_id, cx, cy)
|
||||
return True
|
||||
|
||||
if time.time() - start >= timeout_seconds:
|
||||
if time_module.time() - start >= timeout_seconds:
|
||||
return False
|
||||
time.sleep(0.2)
|
||||
time_module.sleep(0.2)
|
||||
|
||||
def tap_close_icon(
|
||||
self, device_id: str, screen_width: int = 1080, timeout_seconds: float = 2.0
|
||||
@@ -3063,7 +3071,7 @@ class underlying_operations:
|
||||
import path_config
|
||||
|
||||
local_path = path_config.get_window_dump_path()
|
||||
start = time.time()
|
||||
start = time_module.time()
|
||||
|
||||
def _score(node_attrib: dict, bounds_tuple) -> int:
|
||||
x1, y1, x2, y2 = bounds_tuple
|
||||
@@ -3131,6 +3139,6 @@ class underlying_operations:
|
||||
self.click(device_id, cx, cy)
|
||||
return True
|
||||
|
||||
if time.time() - start >= timeout_seconds:
|
||||
if time_module.time() - start >= timeout_seconds:
|
||||
return False
|
||||
time.sleep(0.2)
|
||||
time_module.sleep(0.2)
|
||||
Reference in new issue
Block a user