654 lines
30 KiB
Python
654 lines
30 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Screen 门面:把「截图 + 匹配 + 点击 + 等待」收成一组好用方法。
|
||
|
||
一个 Screen 实例 = 一套固定配置(截图范围/窗口、阈值、缩放集合、灰度、调试图目录),
|
||
业务里通常这样用:
|
||
s = Screen(window="钉钉")
|
||
s.activate()
|
||
if not s.wait("img/list_loaded.png", timeout=30):
|
||
raise RuntimeError("列表没加载出来")
|
||
s.click("img/btn_export.png")
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import os
|
||
import random
|
||
import time
|
||
from typing import List, Optional, Sequence, Tuple, Union
|
||
|
||
import numpy as np
|
||
|
||
from . import capture, clipboard, colors, keys, ocr, matcher as _m
|
||
from ._win32 import activate_window, click_at as _click_at, cursor_pos
|
||
from ._win32 import drag as _drag
|
||
from ._win32 import move_mouse as _move_mouse
|
||
from ._win32 import move_to
|
||
from ._win32 import scroll as _scroll
|
||
from ._win32 import screen_size
|
||
from .colors import ColorMatch
|
||
from .matcher import Match
|
||
from .ocr import TextItem
|
||
|
||
logger = logging.getLogger("desktopauto")
|
||
|
||
Region = Sequence[int]
|
||
Template = Union[str, np.ndarray]
|
||
|
||
# 九宫格锚点因子(影刀「点击图像」的 anchor_type / sudoku_part)
|
||
_ANCHORS = {
|
||
"center": (0.5, 0.5), "middlecenter": (0.5, 0.5),
|
||
"left": (0.0, 0.5), "middleleft": (0.0, 0.5),
|
||
"right": (1.0, 0.5), "middleright": (1.0, 0.5),
|
||
"top": (0.5, 0.0), "middletop": (0.5, 0.0),
|
||
"bottom": (0.5, 1.0), "middlebottom": (0.5, 1.0),
|
||
"topleft": (0.0, 0.0), "lefttop": (0.0, 0.0),
|
||
"topright": (1.0, 0.0), "righttop": (1.0, 0.0),
|
||
"bottomleft": (0.0, 1.0), "leftbottom": (0.0, 1.0),
|
||
"bottomright": (1.0, 1.0), "rightbottom": (1.0, 1.0),
|
||
}
|
||
|
||
|
||
class Screen:
|
||
"""屏幕识图门面。
|
||
|
||
Args:
|
||
window: 限定窗口(hwnd 或标题关键字);设置后所有截图/匹配只在该窗口矩形内。
|
||
region: 限定区域 (left, top, right, bottom);window 优先。
|
||
threshold: 相似度阈值(默认 0.85)。
|
||
scales: 模板缩放集合(默认 (1.0,);跨 DPI 复用模板时可给 (0.8, 0.9, 1.0, 1.1, 1.25))。
|
||
gray: 灰度匹配(默认 True)。
|
||
debug_dir: 非空时每次匹配把命中/未命中截图落盘,便于排查。
|
||
activate_before_click: 点击前自动激活 window(仅当设置了 window)。
|
||
"""
|
||
|
||
def __init__(self,
|
||
window: Union[int, str, None] = None,
|
||
region: Optional[Region] = None,
|
||
threshold: float = _m.DEFAULT_THRESHOLD,
|
||
scales: Sequence[float] = (1.0,),
|
||
gray: bool = True,
|
||
debug_dir: str = "",
|
||
activate_before_click: bool = True):
|
||
self.window = window
|
||
self.region = tuple(int(v) for v in region) if region else None
|
||
self.threshold = float(threshold)
|
||
self.scales = tuple(scales) if scales else (1.0,)
|
||
self.gray = bool(gray)
|
||
self.debug_dir = debug_dir or ""
|
||
self.activate_before_click = activate_before_click
|
||
|
||
# ---------- 配置派生 ----------
|
||
def clone(self, **kwargs) -> "Screen":
|
||
"""派生一个新实例(覆盖部分配置,不改原对象)。"""
|
||
cfg = {"window": self.window, "region": self.region, "threshold": self.threshold,
|
||
"scales": self.scales, "gray": self.gray, "debug_dir": self.debug_dir,
|
||
"activate_before_click": self.activate_before_click}
|
||
cfg.update(kwargs)
|
||
return Screen(**cfg)
|
||
|
||
def _options(self, kwargs: dict) -> dict:
|
||
"""合并单次调用的临时覆盖项(threshold/scales/gray/window/region/max_results)。"""
|
||
opts = {"window": self.window, "region": self.region, "threshold": self.threshold,
|
||
"scales": self.scales, "gray": self.gray, "max_results": 0}
|
||
for key in ("window", "region", "threshold", "scales", "gray", "max_results"):
|
||
if key in kwargs and kwargs[key] is not None:
|
||
opts[key] = kwargs[key]
|
||
return opts
|
||
|
||
# ---------- 截图 ----------
|
||
def grab(self) -> Tuple[np.ndarray, Tuple[int, int, int, int]]:
|
||
"""按当前配置截图,返回 (BGR 图, 屏幕区域)。"""
|
||
return capture.grab(region=self.region, window=self.window)
|
||
|
||
def screenshot(self, path: str = "", region: Optional[Region] = None,
|
||
window: Union[int, str, None] = None) -> str:
|
||
"""截图落盘,返回文件路径(path 为空时自动生成文件名)。"""
|
||
return capture.screenshot(path=path,
|
||
region=self.region if region is None else region,
|
||
window=self.window if window is None else window)
|
||
|
||
def activate(self) -> None:
|
||
"""激活限定窗口(未设置 window 时无操作)。"""
|
||
if self.window is not None:
|
||
activate_window(self.window)
|
||
|
||
# ---------- 识图 ----------
|
||
def find_all(self, template: Template, **kwargs) -> List[Match]:
|
||
"""找出全部命中(按相似度降序);没有返回空列表。"""
|
||
opts = self._options(kwargs)
|
||
img, reg = capture.grab(region=opts["region"], window=opts["window"])
|
||
matches = _m.match_in(img, template, threshold=opts["threshold"], scales=opts["scales"],
|
||
gray=opts["gray"], max_results=int(opts["max_results"] or 0),
|
||
origin=(reg[0], reg[1]))
|
||
self._dump(img, matches, template, reg)
|
||
return matches
|
||
|
||
def find(self, template: Template, **kwargs) -> Optional[Match]:
|
||
"""找最像的一个;没找到返回 None。"""
|
||
kwargs.setdefault("max_results", 1)
|
||
matches = self.find_all(template, **kwargs)
|
||
return matches[0] if matches else None
|
||
|
||
def exists(self, template: Template, **kwargs) -> bool:
|
||
"""识图判断是否存在(不做点击)。"""
|
||
return self.find(template, **kwargs) is not None
|
||
|
||
def wait_all(self, templates: Sequence[Template], timeout: float = 10.0,
|
||
interval: float = 0.5, **kwargs) -> bool:
|
||
"""等所有模板都出现(影刀「等待图像」勾选"等待所有图像"),超时返回 False。
|
||
|
||
同一帧里一次性判断,避免逐图重复截图。
|
||
"""
|
||
tpl_list = list(templates or ())
|
||
if not tpl_list:
|
||
raise ValueError("wait_all 需要至少一个模板")
|
||
deadline = time.time() + max(0.0, float(timeout))
|
||
while True:
|
||
opts = self._options(kwargs)
|
||
img, reg = capture.grab(region=opts["region"], window=opts["window"])
|
||
origin = (reg[0], reg[1])
|
||
missing = [t for t in tpl_list
|
||
if not _m.match_in(img, t, threshold=opts["threshold"],
|
||
scales=opts["scales"], gray=opts["gray"],
|
||
max_results=1, origin=origin)]
|
||
if not missing:
|
||
return True
|
||
if time.time() >= deadline:
|
||
logger.debug("wait_all 超时,未出现:%s", missing)
|
||
return False
|
||
time.sleep(max(0.05, float(interval)))
|
||
|
||
def wait_gone(self, template: Template, timeout: float = 10.0,
|
||
interval: float = 0.5, **kwargs) -> bool:
|
||
"""等待图像/文字消失(等加载遮罩、等弹窗关闭),超时返回 False。"""
|
||
deadline = time.time() + max(0.0, float(timeout))
|
||
while True:
|
||
if self.find(template, **kwargs) is None:
|
||
return True
|
||
if time.time() >= deadline:
|
||
return False
|
||
time.sleep(max(0.05, float(interval)))
|
||
|
||
def wait_any(self, templates: Sequence[Template] = (), texts: Sequence[str] = (),
|
||
timeout: float = 10.0, interval: float = 0.5,
|
||
min_score: float = 0.0, **kwargs) -> Optional[dict]:
|
||
"""等待「任一条件」出现:多张图任一命中,或任一文字出现。
|
||
|
||
Returns:
|
||
{"kind": "image"|"text", "target": 模板名或文字, "match": Match|TextItem}
|
||
超时返回 None。
|
||
"""
|
||
tpl_list = list(templates or ())
|
||
text_list = [t for t in (texts or ()) if str(t).strip()]
|
||
if not tpl_list and not text_list:
|
||
raise ValueError("wait_any 需要至少一个模板或文字")
|
||
deadline = time.time() + max(0.0, float(timeout))
|
||
while True:
|
||
opts = self._options(kwargs)
|
||
img, reg = capture.grab(region=opts["region"], window=opts["window"])
|
||
if tpl_list:
|
||
hit, idx = _m.match_any_in(img, tpl_list, threshold=opts["threshold"],
|
||
scales=opts["scales"], gray=opts["gray"],
|
||
origin=(reg[0], reg[1]))
|
||
if hit is not None:
|
||
tpl = tpl_list[idx]
|
||
return {"kind": "image", "match": hit,
|
||
"target": tpl if isinstance(tpl, str) else f"<ndarray#{idx}>"}
|
||
if text_list:
|
||
items = ocr.offset(ocr.recognize(img, min_score=min_score), (reg[0], reg[1]))
|
||
for t in text_list:
|
||
h = ocr.best_text(ocr.match_text(items, t))
|
||
if h is not None:
|
||
return {"kind": "text", "target": t, "match": h}
|
||
if time.time() >= deadline:
|
||
return None
|
||
time.sleep(max(0.1, float(interval)))
|
||
|
||
def find_any(self, templates: Sequence[Template], **kwargs) -> Tuple[Optional[Match], str]:
|
||
"""在一组模板里找最像的一个(一个按钮的多种状态),返回 (命中, 模板名)。
|
||
|
||
都没命中返回 (None, "")。
|
||
"""
|
||
tpl_list = list(templates or ())
|
||
if not tpl_list:
|
||
raise ValueError("find_any 需要至少一个模板")
|
||
opts = self._options(kwargs)
|
||
img, reg = capture.grab(region=opts["region"], window=opts["window"])
|
||
hit, idx = _m.match_any_in(img, tpl_list, threshold=opts["threshold"],
|
||
scales=opts["scales"], gray=opts["gray"],
|
||
origin=(reg[0], reg[1]))
|
||
if hit is None:
|
||
return None, ""
|
||
tpl = tpl_list[idx]
|
||
return hit, (tpl if isinstance(tpl, str) else f"<ndarray#{idx}>")
|
||
|
||
def wait(self, template: Template, timeout: float = 10.0,
|
||
interval: float = 0.5, **kwargs) -> Optional[Match]:
|
||
"""轮询等待出现,超时返回 None(不抛错,便于业务判分支)。"""
|
||
deadline = time.time() + max(0.0, float(timeout))
|
||
while True:
|
||
hit = self.find(template, **kwargs)
|
||
if hit is not None:
|
||
return hit
|
||
if time.time() >= deadline:
|
||
logger.debug("等待超时:%s(%.1fs)", template if isinstance(template, str) else "<ndarray>", timeout)
|
||
return None
|
||
time.sleep(max(0.05, float(interval)))
|
||
|
||
# ---------- 点击 ----------
|
||
def click(self, template: Template, button: str = "left", clicks: int = 1,
|
||
offset: Tuple[int, int] = (0, 0), activate: Optional[bool] = None,
|
||
timeout: float = 0.0, delay_after: float = 0.0,
|
||
anchor: str = "center", **kwargs) -> bool:
|
||
"""识图点击:找到模板后点击它,返回是否点到。
|
||
|
||
Args:
|
||
button: left / right / middle。
|
||
clicks: 1=单击,2=双击。
|
||
offset: 在锚点基础上的像素偏移。
|
||
timeout: >0 时先等图出现(秒),等不到返回 False(影刀「点击图像」的 timeout)。
|
||
delay_after: 点击后延时(秒),等界面响应。
|
||
anchor: 点击位置:center(默认)/ left / right / top / bottom / topleft / topright /
|
||
bottomleft / bottomright(影刀的"九宫格"锚点)。
|
||
"""
|
||
should_activate = self.activate_before_click if activate is None else bool(activate)
|
||
if should_activate and self.window is not None:
|
||
self.activate()
|
||
if timeout and timeout > 0:
|
||
hit = self.wait(template, timeout=timeout, interval=0.3, **kwargs)
|
||
else:
|
||
hit = self.find(template, **kwargs)
|
||
if hit is None:
|
||
logger.warning("识图点击未命中,跳过点击:%s",
|
||
template if isinstance(template, str) else "<ndarray>")
|
||
return False
|
||
px, py = self._anchor_point(hit, anchor, offset)
|
||
_click_at(px, py, button=button, clicks=clicks)
|
||
if delay_after and delay_after > 0:
|
||
time.sleep(float(delay_after))
|
||
logger.debug("识图点击 %s → (%d, %d) score=%.3f", template, px, py, hit.score)
|
||
return True
|
||
|
||
@staticmethod
|
||
def _anchor_point(hit: Match, anchor: str = "center",
|
||
offset: Tuple[int, int] = (0, 0)) -> Tuple[int, int]:
|
||
"""按九宫格锚点算点击坐标(center/left/right/top/bottom/四角)。"""
|
||
fx, fy = _ANCHORS.get((anchor or "center").lower().replace("_", ""), (0.5, 0.5))
|
||
x = hit.left + int(max(0, hit.width - 1) * fx)
|
||
y = hit.top + int(max(0, hit.height - 1) * fy)
|
||
return x + int(offset[0]), y + int(offset[1])
|
||
|
||
def click_at(self, x: int, y: int, button: str = "left",
|
||
clicks: int = 1, activate: bool = False) -> None:
|
||
"""直接点击屏幕坐标(识图结果的另一种用法:外部算出坐标再点)。"""
|
||
if activate and self.window is not None:
|
||
self.activate()
|
||
_click_at(int(x), int(y), button=button, clicks=clicks)
|
||
|
||
def hover(self, target, offset: Tuple[int, int] = (0, 0),
|
||
activate: Optional[bool] = None, **kwargs) -> bool:
|
||
"""鼠标悬停在图像(或坐标)上,不点击;用于展开下拉、触发 tooltip。"""
|
||
should_activate = self.activate_before_click if activate is None else bool(activate)
|
||
if should_activate and self.window is not None:
|
||
self.activate()
|
||
point = self._point(target, **kwargs)
|
||
if point is None:
|
||
return False
|
||
move_to(point[0] + int(offset[0]), point[1] + int(offset[1]))
|
||
return True
|
||
|
||
def hover_text(self, text: str, offset: Tuple[int, int] = (0, 0),
|
||
activate: Optional[bool] = None, **kwargs) -> bool:
|
||
"""鼠标悬停在文字上(OCR 定位后移过去,不点击)。"""
|
||
should_activate = self.activate_before_click if activate is None else bool(activate)
|
||
if should_activate and self.window is not None:
|
||
self.activate()
|
||
hit = self.find_text(text, **kwargs)
|
||
if hit is None:
|
||
logger.warning("悬停未找到文字:%s", text)
|
||
return False
|
||
cx, cy = hit.center
|
||
move_to(cx + int(offset[0]), cy + int(offset[1]))
|
||
return True
|
||
|
||
# ---------- 键盘 / 剪贴板 / 滚轮 / 拖拽 ----------
|
||
def paste(self, text: str, restore: bool = True) -> None:
|
||
"""写剪贴板 + Ctrl+V 粘贴(中文、长文本最稳;restore=True 时粘贴后恢复原剪贴板)。"""
|
||
clipboard.paste(text, restore=restore)
|
||
|
||
def type_text(self, text: str, method: str = "auto", interval: float = 0.01) -> None:
|
||
"""输入文本(auto:含非 ASCII 自动走剪贴板,纯英文走逐字符注入)。"""
|
||
keys.type_text(text, method=method, interval=interval)
|
||
|
||
def press(self, key: str, times: int = 1, interval: float = 0.05) -> None:
|
||
"""按键(enter/tab/esc/f5/a/1 ...)。"""
|
||
keys.press(key, times=times, interval=interval)
|
||
|
||
def send_keys(self, keys_text: str, interval: float = 0.02, delay_after: float = 0.0) -> None:
|
||
"""发送按键串(兼容影刀写法):`{ENTER}`、`^a`、`%{F4}`、`abc{ENTER}`。"""
|
||
keys.send_keys(keys_text, interval=interval, delay_after=delay_after)
|
||
|
||
def move_mouse(self, x: int, y: int, relative_to: str = "screen",
|
||
speed: str = "instant") -> Tuple[int, int]:
|
||
"""移动鼠标;relative_to="window" 时按本窗口左上角算偏移。"""
|
||
return _move_mouse(x, y, relative_to=relative_to, speed=speed, window=self.window)
|
||
|
||
def hotkey(self, *key_names: str, interval: float = 0.02) -> None:
|
||
"""组合键,如 hotkey("ctrl", "s")、hotkey("alt", "f4")。"""
|
||
keys.hotkey(*key_names, interval=interval)
|
||
|
||
def scroll(self, notches: int = 3, at=None, horizontal: bool = False) -> None:
|
||
"""滚动滚轮;at 可传坐标 (x, y) 或模板图(先定位再滚)。"""
|
||
point = self._point(at) if at is not None else None
|
||
_scroll(notches, at=point, horizontal=horizontal)
|
||
|
||
def drag(self, src, dst, duration: float = 0.5, button: str = "left") -> None:
|
||
"""拖拽:src/dst 可传坐标 (x, y) 或模板图(先定位中心再拖)。"""
|
||
p1 = self._point(src)
|
||
p2 = self._point(dst)
|
||
_drag(p1, p2, duration=duration, button=button)
|
||
|
||
def _point(self, target, **kwargs) -> Optional[Tuple[int, int]]:
|
||
"""把「坐标」或「模板」统一解析成屏幕坐标点(模板没找到返回 None)。"""
|
||
if target is None:
|
||
return None
|
||
if isinstance(target, (tuple, list)) and len(target) == 2 \
|
||
and all(isinstance(v, (int, float)) for v in target):
|
||
return int(target[0]), int(target[1])
|
||
hit = self.find(target, **kwargs)
|
||
if hit is None:
|
||
logger.warning("定位失败,未找到:%s", target)
|
||
return None
|
||
return hit.center
|
||
|
||
# ---------- 文字识别(OCR) ----------
|
||
def read_text(self, min_score: float = 0.0, **kwargs) -> List[TextItem]:
|
||
"""识别当前画面全部文字,返回带坐标的列表(坐标已换算成屏幕坐标)。"""
|
||
opts = self._options(kwargs)
|
||
img, reg = capture.grab(region=opts["region"], window=opts["window"])
|
||
items = ocr.recognize(img, min_score=min_score)
|
||
return ocr.offset(items, (reg[0], reg[1]))
|
||
|
||
def find_all_text(self, text: str, exact: bool = False, regex: bool = False,
|
||
case_sensitive: bool = False, min_score: float = 0.0,
|
||
**kwargs) -> List[TextItem]:
|
||
"""按文字找全部命中(默认包含匹配、忽略大小写与空白)。"""
|
||
items = self.read_text(min_score=min_score, **kwargs)
|
||
return ocr.match_text(items, text, exact=exact, regex=regex, case_sensitive=case_sensitive)
|
||
|
||
def find_text(self, text: str, **kwargs) -> Optional[TextItem]:
|
||
"""按文字找最可信的一个;找不到返回 None。"""
|
||
hits = self.find_all_text(text, **kwargs)
|
||
return ocr.best_text(hits)
|
||
|
||
def text_exists(self, text: str, **kwargs) -> bool:
|
||
"""判断文字是否存在(OCR 一次后本地匹配)。"""
|
||
return self.find_text(text, **kwargs) is not None
|
||
|
||
def wait_text(self, text: str, timeout: float = 10.0, interval: float = 1.0,
|
||
**kwargs) -> Optional[TextItem]:
|
||
"""轮询等待文字出现(OCR 较慢,默认间隔 1s;建议限定 region/window)。"""
|
||
deadline = time.time() + max(0.0, float(timeout))
|
||
while True:
|
||
hit = self.find_text(text, **kwargs)
|
||
if hit is not None:
|
||
return hit
|
||
if time.time() >= deadline:
|
||
return None
|
||
time.sleep(max(0.2, float(interval)))
|
||
|
||
def click_text(self, text: str, button: str = "left", clicks: int = 1,
|
||
offset: Tuple[int, int] = (0, 0), activate: Optional[bool] = None,
|
||
timeout: float = 0.0, delay_after: float = 0.0, **kwargs) -> bool:
|
||
"""按文字点击:OCR 找到文字后点其中心,返回是否点到。
|
||
|
||
timeout>0 时先等文字出现(秒);delay_after=点击后延时。
|
||
"""
|
||
should_activate = self.activate_before_click if activate is None else bool(activate)
|
||
if should_activate and self.window is not None:
|
||
self.activate()
|
||
if timeout and timeout > 0:
|
||
hit = self.wait_text(text, timeout=timeout, interval=1.0, **kwargs)
|
||
else:
|
||
hit = self.find_text(text, **kwargs)
|
||
if hit is None:
|
||
logger.warning("按文字点击未找到:%s", text)
|
||
return False
|
||
cx, cy = hit.center
|
||
_click_at(cx + int(offset[0]), cy + int(offset[1]), button=button, clicks=clicks)
|
||
if delay_after and delay_after > 0:
|
||
time.sleep(float(delay_after))
|
||
logger.debug("按文字点击 '%s' → (%d, %d) score=%.3f", hit.text, cx, cy, hit.score)
|
||
return True
|
||
|
||
# ---------- 纯文本 OCR(给 LLM / 日志用) ----------
|
||
def ocr_text(self, sep: str = "\n", min_score: float = 0.0, **kwargs) -> str:
|
||
"""通用文字识别(只要文本,不要坐标);多段用 sep 连接。"""
|
||
items = self.read_text(min_score=min_score, **kwargs)
|
||
return sep.join(it.text for it in items)
|
||
|
||
# ---------- 找色 / 界面差异 ----------
|
||
def find_color(self, color, tolerance: int = 12, min_area: int = 4,
|
||
max_results: int = 0, **kwargs) -> List[ColorMatch]:
|
||
"""找指定颜色的连通区域(颜色用 RGB:"#FF3B30" 或 (255,59,48))。"""
|
||
opts = self._options(kwargs)
|
||
return colors.find_color(color, tolerance=tolerance, region=opts["region"],
|
||
window=opts["window"], min_area=min_area,
|
||
max_results=max_results)
|
||
|
||
def color_exists(self, color, tolerance: int = 12, min_area: int = 4, **kwargs) -> bool:
|
||
"""画面上是否存在该颜色(判断红点/告警/高亮)。"""
|
||
return bool(self.find_color(color, tolerance=tolerance, min_area=min_area,
|
||
max_results=1, **kwargs))
|
||
|
||
def diff(self, baseline, tolerance: int = 10, min_area: int = 30, **kwargs) -> dict:
|
||
"""把当前画面与基准图比对,返回变化比例与变化区域(判断界面是否变化/卡死)。"""
|
||
opts = self._options(kwargs)
|
||
return colors.diff(baseline, None, tolerance=tolerance, min_area=min_area,
|
||
region=opts["region"], window=opts["window"])
|
||
|
||
# ---------- 调试 ----------
|
||
def _dump(self, img: np.ndarray, matches: Sequence[Match], template: Template,
|
||
region: Tuple[int, int, int, int]) -> None:
|
||
"""调试图:命中画框、未命中存原图,文件名带模板名与时间戳。"""
|
||
if not self.debug_dir:
|
||
return
|
||
try:
|
||
name = os.path.splitext(os.path.basename(str(template)))[0] \
|
||
if isinstance(template, str) else "template"
|
||
tag = "hit" if matches else "miss"
|
||
ts = time.strftime("%Y%m%d_%H%M%S")
|
||
shot = _m.annotate(img, matches, origin=(region[0], region[1]))
|
||
capture.save_image(shot, os.path.join(self.debug_dir, f"{tag}_{name}_{ts}.png"))
|
||
except Exception as e: # noqa: BLE001 调试图失败不影响主流程
|
||
logger.debug("调试图保存失败:%s", e)
|
||
|
||
|
||
# ==================== 模块级便捷函数(默认全屏单例) ====================
|
||
_default = Screen()
|
||
|
||
|
||
def find(template: Template, **kwargs) -> Optional[Match]:
|
||
"""在全屏找最像的一个。"""
|
||
return _default.find(template, **kwargs)
|
||
|
||
|
||
def find_all(template: Template, **kwargs) -> List[Match]:
|
||
"""在全屏找全部命中。"""
|
||
return _default.find_all(template, **kwargs)
|
||
|
||
|
||
def exists(template: Template, **kwargs) -> bool:
|
||
"""识图判断是否存在(全屏)。"""
|
||
return _default.exists(template, **kwargs)
|
||
|
||
|
||
def wait(template: Template, timeout: float = 10.0, interval: float = 0.5, **kwargs) -> Optional[Match]:
|
||
"""全屏轮询等待出现。"""
|
||
return _default.wait(template, timeout=timeout, interval=interval, **kwargs)
|
||
|
||
|
||
def click(template: Template, button: str = "left", clicks: int = 1,
|
||
offset: Tuple[int, int] = (0, 0), **kwargs) -> bool:
|
||
"""识图点击(全屏)。"""
|
||
return _default.click(template, button=button, clicks=clicks, offset=offset, **kwargs)
|
||
|
||
|
||
def cursor() -> Tuple[int, int]:
|
||
"""当前鼠标坐标。"""
|
||
return cursor_pos()
|
||
|
||
|
||
def size() -> Tuple[int, int]:
|
||
"""主屏物理像素尺寸。"""
|
||
return screen_size()
|
||
|
||
|
||
# ==================== 文字识别(全屏) ====================
|
||
def read_text(min_score: float = 0.0, **kwargs) -> List[TextItem]:
|
||
"""OCR 全屏文字,返回带坐标的列表。"""
|
||
return _default.read_text(min_score=min_score, **kwargs)
|
||
|
||
|
||
def find_text(text: str, **kwargs) -> Optional[TextItem]:
|
||
"""按文字找最可信的一个(全屏)。"""
|
||
return _default.find_text(text, **kwargs)
|
||
|
||
|
||
def find_all_text(text: str, **kwargs) -> List[TextItem]:
|
||
"""按文字找全部命中(全屏)。"""
|
||
return _default.find_all_text(text, **kwargs)
|
||
|
||
|
||
def text_exists(text: str, **kwargs) -> bool:
|
||
"""判断文字是否存在(全屏)。"""
|
||
return _default.text_exists(text, **kwargs)
|
||
|
||
|
||
def wait_text(text: str, timeout: float = 10.0, interval: float = 1.0, **kwargs) -> Optional[TextItem]:
|
||
"""等待文字出现(全屏)。"""
|
||
return _default.wait_text(text, timeout=timeout, interval=interval, **kwargs)
|
||
|
||
|
||
def click_text(text: str, button: str = "left", clicks: int = 1,
|
||
offset: Tuple[int, int] = (0, 0), **kwargs) -> bool:
|
||
"""按文字点击(全屏)。"""
|
||
return _default.click_text(text, button=button, clicks=clicks, offset=offset, **kwargs)
|
||
|
||
|
||
def ocr_available() -> bool:
|
||
"""OCR 依赖是否已安装。"""
|
||
return ocr.available()
|
||
|
||
|
||
# ==================== 输入 / 滚轮 / 拖拽(全屏) ====================
|
||
def paste(text: str, restore: bool = True) -> None:
|
||
"""写剪贴板 + Ctrl+V(中文最稳)。"""
|
||
clipboard.paste(text, restore=restore)
|
||
|
||
|
||
def type_text(text: str, method: str = "auto", interval: float = 0.01) -> None:
|
||
"""输入文本。"""
|
||
keys.type_text(text, method=method, interval=interval)
|
||
|
||
|
||
def press(key: str, times: int = 1, interval: float = 0.05) -> None:
|
||
"""按键。"""
|
||
keys.press(key, times=times, interval=interval)
|
||
|
||
|
||
def hotkey(*key_names: str, interval: float = 0.02) -> None:
|
||
"""组合键。"""
|
||
keys.hotkey(*key_names, interval=interval)
|
||
|
||
|
||
def scroll(notches: int = 3, at=None, horizontal: bool = False) -> None:
|
||
"""滚动滚轮(at 可传坐标或模板)。"""
|
||
_scroll(notches, at=_default._point(at) if at is not None else None, horizontal=horizontal)
|
||
|
||
|
||
def sleep(seconds: float = 1.0, random_range: Optional[Tuple[float, float]] = None) -> float:
|
||
"""等待(影刀「等待」指令):random_range=(min, max) 时在区间内随机等待,返回实际秒数。"""
|
||
if random_range:
|
||
lo, hi = float(random_range[0]), float(random_range[1])
|
||
if hi < lo:
|
||
lo, hi = hi, lo
|
||
seconds = random.uniform(lo, hi)
|
||
seconds = max(0.0, float(seconds))
|
||
time.sleep(seconds)
|
||
return seconds
|
||
|
||
|
||
def send_keys(keys_text: str, interval: float = 0.02, delay_after: float = 0.0) -> None:
|
||
"""发送按键串,兼容影刀写法:`{ENTER}`、`^a`(Ctrl+A)、`%{F4}`、`abc{ENTER}`。"""
|
||
keys.send_keys(keys_text, interval=interval, delay_after=delay_after)
|
||
|
||
|
||
def move_mouse(x: int, y: int, relative_to: str = "screen",
|
||
speed: str = "instant", window=None) -> Tuple[int, int]:
|
||
"""移动鼠标;relative_to="window" 时按窗口左上角算偏移(需传 window 或 hwnd)。"""
|
||
return _move_mouse(x, y, relative_to=relative_to, speed=speed, window=window)
|
||
|
||
|
||
def drag(src, dst, duration: float = 0.5, button: str = "left") -> None:
|
||
"""拖拽(src/dst 可传坐标或模板)。"""
|
||
_drag(_default._point(src), _default._point(dst), duration=duration, button=button)
|
||
|
||
|
||
def find_any(templates, **kwargs):
|
||
"""在一组模板里找最像的一个,返回 (命中, 模板名)。"""
|
||
return _default.find_any(templates, **kwargs)
|
||
|
||
|
||
def find_color(color, **kwargs):
|
||
"""找指定颜色的区域(全屏)。"""
|
||
return _default.find_color(color, **kwargs)
|
||
|
||
|
||
def diff(baseline, **kwargs):
|
||
"""与当前画面比对(全屏)。"""
|
||
return _default.diff(baseline, **kwargs)
|
||
|
||
|
||
def hover(target, offset: Tuple[int, int] = (0, 0), **kwargs) -> bool:
|
||
"""鼠标悬停在图像/坐标上(不点击)。"""
|
||
return _default.hover(target, offset=offset, **kwargs)
|
||
|
||
|
||
def hover_text(text: str, offset: Tuple[int, int] = (0, 0), **kwargs) -> bool:
|
||
"""鼠标悬停在文字上(不点击)。"""
|
||
return _default.hover_text(text, offset=offset, **kwargs)
|
||
|
||
|
||
def wait_gone(template: Template, timeout: float = 10.0, interval: float = 0.5, **kwargs) -> bool:
|
||
"""等待图像消失。"""
|
||
return _default.wait_gone(template, timeout=timeout, interval=interval, **kwargs)
|
||
|
||
|
||
def wait_all(templates: Sequence[Template], timeout: float = 10.0,
|
||
interval: float = 0.5, **kwargs) -> bool:
|
||
"""等待所有模板都出现(影刀「等待所有图像」)。"""
|
||
return _default.wait_all(templates, timeout=timeout, interval=interval, **kwargs)
|
||
|
||
|
||
def wait_any(templates: Sequence[Template] = (), texts: Sequence[str] = (),
|
||
timeout: float = 10.0, interval: float = 0.5, **kwargs) -> Optional[dict]:
|
||
"""等待「任一图/任一文字」出现。"""
|
||
return _default.wait_any(templates=templates, texts=texts, timeout=timeout,
|
||
interval=interval, **kwargs)
|
||
|
||
|
||
def ocr_text(sep: str = "\n", **kwargs) -> str:
|
||
"""通用文字识别(只要文本,不含坐标)。"""
|
||
return _default.ocr_text(sep=sep, **kwargs)
|
||
|
||
|
||
# ==================== RPA 指令式别名(语义对齐常见 RPA 工具) ====================
|
||
image_exists = exists # 条件判断:图像是否存在
|
||
wait_image = wait # 等待:等待图像
|
||
wait_text_exists = wait_text # 等待:等待文字
|
||
click_image = click # 鼠标键盘:点击图像
|
||
hover_image = hover # 鼠标键盘:鼠标悬停在图像上
|
||
ocr_text_with_position = read_text # AI/OCR:通用文字识别(含位置)
|