underlying_operations: 52 处 print → _uo_log
- 新增模块级 _uo_log(msg, level):与项目其他 print→logger 改造一致的模式, 优先走 logging(带 [OCR]/[截图]/[Underlying]/[警告]/[错误] 前缀),失败兜底 stdout - 替换的内容包括: - OCR 引擎初始化 / 延迟初始化(PaddleOCR / EasyOCR 切换) - exec-out 截图 / 文件替换 / 回退方案的失败日志 - 滑动操作失败 / ADB 输入注入异常 - 中奖截图保存 / OCR 调试输出 - paste_text_at / click 等底层操作的调试输出 - 保留为 stdout: - 设备选择交互(L220-247,含 input() 提示,需要用户在 stdout 看到) - _uo_log helper 自身的最终兜底(L73) 回归:146 .py 全量编译通过;underlying_operations 类与 _LOGGER 加载正确; test_filter_logging / check_web_gui_config_sync 通过。 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
80b35bcb6c
commit
c5c8def884
1 file changed
+76
-52
@@ -50,6 +50,30 @@ from douyin.core.io_utils import (
|
||||
_mirror_screenshot_to_external,
|
||||
)
|
||||
|
||||
# 模块级 logger:原代码用 print 输出 OCR 初始化 / 截图 / 滑动 / 调试日志,统一走 logging。
|
||||
# 保留消息中已有的 [OCR] / [截图] / [Underlying] / [警告] / [错误] 前缀,避免改变历史搜索习惯。
|
||||
# 设备选择交互(含 input())的 CLI 输出仍用 print,因为用户需要在 stdout 看到提示。
|
||||
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
|
||||
|
||||
|
||||
def _uo_log(msg: str, level: str = "INFO") -> None:
|
||||
"""统一底层操作日志出口;失败兜底 stdout。"""
|
||||
try:
|
||||
lv = str(level or "INFO").upper()
|
||||
if lv == "ERROR":
|
||||
_LOGGER.error(str(msg))
|
||||
elif lv == "WARNING":
|
||||
_LOGGER.warning(str(msg))
|
||||
elif lv == "DEBUG":
|
||||
_LOGGER.debug(str(msg))
|
||||
else:
|
||||
_LOGGER.info(str(msg))
|
||||
except Exception:
|
||||
try:
|
||||
print(str(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class underlying_operations:
|
||||
"""底层操作类"""
|
||||
@@ -82,17 +106,17 @@ class underlying_operations:
|
||||
raise ImportError("ocr_operations._build_paddle 不可用")
|
||||
self.ocr = _build_paddle()
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 使用 PaddleOCR v4-mobile(CPU模式)")
|
||||
_uo_log("[OCR] 使用 PaddleOCR v4-mobile(CPU模式)")
|
||||
except Exception as e:
|
||||
print(f"[OCR] PaddleOCR 初始化失败: {e},回退到 EasyOCR")
|
||||
_uo_log(f"[OCR] PaddleOCR 初始化失败: {e},回退到 EasyOCR")
|
||||
try:
|
||||
if _build_easyocr is None:
|
||||
raise ImportError("ocr_operations._build_easyocr 不可用")
|
||||
self.ocr = _build_easyocr()
|
||||
self.ocr_type = "easyocr"
|
||||
print("[OCR] 使用 EasyOCR(CPU模式,回退引擎)")
|
||||
_uo_log("[OCR] 使用 EasyOCR(CPU模式,回退引擎)")
|
||||
except Exception as e2:
|
||||
print(f"[OCR] 所有 OCR 引擎初始化失败: {e2}")
|
||||
_uo_log(f"[OCR] 所有 OCR 引擎初始化失败: {e2}")
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
# 注释掉全局日志禁用,以便查看详细的计时日志
|
||||
@@ -156,19 +180,19 @@ class underlying_operations:
|
||||
raise ImportError("ocr_operations._build_paddle 不可用")
|
||||
self.ocr = _build_paddle()
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR v4-mobile(CPU模式)")
|
||||
_uo_log("[OCR] 延迟初始化:使用 PaddleOCR v4-mobile(CPU模式)")
|
||||
return
|
||||
except Exception as e:
|
||||
print(f"[OCR] 延迟初始化 PaddleOCR 失败: {e},回退 EasyOCR")
|
||||
_uo_log(f"[OCR] 延迟初始化 PaddleOCR 失败: {e},回退 EasyOCR")
|
||||
|
||||
try:
|
||||
if _build_easyocr is None:
|
||||
raise ImportError("ocr_operations._build_easyocr 不可用")
|
||||
self.ocr = _build_easyocr()
|
||||
self.ocr_type = "easyocr"
|
||||
print("[OCR] 延迟初始化:使用 EasyOCR(CPU模式,回退)")
|
||||
_uo_log("[OCR] 延迟初始化:使用 EasyOCR(CPU模式,回退)")
|
||||
except Exception as e:
|
||||
print(f"[OCR] 延迟初始化失败: {e}")
|
||||
_uo_log(f"[OCR] 延迟初始化失败: {e}")
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
|
||||
@@ -755,7 +779,7 @@ class underlying_operations:
|
||||
# 如果快速验证失败,记录诊断信息
|
||||
try:
|
||||
st = os.stat(out_file)
|
||||
print(
|
||||
_uo_log(
|
||||
f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}"
|
||||
)
|
||||
except Exception:
|
||||
@@ -767,7 +791,7 @@ class underlying_operations:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
st = os.stat(tmp_file)
|
||||
print(
|
||||
_uo_log(
|
||||
f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}"
|
||||
)
|
||||
except Exception:
|
||||
@@ -778,7 +802,7 @@ class underlying_operations:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
st = os.stat(tmp_file)
|
||||
print(
|
||||
_uo_log(
|
||||
f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}"
|
||||
)
|
||||
except Exception:
|
||||
@@ -786,7 +810,7 @@ class underlying_operations:
|
||||
# 继续尝试回退方案
|
||||
except subprocess.TimeoutExpired:
|
||||
# 超时异常,记录并继续重试
|
||||
print("[截图] exec-out 超时,尝试重试或回退方案")
|
||||
_uo_log("[截图] exec-out 超时,尝试重试或回退方案")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
@@ -794,7 +818,7 @@ class underlying_operations:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 继续回退/重试
|
||||
print(f"[截图] exec-out 异常:{e}")
|
||||
_uo_log(f"[截图] exec-out 异常:{e}")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
@@ -904,7 +928,7 @@ class underlying_operations:
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
try:
|
||||
if _valid_png(out_file):
|
||||
print(
|
||||
_uo_log(
|
||||
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)"
|
||||
)
|
||||
return True
|
||||
@@ -917,7 +941,7 @@ class underlying_operations:
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
try:
|
||||
if _valid_png(out_file):
|
||||
print(
|
||||
_uo_log(
|
||||
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)"
|
||||
)
|
||||
return True
|
||||
@@ -925,12 +949,12 @@ class underlying_operations:
|
||||
pass
|
||||
else:
|
||||
# 最后兜底:返回True,让调用者知道临时文件存在
|
||||
print(
|
||||
_uo_log(
|
||||
f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}"
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
print(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
|
||||
_uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
|
||||
return True
|
||||
# 文件异常则继续进入更深回退
|
||||
except Exception:
|
||||
@@ -971,7 +995,7 @@ class underlying_operations:
|
||||
def get_current_hour(self):
|
||||
"""获取当前的时间小时数"""
|
||||
time_hour = datetime.now().strftime("%H")
|
||||
print("当前时间{}点".format(time_hour))
|
||||
_uo_log("当前时间{}点".format(time_hour))
|
||||
return int(time_hour)
|
||||
|
||||
def click_confirm(self, device_id):
|
||||
@@ -982,7 +1006,7 @@ class underlying_operations:
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
print("点击确认键")
|
||||
_uo_log("点击确认键")
|
||||
|
||||
def click_back(self, device_id):
|
||||
"""点击返回键"""
|
||||
@@ -992,7 +1016,7 @@ class underlying_operations:
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
print("点击返回键")
|
||||
_uo_log("点击返回键")
|
||||
|
||||
# 电量检测方法已删除
|
||||
|
||||
@@ -1012,7 +1036,7 @@ class underlying_operations:
|
||||
if match:
|
||||
width = int(match.group(1))
|
||||
height = int(match.group(2))
|
||||
print("设备分辨率为:{}*{}".format(width, height))
|
||||
_uo_log("设备分辨率为:{}*{}".format(width, height))
|
||||
return width, height
|
||||
else:
|
||||
raise ValueError("Could not find resolution in adb output")
|
||||
@@ -1042,7 +1066,7 @@ class underlying_operations:
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
print("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
|
||||
_uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1075,10 +1099,10 @@ class underlying_operations:
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
print("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
|
||||
_uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
|
||||
except Exception:
|
||||
# 保存失败不打断主流程
|
||||
print("保存中奖截图失败")
|
||||
_uo_log("保存中奖截图失败")
|
||||
|
||||
def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""):
|
||||
"""裁剪图片,获取需要的区域小图片方便识别
|
||||
@@ -1122,7 +1146,7 @@ class underlying_operations:
|
||||
except (SyntaxError, IOError, OSError) as e:
|
||||
# 图片损坏,重试或返回False
|
||||
if attempt < max_retries - 1:
|
||||
print(
|
||||
_uo_log(
|
||||
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
|
||||
)
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
@@ -1242,7 +1266,7 @@ class underlying_operations:
|
||||
except (SyntaxError, IOError, OSError) as e:
|
||||
# 图片损坏,重试或返回False
|
||||
if attempt < max_retries - 1:
|
||||
print(
|
||||
_uo_log(
|
||||
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
|
||||
)
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
@@ -1269,7 +1293,7 @@ class underlying_operations:
|
||||
):
|
||||
error_msg = f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
|
||||
if attempt == max_retries - 1:
|
||||
print(f"[错误] {error_msg}")
|
||||
_uo_log(f"[错误] {error_msg}")
|
||||
return False
|
||||
continue
|
||||
|
||||
@@ -1320,9 +1344,9 @@ class underlying_operations:
|
||||
# 裁剪或读取图片时发生错误,最后一次尝试失败则记录并返回 False
|
||||
if attempt == max_retries - 1:
|
||||
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
|
||||
print(error_msg)
|
||||
print(f" 源文件: {locals().get('pic1_path', 'N/A')}")
|
||||
print(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
|
||||
_uo_log(error_msg)
|
||||
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
|
||||
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
|
||||
return False
|
||||
# 否则继续重试
|
||||
continue
|
||||
@@ -1553,11 +1577,11 @@ class underlying_operations:
|
||||
if picname in ("福袋内容", "福袋倒计时") and not text:
|
||||
try:
|
||||
if isinstance(result, list) and result and isinstance(result[0], dict):
|
||||
print(
|
||||
_uo_log(
|
||||
f"OCR调试({picname}): result[0] keys={list(result[0].keys())}"
|
||||
)
|
||||
else:
|
||||
print(f"OCR调试({picname}): result type={type(result)}")
|
||||
_uo_log(f"OCR调试({picname}): result type={type(result)}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1968,7 +1992,7 @@ class underlying_operations:
|
||||
def random_delay(self, min_seconds=1, max_seconds=100):
|
||||
"""等待随机的时长"""
|
||||
random_wait_seconds = random.randint(min_seconds, max_seconds)
|
||||
print("随机等待{}秒.".format(random_wait_seconds))
|
||||
_uo_log("随机等待{}秒.".format(random_wait_seconds))
|
||||
self.delay(random_wait_seconds)
|
||||
|
||||
def check_countdown(self, last_time=""):
|
||||
@@ -2113,23 +2137,23 @@ class underlying_operations:
|
||||
try:
|
||||
total_seconds = _parse_seconds(last_time)
|
||||
if total_seconds is None:
|
||||
print("时间格式异常")
|
||||
_uo_log("时间格式异常")
|
||||
return False
|
||||
print("剩余总秒数:", total_seconds)
|
||||
_uo_log("剩余总秒数:", total_seconds)
|
||||
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
|
||||
if total_seconds > 900:
|
||||
total_seconds = 890
|
||||
|
||||
now = datetime.now()
|
||||
print("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
future_time = now + timedelta(seconds=int(total_seconds))
|
||||
future_timestamp = future_time.timestamp()
|
||||
future_datetime = datetime.fromtimestamp(future_timestamp)
|
||||
formatted_future_time = future_datetime.strftime("%Y-%m-%d %H:%M:%S")
|
||||
print("预计开奖时间:", formatted_future_time)
|
||||
_uo_log("预计开奖时间:", formatted_future_time)
|
||||
return int(total_seconds), future_timestamp
|
||||
except Exception:
|
||||
print("输入的字符串不是有效的时间格式")
|
||||
_uo_log("输入的字符串不是有效的时间格式")
|
||||
return False
|
||||
|
||||
def swipe(
|
||||
@@ -2197,16 +2221,16 @@ class underlying_operations:
|
||||
|
||||
# 记录错误但不抛出异常,避免中断主流程
|
||||
error_msg = stderr_text.strip() if stderr_text else "权限不足"
|
||||
print(f"[警告] 滑动操作失败: {error_msg}")
|
||||
print("[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
|
||||
print(
|
||||
_uo_log(f"[警告] 滑动操作失败: {error_msg}")
|
||||
_uo_log("[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
|
||||
_uo_log(
|
||||
" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'"
|
||||
)
|
||||
print(" 2. 使用已 root 的设备")
|
||||
print(" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
|
||||
_uo_log(" 2. 使用已 root 的设备")
|
||||
_uo_log(" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
|
||||
# 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用)
|
||||
except subprocess.TimeoutExpired:
|
||||
print("[警告] 滑动操作超时")
|
||||
_uo_log("[警告] 滑动操作超时")
|
||||
except Exception as e:
|
||||
# 降级重试一次,保持旧逻辑的宽容行为。
|
||||
try:
|
||||
@@ -2217,7 +2241,7 @@ class underlying_operations:
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
print(f"[警告] 滑动操作失败: {type(e).__name__}: {e}")
|
||||
_uo_log(f"[警告] 滑动操作失败: {type(e).__name__}: {e}")
|
||||
|
||||
def _swipe_with_sendevent(self, device_id, x1, y1, x2, y2, steps):
|
||||
"""使用 sendevent 方法滑动(需要 root 权限)"""
|
||||
@@ -2310,7 +2334,7 @@ class underlying_operations:
|
||||
"""
|
||||
try:
|
||||
if log:
|
||||
print(f"[Underlying] click: device_id={device_id} coord=({x},{y})")
|
||||
_uo_log(f"[Underlying] click: device_id={device_id} coord=({x},{y})")
|
||||
except Exception:
|
||||
pass
|
||||
subprocess.run(
|
||||
@@ -2743,7 +2767,7 @@ class underlying_operations:
|
||||
try:
|
||||
if ensure_focus:
|
||||
try:
|
||||
print(
|
||||
_uo_log(
|
||||
f"[Underlying] paste_text_at: clicking to focus device_id={device_id} coord=({x},{y})"
|
||||
)
|
||||
except Exception:
|
||||
@@ -2752,7 +2776,7 @@ class underlying_operations:
|
||||
time_module.sleep(0.2)
|
||||
# 有些输入框第一次点不进,补一次轻点
|
||||
try:
|
||||
print(
|
||||
_uo_log(
|
||||
f"[Underlying] paste_text_at: clicking again to ensure focus device_id={device_id} coord=({x},{y})"
|
||||
)
|
||||
except Exception:
|
||||
@@ -2773,7 +2797,7 @@ class underlying_operations:
|
||||
except Exception:
|
||||
ok_adbkb = False
|
||||
try:
|
||||
print(
|
||||
_uo_log(
|
||||
f"[Underlying] paste_text_at: input_text_adbkeyboard -> {ok_adbkb}"
|
||||
)
|
||||
except Exception:
|
||||
@@ -2790,7 +2814,7 @@ class underlying_operations:
|
||||
except Exception:
|
||||
ok_clip = False
|
||||
try:
|
||||
print(f"[Underlying] paste_text_at: set_clipboard_text -> {ok_clip}")
|
||||
_uo_log(f"[Underlying] paste_text_at: set_clipboard_text -> {ok_clip}")
|
||||
except Exception:
|
||||
pass
|
||||
if ok_clip:
|
||||
@@ -2802,7 +2826,7 @@ class underlying_operations:
|
||||
except Exception:
|
||||
ok_paste = False
|
||||
try:
|
||||
print(f"[Underlying] paste_text_at: paste_from_clipboard -> {ok_paste}")
|
||||
_uo_log(f"[Underlying] paste_text_at: paste_from_clipboard -> {ok_paste}")
|
||||
except Exception:
|
||||
pass
|
||||
if ok_paste:
|
||||
@@ -2810,7 +2834,7 @@ class underlying_operations:
|
||||
|
||||
# 2) 兜底:adb input text(中文可能不稳定)
|
||||
try:
|
||||
print(
|
||||
_uo_log(
|
||||
f"[Underlying] paste_text_at: falling back to input_text for device_id={device_id}"
|
||||
)
|
||||
except Exception:
|
||||
|
||||
Reference in new issue
Block a user