import subprocess import threading from datetime import datetime, timedelta import os import sys import warnings # PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。 # 这里提前设置环境变量,避免启动耗时/卡死。 os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True") os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "1") # 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING) os.environ.setdefault("GLOG_minloglevel", "2") os.environ.setdefault("OMP_NUM_THREADS", "1") # 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告) warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning) warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning) import time as time_module # alias for existing code that uses `time` name time = time_module import logging import re import random import xml.etree.ElementTree as ET import shlex import contextlib import base64 from typing import Tuple, Optional, Any from douyin.core import path_config # 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用。 # 这些常量与文件 IO 辅助函数已抽离到 io_utils.py,此处仅为向后兼容重新导出。 from douyin.core.io_utils import ( _EXTERNAL_DOUYIN_FUDAI_DIR, _EXTERNAL_AXF_SCREENSHOT, _verify_png_integrity, _safe_replace_file, _ensure_parent_dir, _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 # 已搬到子包 douyin.core.underlying_operations_pkg 的 6 个方法实现 from douyin.core.underlying_operations_pkg import ( _adb_path as _impl_adb_path, _find_pic_path as _impl_find_pic_path, _parse_bounds as _impl_parse_bounds, _pick_adbkeyboard_ime as _impl_pick_adbkeyboard_ime, check_countdown as _impl_check_countdown, extract_ocr_content as _impl_extract_ocr_content, _adb_args as _impl_adb_args, save_reward_pic as _impl_save_reward_pic, set_clipboard_text as _impl_set_clipboard_text, _swipe_with_sendevent_improved as _impl_swipe_sendevent_improved, select_device as _impl_select_device, analyse_pic_digits as _impl_analyse_pic_digits, paste_from_clipboard as _impl_paste_from_clipboard, input_text as _impl_input_text, paste_text as _impl_paste_text, get_current_ime as _impl_get_current_ime, list_imes as _impl_list_imes, ensure_adbkeyboard_ime as _impl_ensure_adbkeyboard_ime, restore_ime as _impl_restore_ime, try_set_ime as _impl_try_set_ime, _adbkeyboard_broadcast as _impl_adbkeyboard_broadcast, _adbkeyboard_broadcast_int as _impl_adbkeyboard_broadcast_int, keyevent as _impl_keyevent, adbkeyboard_editor_action as _impl_adbkeyboard_editor_action, confirm_from_keyboard as _impl_confirm_from_keyboard, input_text_adbkeyboard as _impl_input_text_adbkeyboard, paste_text_at as _impl_paste_text_at, uiautomator_dump as _impl_uiautomator_dump, tap_by_text as _impl_tap_by_text, tap_close_icon as _impl_tap_close_icon, get_top_package as _impl_get_top_package, launch_package as _impl_launch_package, is_douyin_foreground as _impl_is_douyin_foreground, ) from douyin.core.underlying_operations_pkg.screenshot_pipeline import ( get_screenshot as _impl_get_screenshot, ) class underlying_operations: """底层操作类""" def __init__(self): # 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。 # 支持延迟初始化(测试流程/只做点击时不需要 OCR)。 self.ocr: Any = None self.ocr_type = None # 'easyocr' 或 'paddleocr' # 用于存储OCR区域的坐标信息(key为picname,value为(left, top, right, bottom)) self._ocr_coords_cache: dict[str, tuple[int, int, int, int]] = {} # 线程安全锁 self._ocr_lock = threading.RLock() # 保护 OCR 初始化 self._ocr_coords_lock = threading.Lock() # 保护坐标缓存 # 并行 OCR:每个工作线程使用独立实例,避免共享同一实例导致底层并发崩溃 self._ocr_thread_local = threading.local() self._ocr_instance_build_lock = threading.Lock() # 默认使用CPU模式(删除GPU检测) self._gpu_available = False if not str(os.environ.get("SKIP_OCR_INIT", "")).strip(): # 统一通过 operations.ocr_operations 的工厂函数初始化(避免与 OCRProcessor 重复定义) # 优先 PaddleOCR v4-mobile(实测精度+速度均胜 EasyOCR),失败回退 EasyOCR try: from operations.ocr_operations import _build_paddle, _build_easyocr # noqa: WPS433 except Exception: _build_paddle = None _build_easyocr = None try: if _build_paddle is None: raise ImportError("ocr_operations._build_paddle 不可用") self.ocr = _build_paddle() self.ocr_type = "paddleocr" _uo_log("[OCR] 使用 PaddleOCR v4-mobile(CPU模式)") except Exception as e: _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" _uo_log("[OCR] 使用 EasyOCR(CPU模式,回退引擎)") except Exception as e2: _uo_log(f"[OCR] 所有 OCR 引擎初始化失败: {e2}") self.ocr = None self.ocr_type = None # 注释掉全局日志禁用,以便查看详细的计时日志 # logging.disable(logging.DEBUG) # logging.disable(logging.WARNING) # 用于短期内记录 get_screenshot 调用来源(用于精确定位高频调用) try: import collections self._screenshot_call_cache = collections.deque(maxlen=1000) except Exception: self._screenshot_call_cache = [] # 日志文件路径(JSON Lines 格式) try: from douyin.core import path_config self._screenshot_log_path = os.path.join( path_config.get_logs_dir(), "screenshot_calls.jsonl" ) except Exception: # path_config 不可用时退化到 dirname(保留旧行为兼容) self._screenshot_log_path = os.path.join( os.path.dirname(__file__), "logs", "screenshot_calls.jsonl" ) @staticmethod def _adb() -> str: adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb") # 始终加引号,避免路径带空格 / 版本混用 if adb.startswith('"') and adb.endswith('"'): return adb return f'"{adb}"' @staticmethod def _adb_path() -> str: return _impl_adb_path() def _adb_args(self, device_id: str, *args: object) -> list[str]: return _impl_adb_args(device_id, *args) @staticmethod def _split_shell_cmd(shell_cmd: str) -> list[str]: return shlex.split(str(shell_cmd or ""), posix=(os.name != "nt")) def _ensure_ocr(self): """OCR 引擎延迟初始化(与 __init__ 同优先级:Paddle 优先,EasyOCR 兜底) 加锁防止多线程并发触发重复初始化(main 在 ff8de2c 修复 #7 并发安全问题时引入 _ocr_lock)。 """ if self.ocr is not None: return with self._ocr_lock: # 双检:拿到锁后再确认一次 if self.ocr is not None: return try: from operations.ocr_operations import _build_paddle, _build_easyocr # noqa: WPS433 except Exception: _build_paddle = None _build_easyocr = None try: if _build_paddle is None: raise ImportError("ocr_operations._build_paddle 不可用") self.ocr = _build_paddle() self.ocr_type = "paddleocr" _uo_log("[OCR] 延迟初始化:使用 PaddleOCR v4-mobile(CPU模式)") return except Exception as e: _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" _uo_log("[OCR] 延迟初始化:使用 EasyOCR(CPU模式,回退)") except Exception as e: _uo_log(f"[OCR] 延迟初始化失败: {e}") self.ocr = None self.ocr_type = None def _get_ocr_for_current_thread(self) -> tuple[Any, Any]: """返回当前线程应使用的 OCR 实例。 规则: - 主线程/显式强制共享:复用 self.ocr; - 并行工作线程:懒初始化线程私有 OCR 实例(仍保持并行执行)。 """ self._ensure_ocr() if self.ocr is None: return None, None try: force_shared = str( os.environ.get("OCR_PARALLEL_SHARE_INSTANCE", "0") ).strip().lower() in ("1", "true", "yes", "on") except Exception: force_shared = False cur_thread = threading.current_thread() if force_shared or cur_thread is threading.main_thread(): return self.ocr, self.ocr_type tl = self._ocr_thread_local ocr_obj = getattr(tl, "ocr", None) ocr_type = getattr(tl, "ocr_type", None) if ocr_obj is not None and ocr_type == self.ocr_type: return ocr_obj, ocr_type with self._ocr_instance_build_lock: # double-check:避免同线程重复初始化 ocr_obj = getattr(tl, "ocr", None) ocr_type = getattr(tl, "ocr_type", None) if ocr_obj is not None and ocr_type == self.ocr_type: return ocr_obj, ocr_type try: from operations.ocr_operations import ( _build_easyocr, # noqa: WPS433 _build_paddle, # noqa: WPS433 ) except Exception: _build_paddle = None _build_easyocr = None try: if self.ocr_type == "paddleocr" and _build_paddle is not None: ocr_obj = _build_paddle() ocr_type = "paddleocr" elif self.ocr_type == "easyocr" and _build_easyocr is not None: ocr_obj = _build_easyocr() ocr_type = "easyocr" elif _build_easyocr is not None: # 主实例类型未知/不可用时,用 easyocr 兜底,保持线程可继续工作 ocr_obj = _build_easyocr() ocr_type = "easyocr" else: ocr_obj = self.ocr ocr_type = self.ocr_type except Exception as e: _uo_log( f"[OCR] 并行线程独立实例初始化失败,回退共享实例: {type(e).__name__}: {e}", "WARNING", ) ocr_obj = self.ocr ocr_type = self.ocr_type tl.ocr = ocr_obj tl.ocr_type = ocr_type try: _uo_log( f"[OCR] 并行线程OCR实例就绪 thread={cur_thread.name} type={ocr_type}", "DEBUG", ) except Exception: pass return ocr_obj, ocr_type def select_device(self): return _impl_select_device() def _find_pic_path(self, picname: str, for_reading: bool = True): return _impl_find_pic_path(picname, for_reading) def get_screenshot(self, device_id, path="pic", use_service: bool = False): """截图(支持后台服务模式)。""" return _impl_get_screenshot(self, device_id, path, use_service) def _get_screenshot_direct(self, device_id, path="pic"): """直接截图(不使用服务模式)。 实现已抽到 underlying_operations_pkg.screenshot_direct.capture_screenshot_direct。 """ from douyin.core.underlying_operations_pkg.screenshot_direct import ( capture_screenshot_direct, ) return capture_screenshot_direct(self, device_id, path) def get_current_hour(self): """获取当前的时间小时数""" time_hour = datetime.now().strftime("%H") _uo_log("当前时间{}点".format(time_hour)) return int(time_hour) def click_confirm(self, device_id): """点击确认键""" subprocess.run( self._adb_args(device_id, "shell", "input", "keyevent", "66"), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) _uo_log("点击确认键") def click_back(self, device_id): """点击返回键""" subprocess.run( self._adb_args(device_id, "shell", "input", "keyevent", "4"), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) _uo_log("点击返回键") # 电量检测方法已删除 def get_device_resolution(self, device_id): """获取设备分辨率""" resolution_info = subprocess.run( self._adb_args(device_id, "shell", "wm", "size"), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", check=False, ) resolution_info_string = resolution_info.stdout or "" match = re.search(r"Physical size: (\d+)x(\d+)", resolution_info_string) if match: width = int(match.group(1)) height = int(match.group(2)) _uo_log("设备分辨率为:{}*{}".format(width, height)) return width, height else: raise ValueError("Could not find resolution in adb output") def save_reward_pic(self, device_id): return _impl_save_reward_pic(device_id) def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""): """裁剪图片,获取需要的区域小图片方便识别。""" from douyin.core.underlying_operations_pkg.image_ops import ( cut_pic as _impl, ) return _impl(self, left_up, right_down, target, name) def analyse_pic_word( self, picname, change_color=0, pic_path=None, return_confidence=False ): """对指定图片运行 OCR 并返回拼接后的文本结果。 参数: picname: 用于分类和调试的图片名(如"福袋内容") change_color: 颜色处理模式,0=保留彩色(推荐),1/2=二值化等 pic_path: 可选的图片路径,未提供时通过 `_find_pic_path` 查找 return_confidence: 是否返回置信度信息(默认False,保持向后兼容) """ from douyin.core.underlying_operations_pkg.ocr_pipeline import ( analyse_pic_word as _impl, ) return _impl(self, picname, change_color, pic_path, return_confidence) def analyse_pic_digits(self, picname, change_color=1, pic_path=None): return _impl_analyse_pic_digits(self, picname, change_color, pic_path) def extract_ocr_content(self, content=None, return_confidence: bool = False): return _impl_extract_ocr_content(content, return_confidence) def delay(self, seconds: float = 1): time_module.sleep(seconds) def random_delay(self, min_seconds=1, max_seconds=100): """等待随机的时长""" random_wait_seconds = random.randint(min_seconds, max_seconds) _uo_log("随机等待{}秒.".format(random_wait_seconds)) self.delay(random_wait_seconds) def check_countdown(self, last_time: str = "") -> tuple | bool: return _impl_check_countdown(last_time) def swipe( self, device_id, left_up_x=0, left_up_y=0, right_down_x=1080, right_down_y=1500, steps=300, ): """划动屏幕 参数说明: - left_up_x, left_up_y: 滑动起始位置(手指按下位置) - right_down_x, right_down_y: 滑动结束位置(手指抬起位置) - steps: 滑动持续时间(毫秒),数值越大滑动越慢,默认300ms(已优化,比之前的200ms更快) 执行命令:adb shell input swipe """ # 注意:adb input swipe 的参数顺序是:start_x start_y end_x end_y duration_ms # 这里 left_up_x/y 是起始位置,right_down_x/y 是结束位置 cmd = self._adb_args( device_id, "shell", "input", "swipe", int(left_up_x), int(left_up_y), int(right_down_x), int(right_down_y), int(steps), ) try: # 使用 subprocess 执行命令,捕获错误输出 result = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5.0, text=True, encoding="utf-8", errors="replace", check=False, ) # 检查是否有权限错误 stderr_text = result.stderr if result.stderr else "" has_permission_error = result.returncode != 0 and ( "SecurityException" in stderr_text or "INJECT_EVENTS" in stderr_text or "Injecting to another application" in stderr_text ) if has_permission_error: # 尝试使用 uiautomator(如果可用,某些设备可能支持) try: self._swipe_with_uiautomator( device_id, left_up_x, left_up_y, right_down_x, right_down_y ) return except Exception: pass # 记录错误但不抛出异常,避免中断主流程 error_msg = stderr_text.strip() if stderr_text else "权限不足" _uo_log(f"[警告] 滑动操作失败: {error_msg}") _uo_log("[提示] 设备不允许 ADB 输入注入,可能的解决方案:") _uo_log( " 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'" ) _uo_log(" 2. 使用已 root 的设备") _uo_log(" 3. 某些设备需要在设置中手动授权 ADB 输入权限") # 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用) except subprocess.TimeoutExpired: _uo_log("[警告] 滑动操作超时") except Exception as e: # 降级重试一次,保持旧逻辑的宽容行为。 try: subprocess.run( cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) except Exception: _uo_log(f"[警告] 滑动操作失败: {type(e).__name__}: {e}") def _swipe_with_sendevent(self, device_id, x1, y1, x2, y2, steps): """使用 sendevent 方法滑动(需要 root 权限)""" # 获取触摸设备路径 result = subprocess.run( self._adb_args(device_id, "shell", "getevent", "-p"), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", check=False, ) if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower(): raise FileNotFoundError("无法找到触摸设备") # 简化实现:直接使用 input 命令的替代参数 # 注意:sendevent 需要 root 权限,这里只是尝试 raise PermissionError("sendevent 需要 root 权限,暂不支持") def _swipe_with_uiautomator(self, device_id, x1, y1, x2, y2): """使用 uiautomator 滑动(如果可用) 注意:uiautomator 在某些设备上可能也需要权限,但可以尝试作为备选方案。 """ # 使用 uiautomator swipe 命令 # 注意:uiautomator 命令格式可能因 Android 版本而异 # Android 5.0+: uiautomator swipe [steps] result = subprocess.run( self._adb_args( device_id, "shell", "uiautomator", "swipe", int(x1), int(y1), int(x2), int(y2) ), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5.0, check=False, ) if result.returncode != 0: raise RuntimeError( f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}" ) def _swipe_with_sendevent_improved(self, device_id, x1, y1, x2, y2, steps=50): return _impl_swipe_sendevent_improved(device_id, x1, y1, x2, y2, steps) def click(self, device_id, x=500, y=500, log: bool = True): """点击坐标位置 参数: device_id: 设备ID x, y: 屏幕坐标 log: 是否打印底层日志(默认为 True)。在需要安静点击的场景(如养号)传 False。 """ try: if log: _uo_log(f"[Underlying] click: device_id={device_id} coord=({x},{y})") except Exception: pass subprocess.run( self._adb_args(device_id, "shell", "input", "tap", int(x), int(y)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) def long_press( self, device_id: str, x: int, y: int, duration_ms: int = 900 ) -> None: """长按某个坐标(通过 swipe x y x y duration 模拟)。""" d = int(duration_ms or 900) if d < 300: d = 300 if d > 2000: d = 2000 subprocess.run( self._adb_args( device_id, "shell", "input", "swipe", int(x), int(y), int(x), int(y), d ), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) def _run_adb_shell( self, device_id: str, shell_cmd: str, timeout_seconds: float = 3.0 ) -> bool: """运行 adb shell 命令,成功返回 True。""" try: r = subprocess.run( self._adb_args(device_id, "shell", *self._split_shell_cmd(shell_cmd)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout_seconds, check=False, ) return r.returncode == 0 except Exception: return False def _run_adb_shell_capture( self, device_id: str, shell_cmd: str, timeout_seconds: float = 3.0 ) -> Tuple[bool, str]: """运行 adb shell 命令并捕获输出,返回 (ok, stdout)。""" try: r = subprocess.run( self._adb_args(device_id, "shell", *self._split_shell_cmd(shell_cmd)), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout_seconds, text=True, encoding="utf-8", errors="ignore", check=False, ) return (r.returncode == 0), (r.stdout or "") except Exception: return False, "" def get_top_package(self, device_id: str) -> str: return _impl_get_top_package(self, device_id) def launch_package( self, device_id: str, package_name: str = "", timeout_seconds: float = 5.0, ) -> Tuple[bool, str]: return _impl_launch_package(self, device_id, package_name, timeout_seconds) def is_douyin_foreground(self, device_id: str) -> bool: return _impl_is_douyin_foreground(self, device_id) def set_clipboard_text(self, device_id: str, text: str) -> bool: return _impl_set_clipboard_text(device_id, text) def paste_from_clipboard(self, device_id: str) -> bool: return _impl_paste_from_clipboard(self, device_id) def input_text(self, device_id: str, text: str) -> bool: return _impl_input_text(self, device_id, text) def paste_text(self, device_id: str, text: str) -> bool: return _impl_paste_text(self, device_id, text) # ===== ADBKeyboard (可选) ===== def get_current_ime(self, device_id: str) -> str: return _impl_get_current_ime(self, device_id) def list_imes(self, device_id: str) -> list[str]: return _impl_list_imes(self, device_id) @staticmethod # type: ignore[misc] def _pick_adbkeyboard_ime(imes: list[str]) -> str: return _impl_pick_adbkeyboard_ime(imes) def ensure_adbkeyboard_ime( self, device_id: str, preferred_ime: str = path_config.get_adb_keyboard_ime() ) -> Tuple[bool, str, str]: return _impl_ensure_adbkeyboard_ime(self, device_id, preferred_ime) def restore_ime(self, device_id: str, prev_ime: str) -> bool: return _impl_restore_ime(self, device_id, prev_ime) def try_set_ime(self, device_id: str, ime_id: str) -> bool: return _impl_try_set_ime(self, device_id, ime_id) def _adbkeyboard_broadcast(self, device_id: str, action: str, msg: str) -> bool: return _impl_adbkeyboard_broadcast(self, device_id, action, msg) def _adbkeyboard_broadcast_int( self, device_id: str, action: str, key: str, value: int ) -> bool: return _impl_adbkeyboard_broadcast_int(self, device_id, action, key, value) def keyevent(self, device_id: str, keycode: int) -> bool: return _impl_keyevent(self, device_id, keycode) def adbkeyboard_editor_action(self, device_id: str, action_code: int = 4) -> bool: return _impl_adbkeyboard_editor_action(self, device_id, action_code) def confirm_from_keyboard(self, device_id: str) -> bool: return _impl_confirm_from_keyboard(self, device_id) def input_text_adbkeyboard( self, device_id: str, text: str, ime_id: str = path_config.get_adb_keyboard_ime(), restore_prev: bool = True, ) -> bool: return _impl_input_text_adbkeyboard(self, device_id, text, ime_id, restore_prev) def paste_text_at( self, device_id: str, x: int, y: int, text: str, ensure_focus: bool = True ) -> bool: return _impl_paste_text_at(self, device_id, x, y, text, ensure_focus) def _uiautomator_dump(self, device_id: str, local_path: str) -> bool: return _impl_uiautomator_dump(self, device_id, local_path) @staticmethod def _parse_bounds(bounds: str): return _impl_parse_bounds(bounds) def tap_by_text( self, device_id: str, text: str, contains: bool = True, timeout_seconds: float = 2.0, ) -> bool: return _impl_tap_by_text(self, device_id, text, contains, timeout_seconds) def tap_close_icon( self, device_id: str, screen_width: int = 1080, timeout_seconds: float = 2.0 ) -> bool: return _impl_tap_close_icon(self, device_id, screen_width, timeout_seconds)