feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,433 @@
|
||||
# desktopauto —— 桌面自动化库
|
||||
|
||||
面向「拿不到元素树」的桌面程序:识图点击、文字定位、键鼠操作、窗口与进程管理,多插件、工作流、脚本共用。
|
||||
只依赖 `opencv-python + numpy + pillow`(OCR 另需 `rapidocr` + `onnxruntime`),Windows 下用 ctypes 调系统 API,**不依赖 pyautogui / pywin32 / 任何底座代码**。
|
||||
|
||||
> 配套技能:`.trae/skills/37du-Desktop-Auto/SKILL.md`(AI 使用总纲 + `references/api-reference.md` 完整签名)。
|
||||
> 本库原名 `screenvision`,已整体改名为 `desktopauto`(未发布、无历史引用)。
|
||||
|
||||
## 能力
|
||||
|
||||
| 能力 | 接口 |
|
||||
|---|---|
|
||||
| 识图是否存在 | `exists(tpl)` |
|
||||
| 找最佳命中(含坐标/相似度) | `find(tpl)` |
|
||||
| 找全部命中 | `find_all(tpl)` |
|
||||
| 等图出现(超时返回 None) | `wait(tpl, timeout=30)` |
|
||||
| 识图点击(找到即点中心) | `click(tpl)` |
|
||||
| 点坐标 | `click_at(x, y)` |
|
||||
| 截图(全屏/区域/窗口) | `screenshot(path)` |
|
||||
| **离线图片标记**(不碰屏幕,框出命中位置) | `mark(image, [tpl1, tpl2], out_path)` |
|
||||
| **文字识别取坐标** | `read_text()` → `[TextItem(text, center, score)]` |
|
||||
| **按文字判断/等待/点击** | `text_exists("导出")` / `wait_text` / `click_text` |
|
||||
| **多状态按钮** | `find_any([tpl可用, tpl禁用])` → `(命中, 模板名)` |
|
||||
| **输入文本(中文)** | `paste("内容")`(写剪贴板+Ctrl+V)/ `type_text` |
|
||||
| **按键 / 组合键** | `press("enter")` / `hotkey("ctrl","s")` |
|
||||
| **按键串(影刀写法)** | `send_keys("^a{ENTER}")` / `send_keys("%{F4}")` |
|
||||
| **移动鼠标** | `move_mouse(x, y, relative_to="window")`(支持 instant/fast/middle/slow) |
|
||||
| **等待(含随机)** | `sleep(1.5)` / `sleep(random_range=(1, 3))` |
|
||||
| **文件 / 文件夹** | `fs.exists / write_text / read_text / copy / move / list_files / newest_file / wait_file` |
|
||||
| **等所有图都出现** | `wait_all([a, b], timeout=20)` |
|
||||
| **滚轮 / 拖拽** | `scroll(notches, at=tpl)` / `drag(起点, 终点)`(起点终点可传模板) |
|
||||
| **找色** | `find_color("#FF3B30", tolerance=12)` → `[ColorMatch]` |
|
||||
| **界面差异** | `diff(基准图)` → 变化比例 + 变化区域框 |
|
||||
| 窗口多条件查找 | `find_windows(process="DingTalk.exe")`、`wait_window`、`child_windows` |
|
||||
| 限定窗口 / 区域 | `Screen(window="钉钉")`、`Screen(region=(l,t,r,b))` |
|
||||
|
||||
特性:多尺度匹配(跨 DPI 复用同一套模板)、多目标 + NMS 去重、低纹理模板自动降级为平方差匹配(防纯色误命中)、透明 PNG 白底合成、命中/未命中调试图落盘、DPI 感知(125%/150% 缩放坐标不偏移)。
|
||||
|
||||
## 安装
|
||||
|
||||
```powershell
|
||||
# 开发机 / .venv
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe -m pip install -e libs\desktopauto
|
||||
|
||||
# 执行机便携环境包(推荐:装一次,所有插件都能 import)
|
||||
d:\work\code\37duAutomation\desktop\electron-shell\python-env\<版本>\python.exe -m pip install d:\work\code\37duAutomation\libs\desktopauto
|
||||
|
||||
# 文字识别(OCR)依赖:RapidOCR + onnxruntime,模型随包内置,离线可用
|
||||
pip install rapidocr onnxruntime
|
||||
```
|
||||
|
||||
装好后任何脚本/插件直接 `import desktopauto`。
|
||||
|
||||
> 只用「识图」(模板匹配)时不需要装 OCR;`ocr_available()` 可探测。
|
||||
|
||||
### 插件里怎么用(三种接入方式)
|
||||
|
||||
| 方式 | 做法 | 适用 |
|
||||
|---|---|---|
|
||||
| **A. 环境包预装**(推荐) | 执行机环境包 `pip install desktopauto`,插件 `requirements.txt` 里写 `desktopauto`(仅声明意图,不重复装) | 多插件共用,升级只动一处 |
|
||||
| **B. 打包进插件** | 把 `desktopauto/` 目录复制到插件包内,插件内相对导入 | 需要插件包完全自包含、离线拷走即用 |
|
||||
| **C. 开发期 sys.path** | `sys.path.insert(0, r"d:\work\code\37duAutomation\libs\desktopauto")` | 本地调试图省事,**不要进发布包** |
|
||||
|
||||
> 注意:项目规范要求「插件包内不得 import 插件之外的代码」。选 A 时要在插件 README/规范里明确 `desktopauto` 属于**执行机预装依赖**(与 requests/pandas 同级),不是跨目录 import 业务代码;选 B 则天然合规。
|
||||
|
||||
## 快速上手
|
||||
|
||||
```python
|
||||
from desktopauto import Screen
|
||||
|
||||
s = Screen() # 全屏
|
||||
if s.exists("img/btn_save.png"): # 识图:是否存在
|
||||
print("按钮在")
|
||||
|
||||
s.click("img/btn_save.png") # 识图点击:找到才点,找不到返回 False
|
||||
|
||||
# 限定窗口(标题模糊匹配,自动排除最小化窗口)+ 等图出现
|
||||
ding = Screen(window="钉钉", threshold=0.9, debug_dir="debug")
|
||||
ding.activate()
|
||||
hit = ding.wait("img/chat_input.png", timeout=30)
|
||||
if not hit:
|
||||
raise RuntimeError("钉钉窗口没准备好")
|
||||
ding.click("img/chat_input.png")
|
||||
print(hit.center, hit.score) # (x, y) 屏幕物理像素、相似度
|
||||
|
||||
# 一个窗口里同款图标有多个时
|
||||
for m in ding.find_all("img/row_more.png"):
|
||||
ding.click_at(*m.center)
|
||||
```
|
||||
|
||||
临时覆盖参数(不改实例配置):
|
||||
|
||||
```python
|
||||
s.find("a.png", threshold=0.95, window="WPS", region=(0, 0, 800, 600))
|
||||
s.find_all("a.png", scales=(0.9, 1.0, 1.1), max_results=5) # 跨 DPI 找图
|
||||
```
|
||||
|
||||
## RPA 指令对照(按常见 RPA 工具的分类)
|
||||
|
||||
| 指令 | 本库 | 返回 |
|
||||
|---|---|---|
|
||||
| 条件判断 · IF 图像存在 | `image_exists(tpl)` | `bool` |
|
||||
| 条件判断 · IF 文字存在 | `text_exists("导出")` | `bool` |
|
||||
| 条件判断 · IF 颜色存在 | `s.color_exists("#FF3B30")` | `bool` |
|
||||
| 等待 · 等待图像 | `wait_image(tpl, timeout=10)` | `Match` / `None` |
|
||||
| 等待 · 等待图像消失 | `wait_gone(tpl, timeout=10)` | `bool` |
|
||||
| 等待 · 等待文字 | `wait_text_exists("成功", timeout=10)` | `TextItem` / `None` |
|
||||
| 等待 · 等待任一(图或文字) | `wait_any(templates=[a, b], texts=["成功","失败"], timeout=30)` | `{kind, target, match}` / `None` |
|
||||
| AI/OCR · 通用文字识别 | `ocr_text()` | `str`(纯文本,适合喂 LLM) |
|
||||
| AI/OCR · 通用文字识别(含位置) | `ocr_text_with_position()` = `read_text()` | `[TextItem]`(含坐标/置信度) |
|
||||
| 鼠标键盘 · 点击图像 | `click_image(tpl)` | `bool`(找到才点) |
|
||||
| 鼠标键盘 · 鼠标悬停在图像上 | `hover_image(tpl)` | `bool`(不点击) |
|
||||
| 鼠标键盘 · 悬停到文字 | `hover_text("导出")` | `bool` |
|
||||
| 鼠标键盘 · 输入文本 | `paste(text)` / `type_text(text)` | `None` |
|
||||
| 鼠标键盘 · 按键 / 组合键 | `press("enter")` / `hotkey("ctrl","s")` | `None` |
|
||||
| 鼠标键盘 · 滚轮 / 拖拽 | `scroll(-5, at=tpl)` / `drag(tpl, (x,y))` | `None` |
|
||||
|
||||
一次典型串联:
|
||||
|
||||
```python
|
||||
from desktopauto import (Screen, click_image, paste, hotkey,
|
||||
wait_any, ocr_text)
|
||||
|
||||
s = Screen(window="钉钉", threshold=0.9, debug_dir="debug")
|
||||
s.activate()
|
||||
|
||||
if not s.exists("img/dialog_closed.png"): # 条件判断
|
||||
s.click("img/btn_close.png")
|
||||
|
||||
s.click("img/chat_input.png")
|
||||
paste("排班识别,水庄大鹅……") # 中文输入
|
||||
hotkey("ctrl", "enter")
|
||||
|
||||
r = wait_any(texts=["发送成功", "发送失败"], timeout=20) # 等任一结果
|
||||
print(r["kind"], r["target"], r["match"].center if r else None)
|
||||
print(ocr_text()) # 整屏文字(含坐标用 ocr_text_with_position)
|
||||
```
|
||||
|
||||
## 输入:文本 / 按键 / 滚轮 / 拖拽
|
||||
|
||||
```python
|
||||
from desktopauto import Screen, keys, clipboard
|
||||
|
||||
s = Screen(window="钉钉")
|
||||
s.activate()
|
||||
s.click("img/chat_input.png") # 先点中输入框
|
||||
s.paste("排班识别,水庄大鹅……") # 中文走剪贴板 + Ctrl+V,最稳
|
||||
s.hotkey("ctrl", "enter") # 组合键发送
|
||||
s.send_keys("^a{DELETE}") # 影刀写法:全选后删除(^ = Ctrl,{KEY} = 单键)
|
||||
s.press("tab", times=2) # 单键/连按
|
||||
s.move_mouse(320, 180, relative_to="window") # 相对窗口坐标移动鼠标
|
||||
|
||||
# 影刀「点击图像」的参数也能直接对上:timeout 等图、delay_after 点后延时、anchor 九宫格
|
||||
s.click("images/提交申报按钮.png", timeout=5, delay_after=1, anchor="center")
|
||||
s.type_text("A001", method="unicode") # 纯英文可逐字符注入
|
||||
s.scroll(-5, at="img/list_area.png") # 在指定位置向下滚 5 格
|
||||
s.drag("img/slider.png", (600, 400)) # 拖拽:起点可传模板,终点传坐标
|
||||
|
||||
print(clipboard.get_text()) # 读剪贴板(比 OCR 准:先 Ctrl+A/Ctrl+C)
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- **中文一律 `paste`**(写剪贴板 + Ctrl+V)。`type_text` 默认 `method="auto"`,含非 ASCII 时自动走剪贴板;
|
||||
- `paste(restore=True)` 会在粘贴后**恢复你原来的剪贴板内容**;
|
||||
- `press`/`hotkey` 只支持命名键 + 字母/数字/F1~F12;**符号请用 `type_text`**(避免键盘布局差异);
|
||||
- 目标窗口以管理员权限运行时,普通权限进程的输入会被 UIPI 拦截(`SendInput` 返回 0,库会抛错说明原因)。
|
||||
|
||||
## 窗口对象(RPA 的「获取窗口对象」「激活软件窗口」)
|
||||
|
||||
```python
|
||||
from desktopauto import get_window, foreground_window, activate_window
|
||||
|
||||
# 获取窗口对象:按进程/标题/PID/类名,找不到直接抛错(提示写明条件)
|
||||
w = get_window(process="DingTalk.exe")
|
||||
w = get_window(title="银行", exact=True) # 标题精确匹配
|
||||
w = get_window(process="DingTalk", index=1) # 同进程第二个窗口
|
||||
w = get_window(title="导出", timeout=15) # 等它出现再返回
|
||||
|
||||
print(w.title, w.pid, w.process, w.rect, w.center)
|
||||
w.activate() # 激活软件窗口(还原+置前)
|
||||
w.is_foreground() # 是否在前台
|
||||
w.maximize().move(0, 0) # 最大化/移动(链式)
|
||||
w.wait_ready(timeout=10) # 等可见且非最小化
|
||||
|
||||
s = w.screen(threshold=0.9, debug_dir="debug") # 直接拿到绑定该窗口的 Screen
|
||||
s.click("img/btn_send.png")
|
||||
|
||||
w.screenshot("w.png") # 只截这个窗口
|
||||
w.children() # 子窗口列表
|
||||
w.close(); w.wait_closed(timeout=10) # 关闭并等它消失
|
||||
w.exists() # 窗口是否还在(不抛错)
|
||||
|
||||
foreground_window() # 当前前台窗口对象
|
||||
activate_window("钉钉") # 也可直接用函数式激活
|
||||
```
|
||||
|
||||
`Window` 的属性都是实时读取的:窗口被手动关掉后,访问 `title` 会抛错,用 `exists()` 先判断。
|
||||
|
||||
### 关闭窗口的三种力度
|
||||
|
||||
```python
|
||||
from desktopauto import close_window
|
||||
|
||||
close_window("钉钉") # ① 函数式:发 WM_CLOSE(等同点 ×)
|
||||
w.close() # ② 对象式,同上
|
||||
w.close(); w.wait_closed(timeout=10) # ③ 关完等它真的消失(返回 bool)
|
||||
|
||||
w.kill() # ④ 强杀:TerminateProcess 整个进程(应用无响应/有确认弹框时用)
|
||||
```
|
||||
|
||||
- `close()` 只是**发消息**,应用若弹「是否保存」不会自动处理,需要你再点一下;
|
||||
- `kill()` 会**杀掉整个进程**(该应用所有窗口一起没,未保存数据会丢),仅在卡死时用;
|
||||
- 判断关没关掉一律用 `w.exists()` / `w.wait_closed()`,别用 sleep 猜。
|
||||
|
||||
## 运行或打开 / 终止程序
|
||||
|
||||
```python
|
||||
from desktopauto import (run_or_open, launch, open_path, open_url, is_running,
|
||||
wait_process, list_processes, kill_process, get_window)
|
||||
|
||||
run_or_open(r"D:\Program\DingTalk\DingTalk.exe") # 启动 exe
|
||||
run_or_open(r"D:\资料\工资卡核对结果.xlsx") # 用默认程序打开(WPS/Excel)
|
||||
open_url("https://hr.37du.co") # 打开网址
|
||||
|
||||
# 启动 → 等进程 → 拿窗口 → 操作
|
||||
run_or_open("notepad.exe", wait=1)
|
||||
wait_process("notepad", timeout=10) # 等进程出现
|
||||
w = get_window(title="记事本", timeout=10).activate()
|
||||
|
||||
# 终止
|
||||
kill_process("notepad") # 同名全部终止
|
||||
kill_process(w) # 按窗口对象(终止其进程)
|
||||
kill_process(12345) # 按 pid
|
||||
```
|
||||
|
||||
| 函数 | 说明 |
|
||||
|---|---|
|
||||
| `run_or_open(target, args=(), wait=0)` | `.exe/.bat/.cmd/.com` → 启动返回 Popen;文档/文件夹/网址 → 默认程序打开 |
|
||||
| `launch(exe, args=(), cwd=None, wait=0)` | 只启动程序,返回 Popen(可 `.poll()` / `.terminate()`) |
|
||||
| `open_path(path)` / `open_url(url)` | 用系统默认程序打开 |
|
||||
| `list_processes(name="")` | 进程列表 `[{pid, name, path}]` |
|
||||
| `is_running(name)` | 是否在运行(名称包含匹配) |
|
||||
| `wait_process(name, timeout, until="start")` | 等启动;`until="exit"` 等退出 |
|
||||
| `kill_process(pid / 名称 / Window)` | 终止程序(同名全部杀;找不到抛错) |
|
||||
|
||||
注意:
|
||||
|
||||
- `kill_process` 走 `TerminateProcess`,**不给应用保存机会**;
|
||||
- 只想关一个窗口用 `w.close()`,别为了关窗口把整个进程杀了;
|
||||
- 终止失败多为权限问题:目标以管理员运行、本进程不是 → 会抛错说明。
|
||||
|
||||
## 窗口定位:别只靠标题
|
||||
|
||||
```python
|
||||
from desktopauto import find_windows, wait_window, child_windows, window_info, activate_window
|
||||
|
||||
find_windows(process="DingTalk.exe") # 按进程名(不区分大小写、包含匹配)
|
||||
find_windows(title="工资卡核对结果", exact=True) # 标题精确匹配(Excel 标题带文件名时用)
|
||||
find_windows(pid=27600) # 按 PID
|
||||
find_windows(class_name="Chrome_WidgetWin_1") # 按窗口类名
|
||||
find_windows(title="钉钉", include_minimized=True) # 连最小化的一起列
|
||||
|
||||
w = wait_window(title="导出", timeout=15) # 等弹窗出现,返回窗口信息或 None
|
||||
print(w["title"], w["pid"], w["process"], w["rect"])
|
||||
|
||||
for c in child_windows(w["hwnd"]): # 子窗口(内嵌控件/弹层)
|
||||
print(c["class_name"], c["title"], c["rect"])
|
||||
```
|
||||
|
||||
> 实测钉钉客户端:`DingTalk.exe` / 类名 `Qt51511QWindowIcon` / 76 个子窗口 HWND,
|
||||
> 但没有可用的 UIA 元素树 —— 这正是「图 + 文字」路线要解决的问题。
|
||||
|
||||
## 找色与界面差异
|
||||
|
||||
```python
|
||||
from desktopauto import find_color, diff
|
||||
|
||||
# 找红色状态点(RGB,容差 20),只要面积最大的 3 块
|
||||
for c in find_color("#FF3B30", tolerance=20, min_area=8, max_results=3):
|
||||
print(c.center, c.area)
|
||||
|
||||
# 判断界面有没有变化(比「找具体元素」更鲁棒;也能判断卡死/无响应)
|
||||
base = "img/state_before.png"
|
||||
r = diff(base, tolerance=12, min_area=50)
|
||||
print(r["changed"], r["changed_ratio"], r["boxes"])
|
||||
```
|
||||
|
||||
`Screen` 上还有 `s.find_color(...)` / `s.color_exists(...)` / `s.diff(baseline)`,会按实例的窗口/区域截图。
|
||||
|
||||
## 命令行(不写代码先验证)
|
||||
|
||||
```powershell
|
||||
# 截图(用来裁模板)
|
||||
python -m desktopauto --mode shot --path img/btn.png --window "钉钉"
|
||||
|
||||
# 判断是否存在(退出码 0=存在,1=不存在,2=出错)
|
||||
python -m desktopauto -t img/btn.png --mode exists
|
||||
|
||||
# 识图点击 + 打调试图
|
||||
python -m desktopauto -t img/btn.png --mode click --window "钉钉" --debug-dir debug
|
||||
|
||||
# 离线标记:在一张截图里找多个模板,框出命中位置(不动真实鼠标)
|
||||
python -m desktopauto --mode mark -i shot.png -t "img/a.png,img/b.png" -o marked.png
|
||||
```
|
||||
|
||||
## 离线标记(先用标记验证,再上真实点击)
|
||||
|
||||
上线前不想真点鼠标时,用 `mark()` 拿一张截图先预演:
|
||||
|
||||
```python
|
||||
from desktopauto import mark, summarize
|
||||
|
||||
result = mark(r"C:\Users\admin\Downloads\1.png",
|
||||
[r"C:\Users\admin\Downloads\2.png", r"C:\Users\admin\Downloads\3.png"],
|
||||
out_path="marked.png", threshold=0.85)
|
||||
print(summarize(result))
|
||||
# 图片尺寸:1920x1032,命中合计 2 处
|
||||
# #1 2.png:1 处 score=1.000 框=(148,395) 57x46 点击点=(176, 418)
|
||||
# #2 3.png:1 处 score=1.000 框=(2,372) 102x30 点击点=(53, 387)
|
||||
```
|
||||
|
||||
标注图上:绿/蓝/橙框 = 不同模板的命中框,框中心十字 = 真实 `click()` 会落下的位置。
|
||||
确认标记位置都对,再把同样的模板交给 `Screen(...).click(...)` 真跑。
|
||||
|
||||
输出统一 JSON:`{"ok": true, "match": {"left":..,"top":..,"score":..,"center":[x,y]}}`。
|
||||
|
||||
## 文字识别取坐标(OCR)
|
||||
|
||||
```python
|
||||
from desktopauto import Screen, match_text
|
||||
|
||||
s = Screen() # 建议 Screen(window="钉钉") 限定窗口,又快又准
|
||||
items = s.read_text() # 一次 OCR 拿全量:每项有 text / left / top / width / height / score / center
|
||||
for it in items[:5]:
|
||||
print(it.text, it.center)
|
||||
|
||||
hit = s.find_text("导出") # 包含匹配 + 忽略大小写与空白,返回最可信的一条
|
||||
print(hit.text, hit.center, hit.score)
|
||||
|
||||
s.text_exists("提交") # 文字是否存在(不点击)
|
||||
s.wait_text("导出成功", timeout=30) # 等文字出现
|
||||
s.click_text("导出") # 按文字点击其中心
|
||||
|
||||
# 一屏要查多个词:先 read_text() 拿一次再本地过滤,别反复 OCR
|
||||
items = s.read_text()
|
||||
for kw in ("导出", "刷新", "设置"):
|
||||
print(kw, [t.center for t in match_text(items, kw)])
|
||||
```
|
||||
|
||||
匹配规则:默认「包含 + 忽略大小写 + 忽略空白」(OCR 常在字间插空格,`AI 表格` 能命中 `AI表格`);`exact=True` 精确相等,`regex=True` 正则。
|
||||
|
||||
CLI:
|
||||
|
||||
```powershell
|
||||
# 列出识别到的文字(带坐标),limit 控制输出条数
|
||||
python -m desktopauto --mode ocr --limit 20
|
||||
|
||||
# 在一张截图上找文字并高亮标注(目标绿框,其余淡框)
|
||||
python -m desktopauto --mode ocr -i 1.png --text "导出,提交" -o hit.png
|
||||
|
||||
# 实时截屏 + 限定窗口 + 只找某个词
|
||||
python -m desktopauto --mode ocr --window "钉钉" --text "工作台"
|
||||
```
|
||||
|
||||
性能与坑:
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 速度 | 1920×1080 整屏约 2~4s(CPU);限定 `window/region` 后通常 <1s。引擎首次加载约 0.5s,之后复用 |
|
||||
| 精度 | 小字(<10px)、深色底白字、艺术字容易错;关键操作用「包含 + 短关键词」,别整句精确匹配 |
|
||||
| 坐标 | 实时截图返回**屏幕物理像素**,可直接 `click_text`;离线图(`mark` / `--image`)返回图内坐标 |
|
||||
| 稳定性 | OCR 是「看图」不是无障碍接口,界面改版就可能失效;重要流程建议「模板匹配 + OCR」互为兜底 |
|
||||
|
||||
## 模板图怎么准备
|
||||
|
||||
1. 用 `--mode shot` 截一张,再用画图工具裁出**目标区域**(比目标稍大一点、带完整边框/图标);
|
||||
2. 模板要**有可辨识特征**:纯色/近似纯色的图块会被自动降级为像素匹配,容易在别处命中;
|
||||
3. 避免把**会变的内容**裁进去(时间、数字、用户名、红点角标);
|
||||
4. 同一元素在不同缩放机器上复用时,用 `scales=(0.8, 0.9, 1.0, 1.1, 1.25)`,或按机器各截一份;
|
||||
5. 命中不稳定时先看 `debug_dir` 里的 `hit_*/miss_*.png`(带匹配框和分数),比盲调阈值快。
|
||||
|
||||
## 常见坑
|
||||
|
||||
| 现象 | 原因 / 处理 |
|
||||
|---|---|
|
||||
| 图在屏幕上但点偏了 | 进程 DPI 未感知;本库首次调用已自动 `SetProcessDpiAwareness(2)`。若在别的进程里混用(如先被别的库改了 DPI 感知),需重启进程 |
|
||||
| 截出来是黑屏 | 远程桌面断开 / 锁屏 / 会话未交互;RPA 执行机要保持在已登录且解锁的会话 |
|
||||
| 窗口被别的窗口挡住还能找到? | 不能——本库截的是**屏幕实际显示内容**,不是窗口离屏渲染。点击前用 `activate()` |
|
||||
| 多显示器坐标是负的 | 正常,Windows 虚拟屏幕坐标;`grab()` 全屏包含所有屏幕 |
|
||||
| 相似度 0.85 命中了错的地方 | 提高阈值(0.9~0.95)、缩小 `window/region` 范围、或换更有特征的模板 |
|
||||
| 同款元素多个命中 | 用 `find_all()` 按坐标排序后取第 N 个,别用 `find()` 猜 |
|
||||
| 输入没反应 | 目标窗口以管理员运行 → UIPI 拦截;或窗口没焦点(先 `activate()` 再点目标) |
|
||||
| 粘贴出的是旧内容 | 写剪贴板后立即 Ctrl+V 有竞争,`paste(delay=0.15)` 加延迟;或 `restore=False` 别急着恢复 |
|
||||
| 窗口最小化/被挡时点不到 | 点击是物理坐标,窗口必须可见且在前台;最小化窗口会被 `find_windows` 默认排除 |
|
||||
|
||||
## 从影刀工程迁移
|
||||
|
||||
影刀工程导出的目录(含 `imagesV2.xml` + `resources/images/*.png` + `process*.py`)可以直接复用:
|
||||
|
||||
1. **模板图不用重截**:`scripts/import_yingdao_images.py` 解析 `imagesV2.xml`,把 45 个模板按中文名导出,
|
||||
并把 `similarity=80` → `threshold=0.8`、`graying=False` → `gray=False`、`adaptive=True` → `scales=(0.9,1.0,1.1)`
|
||||
一起写进 `manifest.json`:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe libs\desktopauto\scripts\import_yingdao_images.py
|
||||
# 输出:%LOCALAPPDATA%\37duAutomation\desktopauto_templates\<工程名>\images\*.png + manifest.json
|
||||
```
|
||||
|
||||
2. **指令对照**(影刀 → 本库):
|
||||
|
||||
| 影刀 | 本库 |
|
||||
|---|---|
|
||||
| `image.click(timeout, delay_after, anchor_type, offset_x/y, clicks, button)` | `click(tpl, timeout=, delay_after=, anchor=, offset=, clicks=, button=)` |
|
||||
| `image.wait(wait_mode="appear"/"disappear", is_wait_all_images)` | `wait()` / `wait_gone()` / `wait_all()` |
|
||||
| `image.exist(exist_mode, is_find_all_images)` | `exists()` / `find_all()` |
|
||||
| `win32.send_keys(keys="{ENTER}")` | `send_keys("{ENTER}")` |
|
||||
| `win32.move_mouse(point_x, point_y, relative_to, move_speed)` | `move_mouse(x, y, relative_to="screen"/"window", speed=)` |
|
||||
| `programing.sleep(seconds, random_number, start/stop_number)` | `sleep(s)` / `sleep(random_range=(lo, hi))` |
|
||||
| `file.if_exist(path, expect_exist)` | `fs.exists(path)` |
|
||||
| `dir.makedir(parent, name)` | `fs.make_dir(parent, name)` |
|
||||
| `system.run_or_open` / `terminal_process` | `run_or_open()` / `kill_process()` |
|
||||
| `process.run` / `invoke_module`(流程/调 Python 模块) | 直接用 Python 函数调用,不需要迁 |
|
||||
|
||||
3. **view_coordinates.py**(影刀里查按钮坐标的辅助流程):用 `read_text()` + `click_text()` 或 `mark()` 标注替代。
|
||||
|
||||
## 自测
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe libs\desktopauto\_selftest.py
|
||||
```
|
||||
|
||||
用合成图验证:精确匹配、坐标换算、区域偏移、多目标、低纹理防误命中、多尺度、透明 PNG、调试图输出(不需要真实桌面)。
|
||||
@@ -0,0 +1,297 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""离线自测:用合成图验证匹配算法(不需要真实桌面、不点鼠标)。
|
||||
|
||||
运行:
|
||||
.venv\\Scripts\\python.exe libs\\desktopauto\\_selftest.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from desktopauto import matcher as m # noqa: E402 # pyright: ignore[reportImplicitRelativeImport]
|
||||
|
||||
TMP = tempfile.mkdtemp(prefix="desktopauto_selftest_")
|
||||
_passed = 0
|
||||
|
||||
|
||||
def ok(cond: bool, msg: str) -> None:
|
||||
global _passed
|
||||
if not cond:
|
||||
raise AssertionError(f"[FAIL] {msg}")
|
||||
_passed += 1
|
||||
print(f"[PASS] {msg}")
|
||||
|
||||
|
||||
def build_desktop() -> np.ndarray:
|
||||
"""合成一张「界面」:灰底 + 两个相同的蓝色按钮 + 一个绿色区块。"""
|
||||
img = np.full((600, 800, 3), 240, dtype=np.uint8)
|
||||
for (x, y) in ((100, 100), (500, 300)):
|
||||
cv2.rectangle(img, (x, y), (x + 80, y + 30), (200, 120, 40), -1)
|
||||
cv2.putText(img, "OK", (x + 22, y + 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
|
||||
cv2.rectangle(img, (60, 420), (240, 500), (60, 180, 75), -1)
|
||||
cv2.putText(img, "SUBMIT", (70, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
|
||||
return img
|
||||
|
||||
|
||||
def main() -> int:
|
||||
desktop = build_desktop()
|
||||
shot_path = os.path.join(TMP, "desktop.png")
|
||||
ok(bool(cv2.imwrite(shot_path, desktop)), "生成合成界面图")
|
||||
|
||||
# ---- 1. 精确匹配:两个相同按钮应都找到 ----
|
||||
tpl = desktop[100:130, 100:180].copy()
|
||||
tpl_path = os.path.join(TMP, "btn_ok.png")
|
||||
ok(bool(cv2.imwrite(tpl_path, tpl)), "裁出按钮模板")
|
||||
|
||||
hits = m.match_in(desktop, tpl_path, threshold=0.85)
|
||||
ok(len(hits) == 2, f"同款按钮命中 2 处(实际 {len(hits)})")
|
||||
ok(hits[0].score > 0.99, f"最佳相似度 > 0.99(实际 {hits[0].score:.4f})")
|
||||
coords = sorted([(h.left, h.top) for h in hits])
|
||||
ok(coords == [(100, 100), (500, 300)], f"命中坐标正确:{coords}")
|
||||
ok(hits[0].center == (hits[0].left + 40, hits[0].top + 15), "中心点 = 框中心")
|
||||
|
||||
# ---- 2. 纯色模板:走平方差匹配,只命中同色区域、不误命中彩色按钮 ----
|
||||
blank = np.full_like(tpl, 255)
|
||||
hits_blank = m.match_in(desktop, blank, threshold=0.9)
|
||||
on_button = [h for h in hits_blank
|
||||
if abs(h.left - 100) < 20 and abs(h.top - 100) < 20]
|
||||
ok(not on_button, "纯色模板不会误命中彩色按钮(走平方差匹配)")
|
||||
ok(all(desktop[h.top + 15, h.left + 5].min() > 200 for h in hits_blank),
|
||||
"纯色模板只命中同色区域")
|
||||
|
||||
# ---- 3. max_results 截断 ----
|
||||
hits_one = m.match_in(desktop, tpl_path, threshold=0.85, max_results=1)
|
||||
ok(len(hits_one) == 1, "max_results=1 只返回一条")
|
||||
|
||||
# ---- 4. 区域截图偏移:origin 参与坐标换算 ----
|
||||
crop = desktop[80:360, 60:660]
|
||||
hits_roi = m.match_in(crop, tpl_path, threshold=0.85, origin=(60, 80))
|
||||
ok(len(hits_roi) == 2, "区域匹配仍命中 2 处")
|
||||
ok(sorted([(h.left, h.top) for h in hits_roi]) == [(100, 100), (500, 300)],
|
||||
"区域匹配坐标已加原点偏移(可直接用于点击)")
|
||||
|
||||
# ---- 5. 多尺度:界面被放大 1.25 倍(模拟不同 DPI) ----
|
||||
big = cv2.resize(desktop, None, fx=1.25, fy=1.25, interpolation=cv2.INTER_LINEAR)
|
||||
hits_scale = m.match_in(big, tpl_path, threshold=0.8, scales=(1.0, 1.15, 1.25))
|
||||
ok(len(hits_scale) >= 2, f"跨 DPI 多尺度命中(实际 {len(hits_scale)} 处)")
|
||||
ok(abs(hits_scale[0].left - 125) <= 3, f"放大后坐标按物理像素换算正确(left={hits_scale[0].left})")
|
||||
|
||||
# ---- 6. 透明 PNG:透明区合成白底后仍可匹配 ----
|
||||
rgba = np.zeros((30, 80, 4), dtype=np.uint8)
|
||||
rgba[:, :, :3] = [200, 120, 40]
|
||||
rgba[:, :, 3] = 255
|
||||
rgba[0:6, :, 3] = 0 # 顶部 6 行透明
|
||||
tpl_rgba_path = os.path.join(TMP, "btn_alpha.png")
|
||||
ok(bool(cv2.imwrite(tpl_rgba_path, rgba)), "生成带透明通道的模板")
|
||||
loaded = m.load_template(tpl_rgba_path)
|
||||
ok(loaded.shape[2] == 3, "透明 PNG 已合成三通道")
|
||||
ok(int(loaded[0, 0, 0]) == 255, "透明区域按白底合成")
|
||||
|
||||
# ---- 7. 调试图输出 ----
|
||||
dbg = m.annotate(desktop, hits)
|
||||
dbg_path = os.path.join(TMP, "debug.png")
|
||||
ok(bool(cv2.imwrite(dbg_path, dbg)) and os.path.getsize(dbg_path) > 0, "命中框调试图可输出")
|
||||
|
||||
# ---- 8. 离线标记:多模板 + 标注图落盘(不碰真实屏幕) ----
|
||||
from desktopauto import mark, summarize # noqa: PLC0415
|
||||
submit_tpl = desktop[420:500, 60:240].copy()
|
||||
marked_path = os.path.join(TMP, "marked.png")
|
||||
res = mark(desktop, [tpl_path, submit_tpl], out_path=marked_path, threshold=0.85)
|
||||
ok(res["total"] == 3, f"标记模式命中 2+1 处(实际 {res['total']})")
|
||||
ok(res["items"][0]["count"] == 2 and res["items"][1]["count"] == 1, "按模板分组统计正确")
|
||||
ok(os.path.isfile(marked_path) and os.path.getsize(marked_path) > 0, "标注图已落盘")
|
||||
ok("点击点" in summarize(res), "summarize 输出含点击点信息")
|
||||
ok(res["items"][0]["matches"][0]["center"] in ([140, 115], [540, 315]),
|
||||
"点击点坐标与命中框对应")
|
||||
|
||||
# ---- 9. 文字识别(OCR):合成中文文字 → 识别 → 取坐标 ----
|
||||
from desktopauto import ocr as _ocr # noqa: PLC0415
|
||||
if not _ocr.available():
|
||||
print("[SKIP] 未安装 rapidocr,跳过 OCR 用例")
|
||||
else:
|
||||
from PIL import Image, ImageDraw, ImageFont # noqa: PLC0415
|
||||
font = None
|
||||
for fp in (r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\simhei.ttf",
|
||||
r"C:\Windows\Fonts\simsun.ttc"):
|
||||
if os.path.isfile(fp):
|
||||
try:
|
||||
font = ImageFont.truetype(fp, 30)
|
||||
break
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if font is None:
|
||||
print("[SKIP] 无中文字体,跳过 OCR 用例")
|
||||
else:
|
||||
canvas = np.full((220, 520, 3), 255, dtype=np.uint8)
|
||||
pil = Image.fromarray(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))
|
||||
draw = ImageDraw.Draw(pil)
|
||||
draw.text((60, 50), "导出数据", fill=(0, 0, 0), font=font)
|
||||
draw.text((60, 140), "提交审核", fill=(0, 0, 0), font=font)
|
||||
canvas = cv2.cvtColor(np.asarray(pil), cv2.COLOR_RGB2BGR)
|
||||
|
||||
items = _ocr.recognize(canvas, min_score=0.4)
|
||||
ok(len(items) >= 2, f"OCR 识别到 >=2 段文字(实际 {len(items)}:{[i.text for i in items]})")
|
||||
hit_export = _ocr.best_text(_ocr.match_text(items, "导出"))
|
||||
ok(hit_export is not None, f"按文字『导出』命中(实际 {[i.text for i in items]})")
|
||||
ok(abs(hit_export.center[0] - 120) < 80 and abs(hit_export.center[1] - 68) < 40,
|
||||
f"『导出数据』坐标接近 (120,68),实际 {hit_export.center}")
|
||||
hit_submit = _ocr.best_text(_ocr.match_text(items, "提交"))
|
||||
ok(hit_submit is not None and hit_submit.center[1] > hit_export.center[1],
|
||||
"『提交审核』在『导出数据』下方(坐标关系正确)")
|
||||
ok(_ocr.best_text(_ocr.match_text(items, "不存在的文字")) is None, "查不存在的文字返回 None")
|
||||
|
||||
# 标注图(中文标签用系统字体,避免 cv2 画中文变问号)
|
||||
marked = os.path.join(TMP, "ocr_marked.png")
|
||||
out = _ocr.mark_text(canvas, items, out_path=marked, only=[hit_export])
|
||||
ok(os.path.isfile(out) and os.path.getsize(out) > 0, "OCR 标注图已落盘")
|
||||
|
||||
# ---- 10. find_any:多模板里挑最像的一个 ----
|
||||
from desktopauto import matcher as mm # noqa: PLC0415
|
||||
other_tpl = desktop[420:500, 60:240].copy() # 绿色 SUBMIT
|
||||
hit_any, idx_any = mm.match_any_in(desktop, [other_tpl, tpl_path], threshold=0.85)
|
||||
ok(hit_any is not None and idx_any == 1, f"find_any 选中正确模板(idx={idx_any})")
|
||||
hit_none, idx_none = mm.match_any_in(desktop, [blank], threshold=0.999)
|
||||
ok(hit_none is None and idx_none == -1, "find_any 全不命中返回 (None, -1)")
|
||||
|
||||
# ---- 11. 找色:按 RGB 找连通区域 ----
|
||||
from desktopauto import colors as _colors # noqa: PLC0415
|
||||
ok(_colors.parse_color("#FF3B30") == (255, 59, 48), "parse_color 支持 #RRGGBB")
|
||||
ok(_colors.parse_color("255,59,48") == (255, 59, 48), "parse_color 支持 r,g,b 字符串")
|
||||
ok(_colors.parse_color((200, 120, 40)) == (200, 120, 40), "parse_color 支持元组")
|
||||
|
||||
btn_rgb = (40, 120, 200) # 按钮在 BGR 里是 (200,120,40) → RGB (40,120,200)
|
||||
hits_color = _colors.find_color_in(desktop, btn_rgb, tolerance=10, min_area=100)
|
||||
ok(len(hits_color) == 2, f"同色按钮识别出 2 处(实际 {len(hits_color)})")
|
||||
ok(hits_color[0].area > 1000, f"连通域面积合理({hits_color[0].area})")
|
||||
ok(all(0 <= c.center[0] <= 800 for c in hits_color), "找色坐标在图内")
|
||||
|
||||
# ---- 12. 界面差异 diff ----
|
||||
same = _colors.diff(desktop, desktop)
|
||||
ok(same["changed"] is False and same["changed_ratio"] == 0, "同一张图 diff = 0 变化")
|
||||
changed_img = desktop.copy()
|
||||
cv2.rectangle(changed_img, (600, 500), (700, 560), (0, 0, 255), -1)
|
||||
res = _colors.diff(desktop, changed_img, min_area=100)
|
||||
ok(res["changed"] is True and res["changed_ratio"] > 0, f"改动后 diff 检出变化({res['changed_ratio']})")
|
||||
ok(len(res["boxes"]) >= 1, f"变化区域有框({len(res['boxes'])} 个)")
|
||||
|
||||
# ---- 13. 键名映射(不发真实按键,避免干扰桌面) ----
|
||||
from desktopauto import keys as _keys # noqa: PLC0415
|
||||
ok(_keys.to_vk("ctrl") == 0x11 and _keys.to_vk("enter") == 0x0D, "键名映射:ctrl/enter")
|
||||
ok(_keys.to_vk("f5") == 0x74 and _keys.to_vk("a") == 0x41 and _keys.to_vk("1") == 0x31,
|
||||
"键名映射:f5/a/1")
|
||||
try:
|
||||
_keys.to_vk("/")
|
||||
ok(False, "符号键应提示改用 type_text")
|
||||
except ValueError:
|
||||
ok(True, "符号键给出明确提示(用 type_text)")
|
||||
|
||||
# ---- 14. RPA 指令:条件判断 / 等消失 / 悬停(不移动鼠标:目标不存在直接返回) ----
|
||||
from desktopauto import Screen as _Screen # noqa: PLC0415
|
||||
from desktopauto import image_exists, ocr_text, ocr_text_with_position # noqa: PLC0415
|
||||
scr = _Screen()
|
||||
absent = os.path.join(TMP, "no_such_target.png")
|
||||
rng = np.random.default_rng(1)
|
||||
cv2.imwrite(absent, rng.integers(0, 255, (20, 20, 3), dtype=np.uint8))
|
||||
ok(scr.wait_gone(absent, timeout=1.0, interval=0.2) is True,
|
||||
"wait_gone:目标不存在立即返回 True")
|
||||
ok(scr.hover(absent) is False, "hover:目标不存在返回 False(不移动鼠标)")
|
||||
ok(callable(image_exists) and callable(ocr_text) and callable(ocr_text_with_position),
|
||||
"RPA 指令别名可用(image_exists / ocr_text / ocr_text_with_position)")
|
||||
|
||||
# ---- 15. 窗口对象:获取 / 属性 / 绑定 Screen ----
|
||||
from desktopauto import Window, find_windows, foreground_window, get_window # noqa: PLC0415
|
||||
try:
|
||||
get_window(process="definitely_not_exist_123.exe")
|
||||
ok(False, "找不到窗口应抛错")
|
||||
except RuntimeError as e:
|
||||
ok("未找到窗口" in str(e), "找不到窗口时抛 RuntimeError(提示明确)")
|
||||
|
||||
ok(foreground_window() is not None, "foreground_window() 能拿到前台窗口对象")
|
||||
|
||||
from desktopauto import close_window # noqa: PLC0415
|
||||
ok(callable(close_window), "close_window 可用(函数式关闭)")
|
||||
try:
|
||||
close_window("绝对不存在的窗口标题_xyz_123")
|
||||
ok(False, "关闭不存在的窗口应抛错")
|
||||
except RuntimeError:
|
||||
ok(True, "关闭不存在的窗口抛 RuntimeError(不会误关别的窗口)")
|
||||
|
||||
cands = find_windows(process="DingTalk")
|
||||
if cands:
|
||||
w = Window(cands[0]["hwnd"])
|
||||
ok(w.exists() and w.width > 0 and w.height > 0, f"Window 属性正常:{w}")
|
||||
ok(isinstance(w.title, str) and isinstance(w.pid, int), "Window 标题/PID 可读")
|
||||
ok(len(w.children()) > 0, f"Window.children() 有子窗口({len(w.children())} 个)")
|
||||
sc = w.screen(threshold=0.9)
|
||||
img, reg = sc.grab()
|
||||
ok((reg[2] - reg[0]) == w.width, "Window.screen() 截图范围与窗口尺寸一致")
|
||||
ok(w.hwnd == sc.window, "Screen 已绑定该窗口句柄")
|
||||
else:
|
||||
print("[SKIP] 未发现钉钉窗口,跳过 Window 真实用例")
|
||||
|
||||
# ---- 16. 进程:只做查询,不启动/不终止(避免干扰桌面) ----
|
||||
from desktopauto import (is_running, kill_process, list_processes, # noqa: PLC0415
|
||||
open_path, run_or_open)
|
||||
procs = list_processes()
|
||||
ok(len(procs) > 0, f"进程枚举正常({len(procs)} 个)")
|
||||
ok(is_running("explorer") is True, "is_running:explorer.exe 在运行")
|
||||
ok(list_processes("绝对不存在的进程名_xyz") == [], "查不存在的进程返回空列表")
|
||||
try:
|
||||
kill_process("绝对不存在的进程名_xyz")
|
||||
ok(False, "终止不存在的进程应抛错")
|
||||
except RuntimeError:
|
||||
ok(True, "终止不存在的进程抛 RuntimeError(不会误杀)")
|
||||
try:
|
||||
open_path(r"C:\绝对不存在的文件_xyz_123.txt")
|
||||
ok(False, "打开不存在的路径应抛错")
|
||||
except RuntimeError:
|
||||
ok(True, "打开不存在的路径抛 RuntimeError")
|
||||
ok(callable(run_or_open) and callable(list_processes), "运行或打开 接口可用")
|
||||
|
||||
# ---- 17. 影刀指令对齐:send_keys 解析 / 文件系统 / 随机等待 ----
|
||||
from desktopauto import fs as _fs # noqa: PLC0415
|
||||
from desktopauto import Screen as _S2, sleep # noqa: PLC0415
|
||||
from desktopauto.keys import parse_send_keys # noqa: PLC0415
|
||||
ok(parse_send_keys("{ENTER}") == [("key", "ENTER")], "{ENTER} 解析为单键")
|
||||
ok(parse_send_keys("^a") == [("combo", ["ctrl", "a"])], "^a 解析为 Ctrl+A")
|
||||
ok(parse_send_keys("abc{ENTER}") == [("text", "abc"), ("key", "ENTER")],
|
||||
"文本+按键混合解析")
|
||||
ok(parse_send_keys("%{F4}") == [("combo", ["alt", "F4"])], "%{F4} 解析为 Alt+F4")
|
||||
|
||||
fs_dir = os.path.join(TMP, "fs_test")
|
||||
f1 = _fs.write_text(os.path.join(fs_dir, "a.txt"), "第一行")
|
||||
ok(_fs.exists(f1) and _fs.read_text(f1) == "第一行", "fs 写入/读取 UTF-8")
|
||||
f2 = _fs.write_text(os.path.join(fs_dir, "gbk.txt"), "中文内容", encoding="gbk")
|
||||
ok(_fs.read_text(f2) == "中文内容", "fs 读取 GBK 自动回退")
|
||||
sub = _fs.make_dir(fs_dir, "sub")
|
||||
ok(_fs.dir_exists(sub), "fs 创建文件夹")
|
||||
copied = _fs.copy(f1, sub)
|
||||
ok(_fs.exists(copied), "fs 复制文件到目录")
|
||||
moved = _fs.move(copied, os.path.join(sub, "b.txt"))
|
||||
ok(_fs.exists(moved) and not _fs.exists(copied), "fs 移动/重命名")
|
||||
ok(len(_fs.list_files(sub, pattern="*.txt")) == 1, "fs 列文件(通配符)")
|
||||
ok(_fs.newest_file(fs_dir, "*.txt", recursive=True) is not None, "fs 取最新文件")
|
||||
ok(_fs.wait_file(moved, timeout=1), "fs 等文件出现")
|
||||
ok(_fs.delete(sub) and not _fs.exists(sub), "fs 删除文件夹")
|
||||
|
||||
waited = sleep(0.01, random_range=(0.01, 0.02))
|
||||
ok(0.009 <= waited <= 0.021, f"sleep 随机等待生效({waited:.3f}s)")
|
||||
ok(_S2().wait_all([absent], timeout=0.5) is False, "wait_all:有模板不存在返回 False")
|
||||
|
||||
print(f"\n全部通过:{_passed} 项;临时目录 {TMP}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except AssertionError as e:
|
||||
print(e)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,87 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""desktopauto —— 屏幕识图 / 文字识别 / 鼠标键盘 工具库(面向无元素树的桌面自动化)。
|
||||
|
||||
只依赖 opencv-python + numpy + pillow(OCR 另需 rapidocr + onnxruntime),
|
||||
鼠标键盘窗口全部走 ctypes 调系统 API,不依赖 pyautogui / pywin32 / 任何底座代码。
|
||||
|
||||
一次完整操作通常是:
|
||||
from desktopauto import Screen
|
||||
|
||||
s = Screen(window="钉钉") # 限定窗口
|
||||
s.activate()
|
||||
s.click("img/chat_input.png") # 识图点击
|
||||
s.paste("排班识别,水庄大鹅……") # 写剪贴板 + Ctrl+V(中文最稳)
|
||||
s.hotkey("ctrl", "enter") # 组合键
|
||||
s.wait_stable_text = s.wait_text("发送成功") # 文字确认
|
||||
|
||||
分组:
|
||||
截图 grab / screenshot
|
||||
识图 find / find_all / find_any / exists / wait / click / click_at
|
||||
文字 read_text / recognize / find_text / find_all_text / text_exists /
|
||||
wait_text / click_text
|
||||
输入 paste / type_text / press / hotkey / key_down / key_up
|
||||
鼠标 scroll / drag(click 已含左/右/中键与连击)
|
||||
窗口 list_windows / find_window(s) / wait_window / child_windows /
|
||||
window_info / window_rect / activate_window
|
||||
颜色差异 find_color / find_colors / diff / diff_ratio
|
||||
离线 mark(在图片上标注命中,不碰屏幕)
|
||||
|
||||
异常约定:
|
||||
模板不存在/无法解码、窗口找不到、依赖缺失 → RuntimeError(配置错误,需要修);
|
||||
图/文字没匹配到 → None / False(业务上的「不存在」,不是异常)。
|
||||
"""
|
||||
from . import clipboard, colors, fs, keys, ocr, process
|
||||
from .colors import ColorMatch, diff_ratio, find_colors
|
||||
from .process import (is_running, kill_process, launch, list_processes, open_path,
|
||||
open_url, run_or_open, wait_process)
|
||||
from .marking import mark, summarize
|
||||
from .matcher import Match
|
||||
from .ocr import TextItem, match_text, recognize
|
||||
from .screen import (
|
||||
Screen, click, click_image, click_text, diff, drag, exists, find, find_all,
|
||||
find_all_text, find_any, find_color, find_text, hotkey, hover, hover_image,
|
||||
hover_text, image_exists, move_mouse, ocr_available, ocr_text,
|
||||
ocr_text_with_position, paste, press, read_text, scroll, send_keys, sleep,
|
||||
text_exists, type_text, wait, wait_any, wait_all, wait_gone, wait_image,
|
||||
wait_text, wait_text_exists,
|
||||
)
|
||||
from .window import (
|
||||
Window, activate_window, child_windows, close_window, find_window, find_windows,
|
||||
foreground_window, get_window, list_windows, wait_window, window_info, window_rect,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# 门面
|
||||
"Screen",
|
||||
"Match",
|
||||
"TextItem",
|
||||
"ColorMatch",
|
||||
# 识图 / 条件判断 / 等待
|
||||
"find", "find_all", "find_any", "exists", "wait", "click",
|
||||
"wait_gone", "wait_any", "wait_all", "hover", "hover_text",
|
||||
# 文字
|
||||
"read_text", "recognize", "match_text", "find_text", "find_all_text",
|
||||
"text_exists", "wait_text", "click_text", "ocr_available", "ocr",
|
||||
"ocr_text", "ocr_text_with_position",
|
||||
# RPA 指令别名
|
||||
"image_exists", "wait_image", "click_image", "hover_image", "wait_text_exists",
|
||||
# 输入
|
||||
"paste", "type_text", "press", "hotkey", "send_keys", "keys", "clipboard",
|
||||
# 鼠标 / 等待
|
||||
"scroll", "drag", "move_mouse", "sleep",
|
||||
# 文件与文件夹
|
||||
"fs",
|
||||
# 颜色 / 差异
|
||||
"find_color", "find_colors", "diff", "diff_ratio", "colors",
|
||||
# 窗口
|
||||
"Window", "get_window", "foreground_window", "activate_window", "close_window",
|
||||
"list_windows", "find_window", "find_windows", "wait_window", "child_windows",
|
||||
"window_info", "window_rect",
|
||||
# 进程:运行或打开 / 终止程序
|
||||
"run_or_open", "launch", "open_path", "open_url",
|
||||
"list_processes", "is_running", "wait_process", "kill_process", "process",
|
||||
# 离线
|
||||
"mark", "summarize",
|
||||
]
|
||||
|
||||
__version__ = "0.4.0"
|
||||
@@ -0,0 +1,150 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命令行入口:不写代码也能验证识图。
|
||||
|
||||
用法示例:
|
||||
python -m desktopauto --template img/btn.png --mode exists
|
||||
python -m desktopauto --template img/btn.png --mode click --window "钉钉"
|
||||
python -m desktopauto --template img/btn.png --mode wait --timeout 30 --debug-dir debug
|
||||
python -m desktopauto --mode shot --path shot.png
|
||||
|
||||
输出:JSON({"ok": true/false, "match": {...}}),退出码 0=命中/成功,1=未命中,2=参数或运行错误。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from . import marking, ocr
|
||||
from . import matcher as _m
|
||||
from .screen import Screen
|
||||
|
||||
|
||||
def _parse_region(text: str) -> Optional[List[int]]:
|
||||
if not text:
|
||||
return None
|
||||
parts = [p.strip() for p in text.split(",") if p.strip()]
|
||||
if len(parts) != 4:
|
||||
raise SystemExit(f"--region 需要 4 个数字 (left,top,right,bottom),收到:{text}")
|
||||
return [int(p) for p in parts]
|
||||
|
||||
|
||||
def _parse_scales(text: str) -> List[float]:
|
||||
if not text:
|
||||
return [1.0]
|
||||
return [float(p.strip()) for p in text.split(",") if p.strip()]
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="desktopauto", description="屏幕识图:找图 / 判断存在 / 点击")
|
||||
parser.add_argument("--template", "-t", default="", help="模板图路径(找图/点击必填)")
|
||||
parser.add_argument("--mode", "-m", default="exists",
|
||||
choices=["exists", "find", "all", "click", "wait", "shot", "mark", "ocr"],
|
||||
help="exists=判断存在,find=返回最佳位置,all=返回全部,click=识图点击,"
|
||||
"wait=等待出现,shot=仅截图,mark=离线图片标记,ocr=文字识别/按文字定位")
|
||||
parser.add_argument("--image", "-i", default="", help="mark/ocr 模式的待识别图片路径(不给则实时截屏)")
|
||||
parser.add_argument("--out", "-o", default="", help="mark/ocr 模式的标注图输出路径")
|
||||
parser.add_argument("--text", default="", help="ocr 模式要查找的文字(多个用逗号分隔;留空则列出全部)")
|
||||
parser.add_argument("--min-score", type=float, default=0.5, help="ocr 识别置信度下限,默认 0.5")
|
||||
parser.add_argument("--limit", type=int, default=0, help="ocr 模式最多输出多少条(0=不限)")
|
||||
parser.add_argument("--window", "-w", default="", help="限定窗口标题关键字(可选)")
|
||||
parser.add_argument("--region", "-r", default="", help="限定区域 left,top,right,bottom(可选)")
|
||||
parser.add_argument("--threshold", type=float, default=_m.DEFAULT_THRESHOLD, help="相似度阈值 0~1,默认 0.85")
|
||||
parser.add_argument("--scales", default="", help="模板缩放集合,如 0.9,1.0,1.1(跨 DPI 用)")
|
||||
parser.add_argument("--timeout", type=float, default=10.0, help="wait 模式超时秒数")
|
||||
parser.add_argument("--interval", type=float, default=0.5, help="wait 模式轮询间隔秒数")
|
||||
parser.add_argument("--debug-dir", default="", help="调试图输出目录(可选)")
|
||||
parser.add_argument("--color", action="store_true", help="彩色匹配(默认灰度)")
|
||||
parser.add_argument("--button", default="left", choices=["left", "right", "middle"], help="点击键")
|
||||
parser.add_argument("--clicks", type=int, default=1, help="点击次数(2=双击)")
|
||||
parser.add_argument("--path", default="", help="shot 模式的保存路径")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
screen = Screen(window=args.window or None, region=_parse_region(args.region),
|
||||
threshold=args.threshold, scales=_parse_scales(args.scales),
|
||||
gray=not args.color, debug_dir=args.debug_dir)
|
||||
|
||||
try:
|
||||
if args.mode == "shot":
|
||||
path = screen.screenshot(args.path)
|
||||
print(json.dumps({"ok": True, "path": path}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
if args.mode == "mark":
|
||||
if not args.image:
|
||||
print(json.dumps({"ok": False, "error": "mark 模式需要 --image"}, ensure_ascii=False))
|
||||
return 2
|
||||
tpls = [p.strip() for p in (args.template or "").split(",") if p.strip()]
|
||||
if not tpls:
|
||||
print(json.dumps({"ok": False, "error": "mark 模式需要 --template(多个用逗号分隔)"},
|
||||
ensure_ascii=False))
|
||||
return 2
|
||||
result = marking.mark(args.image, tpls, out_path=args.out or args.path,
|
||||
threshold=args.threshold, scales=_parse_scales(args.scales),
|
||||
gray=not args.color)
|
||||
print(marking.summarize(result))
|
||||
print(json.dumps({"ok": result["total"] > 0, "out": result["out"],
|
||||
"items": result["items"]}, ensure_ascii=False))
|
||||
return 0 if result["total"] > 0 else 1
|
||||
|
||||
if args.mode == "ocr":
|
||||
queries = [q.strip() for q in (args.text or "").split(",") if q.strip()]
|
||||
if args.image:
|
||||
img = _m.load_template(args.image)
|
||||
origin = (0, 0)
|
||||
else:
|
||||
img, reg = screen.grab()
|
||||
origin = (int(reg[0]), int(reg[1]))
|
||||
items = ocr.recognize(img, min_score=args.min_score)
|
||||
matched: list = []
|
||||
for q in queries:
|
||||
matched.extend(ocr.match_text(items, q))
|
||||
targets = matched if queries else items
|
||||
show = targets[: args.limit] if args.limit else targets
|
||||
out = args.out or args.path or os.path.join(
|
||||
os.getcwd(), f"ocr_marked_{time.strftime('%Y%m%d_%H%M%S')}.png")
|
||||
path = ocr.mark_text(img, items, out_path=out,
|
||||
only=(targets if queries else None))
|
||||
print(ocr.summarize(show, limit=args.limit))
|
||||
payload = {"ok": (bool(targets) if queries else bool(items)),
|
||||
"count": len(items), "matched": [it.to_dict() for it in show],
|
||||
"origin": list(origin), "out": path}
|
||||
print(json.dumps(payload, ensure_ascii=False))
|
||||
return 0 if payload["ok"] else 1
|
||||
|
||||
if not args.template:
|
||||
print(json.dumps({"ok": False, "error": "缺少 --template"}, ensure_ascii=False))
|
||||
return 2
|
||||
|
||||
if args.mode == "click":
|
||||
hit = screen.find(args.template)
|
||||
ok = screen.click(args.template, button=args.button, clicks=args.clicks)
|
||||
print(json.dumps({"ok": ok, "match": hit.to_dict() if hit else None}, ensure_ascii=False))
|
||||
return 0 if ok else 1
|
||||
|
||||
if args.mode == "wait":
|
||||
hit = screen.wait(args.template, timeout=args.timeout, interval=args.interval)
|
||||
print(json.dumps({"ok": hit is not None, "match": hit.to_dict() if hit else None},
|
||||
ensure_ascii=False))
|
||||
return 0 if hit else 1
|
||||
|
||||
if args.mode == "all":
|
||||
hits = screen.find_all(args.template)
|
||||
print(json.dumps({"ok": bool(hits), "count": len(hits),
|
||||
"matches": [h.to_dict() for h in hits]}, ensure_ascii=False))
|
||||
return 0 if hits else 1
|
||||
|
||||
hit = screen.find(args.template)
|
||||
print(json.dumps({"ok": hit is not None, "match": hit.to_dict() if hit else None},
|
||||
ensure_ascii=False))
|
||||
return 0 if hit else 1
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False))
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,511 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Windows 底层封装:DPI 感知、窗口枚举/矩形/激活、鼠标点击。
|
||||
|
||||
全部走 ctypes,不引入 pywin32 / pyautogui,保证「装完 opencv + pillow 就能跑」。
|
||||
非 Windows 平台调用会直接抛错(本库只面向 Windows 执行机)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
IS_WINDOWS = sys.platform.startswith("win")
|
||||
|
||||
SW_RESTORE = 9
|
||||
DWMWA_EXTENDED_FRAME_BOUNDS = 9
|
||||
|
||||
# mouse_event 标志位
|
||||
MOUSEEVENTF_LEFTDOWN = 0x0002
|
||||
MOUSEEVENTF_LEFTUP = 0x0004
|
||||
MOUSEEVENTF_RIGHTDOWN = 0x0008
|
||||
MOUSEEVENTF_RIGHTUP = 0x0010
|
||||
MOUSEEVENTF_MIDDLEDOWN = 0x0020
|
||||
MOUSEEVENTF_MIDDLEUP = 0x0040
|
||||
|
||||
_BUTTON_FLAGS = {
|
||||
"left": (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),
|
||||
"right": (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),
|
||||
"middle": (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),
|
||||
}
|
||||
|
||||
_DPI_READY = False
|
||||
|
||||
|
||||
def require_windows(what: str) -> None:
|
||||
if not IS_WINDOWS:
|
||||
raise RuntimeError(f"{what} 仅支持 Windows(当前平台:{sys.platform})")
|
||||
|
||||
|
||||
def ensure_dpi_aware() -> None:
|
||||
"""声明进程 DPI 感知(幂等)。
|
||||
|
||||
不做这一步,系统缩放 125%/150% 时截图按逻辑像素返回、SetCursorPos 按物理像素生效,
|
||||
两边差一个缩放系数,会出现「图明明在屏幕上,点击却偏了几十像素」。
|
||||
"""
|
||||
global _DPI_READY
|
||||
if _DPI_READY:
|
||||
return
|
||||
if IS_WINDOWS:
|
||||
try:
|
||||
ctypes.windll.shcore.SetProcessDpiAwareness(2) # PER_MONITOR_DPI_AWARE_V2
|
||||
except Exception: # noqa: BLE001 老系统(Win7/8)回退
|
||||
try:
|
||||
ctypes.windll.user32.SetProcessDPIAware()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_DPI_READY = True
|
||||
|
||||
|
||||
# ==================== 窗口 ====================
|
||||
def list_windows(keyword: str = "", visible_only: bool = True) -> List[Tuple[int, str]]:
|
||||
"""按标题关键字模糊查找顶层窗口,返回 [(hwnd, title)](已排除最小化窗口)。"""
|
||||
require_windows("窗口查找")
|
||||
ensure_dpi_aware()
|
||||
user32 = ctypes.windll.user32
|
||||
found: List[Tuple[int, str]] = []
|
||||
keyword = (keyword or "").strip()
|
||||
buf = ctypes.create_unicode_buffer(512)
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
|
||||
def _enum(hwnd, _lparam): # noqa: ANN001
|
||||
if visible_only and not user32.IsWindowVisible(hwnd):
|
||||
return True
|
||||
if user32.IsIconic(hwnd): # 最小化:截图会是空白,直接排除
|
||||
return True
|
||||
buf.value = ""
|
||||
user32.GetWindowTextW(hwnd, buf, 512)
|
||||
title = buf.value.strip()
|
||||
if not title:
|
||||
return True
|
||||
if keyword and keyword not in title:
|
||||
return True
|
||||
found.append((int(hwnd), title))
|
||||
return True
|
||||
|
||||
user32.EnumWindows(_enum, 0)
|
||||
return found
|
||||
|
||||
|
||||
def resolve_hwnd(window: Union[int, str]) -> int:
|
||||
"""把 hwnd 或标题关键字解析为唯一 hwnd(多个命中取标题最短的主窗口)。"""
|
||||
if isinstance(window, int):
|
||||
return window
|
||||
hits = list_windows(str(window))
|
||||
if not hits:
|
||||
raise RuntimeError(f"未找到标题含「{window}」的可见窗口(窗口是否已打开/最小化?)")
|
||||
if len(hits) > 1:
|
||||
hits.sort(key=lambda x: len(x[1]))
|
||||
hits = [hits[0]]
|
||||
return hits[0][0]
|
||||
|
||||
|
||||
def window_rect(window: Union[int, str]) -> Tuple[int, int, int, int]:
|
||||
"""窗口屏幕矩形 (left, top, right, bottom),优先用 DWM 扩展边框(更贴近可见区域)。"""
|
||||
require_windows("窗口截图")
|
||||
ensure_dpi_aware()
|
||||
hwnd = resolve_hwnd(window)
|
||||
rect = wintypes.RECT()
|
||||
try:
|
||||
hr = ctypes.windll.dwmapi.DwmGetWindowAttribute(
|
||||
wintypes.HWND(hwnd), wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
|
||||
ctypes.byref(rect), ctypes.sizeof(rect))
|
||||
if hr != 0:
|
||||
raise OSError(hr)
|
||||
except Exception: # noqa: BLE001 DWM 不可用时回退
|
||||
if not ctypes.windll.user32.GetWindowRect(wintypes.HWND(hwnd), ctypes.byref(rect)):
|
||||
raise RuntimeError(f"获取窗口矩形失败:{window}")
|
||||
if rect.right <= rect.left or rect.bottom <= rect.top:
|
||||
raise RuntimeError(f"窗口矩形无效(可能已最小化):{window}")
|
||||
return int(rect.left), int(rect.top), int(rect.right), int(rect.bottom)
|
||||
|
||||
|
||||
def activate_window(window: Union[int, str], wait: float = 0.2) -> int:
|
||||
"""前置并激活窗口,返回 hwnd(点击前建议先激活,避免点到被遮挡的位置)。"""
|
||||
hwnd = resolve_hwnd(window)
|
||||
user32 = ctypes.windll.user32
|
||||
try:
|
||||
user32.ShowWindow(wintypes.HWND(hwnd), SW_RESTORE)
|
||||
user32.SetForegroundWindow(wintypes.HWND(hwnd))
|
||||
except Exception: # noqa: BLE001 前台切换可能被系统策略拒绝,不影响后续截图/点击
|
||||
pass
|
||||
if wait:
|
||||
time.sleep(wait)
|
||||
return hwnd
|
||||
|
||||
|
||||
# ==================== 鼠标 ====================
|
||||
def move_to(x: int, y: int, settle: float = 0.0) -> None:
|
||||
"""移动鼠标到屏幕物理像素坐标。"""
|
||||
require_windows("鼠标操作")
|
||||
ensure_dpi_aware()
|
||||
if not ctypes.windll.user32.SetCursorPos(int(x), int(y)):
|
||||
raise RuntimeError(f"鼠标移动失败:({x}, {y})")
|
||||
if settle:
|
||||
time.sleep(settle)
|
||||
|
||||
|
||||
MOVE_SPEEDS = {"instant": 0.0, "fast": 0.05, "middle": 0.15, "normal": 0.15, "slow": 0.35}
|
||||
|
||||
|
||||
def move_mouse(x: int, y: int, relative_to: str = "screen",
|
||||
speed: str = "instant", window: Union[int, str, None] = None) -> Tuple[int, int]:
|
||||
"""移动鼠标(影刀「移动鼠标」指令)。
|
||||
|
||||
Args:
|
||||
x, y: 目标坐标(相对屏幕,或相对窗口左上角)。
|
||||
relative_to: "screen"(默认)或 "window"(需传 window)。
|
||||
speed: instant / fast / middle / slow(非 instant 时分步移动,模拟人工轨迹)。
|
||||
window: relative_to="window" 时的窗口(hwnd 或标题)。
|
||||
|
||||
Returns:
|
||||
实际移动到的屏幕坐标 (x, y)。
|
||||
"""
|
||||
require_windows("鼠标移动")
|
||||
ensure_dpi_aware()
|
||||
if (relative_to or "screen").lower() == "window":
|
||||
if window is None:
|
||||
raise ValueError('relative_to="window" 时必须传 window')
|
||||
left, top, _right, _bottom = window_rect(window)
|
||||
x, y = int(x) + left, int(y) + top
|
||||
else:
|
||||
x, y = int(x), int(y)
|
||||
|
||||
duration = MOVE_SPEEDS.get((speed or "instant").lower(), 0.0)
|
||||
if duration <= 0:
|
||||
move_to(x, y)
|
||||
return x, y
|
||||
|
||||
sx, sy = cursor_pos()
|
||||
steps = max(6, int(duration / 0.01))
|
||||
for i in range(1, steps + 1):
|
||||
t = i / steps
|
||||
move_to(round(sx + (x - sx) * t), round(sy + (y - sy) * t))
|
||||
time.sleep(duration / steps)
|
||||
return x, y
|
||||
|
||||
|
||||
def click_at(x: int, y: int, button: str = "left", clicks: int = 1,
|
||||
interval: float = 0.05, settle: float = 0.05) -> None:
|
||||
"""在屏幕坐标点击(先移动再按下/抬起),支持左/右/中键与连击。"""
|
||||
require_windows("鼠标点击")
|
||||
button = (button or "left").lower()
|
||||
if button not in _BUTTON_FLAGS:
|
||||
raise ValueError(f"不支持的鼠标键:{button}(可选 left/right/middle)")
|
||||
down, up = _BUTTON_FLAGS[button]
|
||||
move_to(x, y)
|
||||
if settle:
|
||||
time.sleep(settle)
|
||||
user32 = ctypes.windll.user32
|
||||
for i in range(max(1, int(clicks))):
|
||||
user32.mouse_event(down, 0, 0, 0, 0)
|
||||
time.sleep(0.01)
|
||||
user32.mouse_event(up, 0, 0, 0, 0)
|
||||
if i < clicks - 1:
|
||||
time.sleep(max(0.01, interval))
|
||||
|
||||
|
||||
def cursor_pos() -> Tuple[int, int]:
|
||||
"""当前鼠标屏幕坐标。"""
|
||||
require_windows("鼠标坐标读取")
|
||||
ensure_dpi_aware()
|
||||
pt = wintypes.POINT()
|
||||
ctypes.windll.user32.GetCursorPos(ctypes.byref(pt))
|
||||
return int(pt.x), int(pt.y)
|
||||
|
||||
|
||||
# ==================== 滚轮 / 拖拽 ====================
|
||||
MOUSEEVENTF_WHEEL = 0x0800
|
||||
MOUSEEVENTF_HWHEEL = 0x1000
|
||||
WHEEL_DELTA = 120
|
||||
|
||||
|
||||
def scroll(notches: int = 3, at: Optional[Tuple[int, int]] = None,
|
||||
horizontal: bool = False, settle: float = 0.08) -> None:
|
||||
"""滚轮滚动。notches>0 向上(垂直)/向左(水平),<0 反之;at 指定先移动到的坐标(不传=当前位置)。"""
|
||||
require_windows("滚轮滚动")
|
||||
ensure_dpi_aware()
|
||||
if at is not None:
|
||||
move_to(int(at[0]), int(at[1]))
|
||||
if settle:
|
||||
time.sleep(settle)
|
||||
flag = MOUSEEVENTF_HWHEEL if horizontal else MOUSEEVENTF_WHEEL
|
||||
delta = ctypes.c_ulong((int(notches) * WHEEL_DELTA) & 0xFFFFFFFF).value
|
||||
ctypes.windll.user32.mouse_event(flag, 0, 0, delta, 0)
|
||||
|
||||
|
||||
def drag(from_xy: Tuple[int, int], to_xy: Tuple[int, int],
|
||||
duration: float = 0.5, button: str = "left", steps: int = 0) -> None:
|
||||
"""按住鼠标从 from_xy 拖到 to_xy(分步移动,模拟人工拖动轨迹)。"""
|
||||
require_windows("鼠标拖拽")
|
||||
button = (button or "left").lower()
|
||||
if button not in _BUTTON_FLAGS:
|
||||
raise ValueError(f"不支持的鼠标键:{button}(可选 left/right/middle)")
|
||||
down, up = _BUTTON_FLAGS[button]
|
||||
x0, y0 = int(from_xy[0]), int(from_xy[1])
|
||||
x1, y1 = int(to_xy[0]), int(to_xy[1])
|
||||
total = max(8, int(steps) if steps else int(max(0.05, duration) / 0.01))
|
||||
user32 = ctypes.windll.user32
|
||||
move_to(x0, y0)
|
||||
time.sleep(0.05)
|
||||
user32.mouse_event(down, 0, 0, 0, 0)
|
||||
try:
|
||||
for i in range(1, total + 1):
|
||||
t = i / total
|
||||
move_to(round(x0 + (x1 - x0) * t), round(y0 + (y1 - y0) * t))
|
||||
time.sleep(max(0.005, duration / total))
|
||||
finally:
|
||||
time.sleep(0.05)
|
||||
user32.mouse_event(up, 0, 0, 0, 0)
|
||||
|
||||
|
||||
# ==================== 窗口信息 / 进程 ====================
|
||||
def _process_name(pid: int) -> str:
|
||||
"""按进程 ID 取可执行文件名(如 DingTalk.exe);失败返回空串。"""
|
||||
if not pid:
|
||||
return ""
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
kernel32.OpenProcess.restype = ctypes.c_void_p
|
||||
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
kernel32.QueryFullProcessImageNameW.argtypes = [
|
||||
ctypes.c_void_p, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||
handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
|
||||
if not handle:
|
||||
return ""
|
||||
try:
|
||||
buf = ctypes.create_unicode_buffer(1024)
|
||||
size = wintypes.DWORD(1024)
|
||||
if kernel32.QueryFullProcessImageNameW(handle, 0, buf, ctypes.byref(size)):
|
||||
return os.path.basename(buf.value)
|
||||
return ""
|
||||
finally:
|
||||
kernel32.CloseHandle(ctypes.c_void_p(handle))
|
||||
|
||||
|
||||
def _window_pid(hwnd: int) -> int:
|
||||
user32 = ctypes.windll.user32
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
pid = wintypes.DWORD()
|
||||
user32.GetWindowThreadProcessId(wintypes.HWND(hwnd), ctypes.byref(pid))
|
||||
return int(pid.value)
|
||||
|
||||
|
||||
def _window_class(hwnd: int) -> str:
|
||||
buf = ctypes.create_unicode_buffer(256)
|
||||
ctypes.windll.user32.GetClassNameW(wintypes.HWND(hwnd), buf, 256)
|
||||
return buf.value
|
||||
|
||||
|
||||
def _window_title(hwnd: int) -> str:
|
||||
buf = ctypes.create_unicode_buffer(512)
|
||||
ctypes.windll.user32.GetWindowTextW(wintypes.HWND(hwnd), buf, 512)
|
||||
return buf.value.strip()
|
||||
|
||||
|
||||
def _window_rect_raw(hwnd: int) -> Tuple[int, int, int, int]:
|
||||
rect = wintypes.RECT()
|
||||
if not ctypes.windll.user32.GetWindowRect(wintypes.HWND(hwnd), ctypes.byref(rect)):
|
||||
return 0, 0, 0, 0
|
||||
return int(rect.left), int(rect.top), int(rect.right), int(rect.bottom)
|
||||
|
||||
|
||||
def window_info(hwnd: int, with_process: bool = True) -> dict:
|
||||
"""取窗口完整信息:{hwnd, title, class_name, pid, process, rect, minimized, visible}。"""
|
||||
require_windows("窗口信息")
|
||||
ensure_dpi_aware()
|
||||
user32 = ctypes.windll.user32
|
||||
pid = _window_pid(hwnd)
|
||||
return {
|
||||
"hwnd": int(hwnd),
|
||||
"title": _window_title(hwnd),
|
||||
"class_name": _window_class(hwnd),
|
||||
"pid": pid,
|
||||
"process": _process_name(pid) if with_process else "",
|
||||
"rect": _window_rect_raw(hwnd),
|
||||
"minimized": bool(user32.IsIconic(wintypes.HWND(hwnd))),
|
||||
"visible": bool(user32.IsWindowVisible(wintypes.HWND(hwnd))),
|
||||
}
|
||||
|
||||
|
||||
def find_windows(title: str = "", exact: bool = False, pid: int = 0,
|
||||
process: str = "", class_name: str = "",
|
||||
visible_only: bool = True, include_minimized: bool = False,
|
||||
with_process: bool = True) -> List[dict]:
|
||||
"""按条件查找顶层窗口,返回窗口信息 dict 列表(按标题长度升序,主窗口在前)。
|
||||
|
||||
Args:
|
||||
title: 标题过滤;exact=False 时包含匹配(默认),exact=True 完全相等。空=不过滤。
|
||||
pid: 进程 ID 精确匹配(0=不过滤)。
|
||||
process: 进程名过滤(如 "DingTalk.exe" / "DingTalk",不区分大小写、包含匹配)。
|
||||
class_name: 窗口类名(包含匹配,如 "Chrome_WidgetWin_1")。
|
||||
visible_only: 只看可见窗口。
|
||||
include_minimized: 是否包含最小化窗口(默认排除,因为截图会是空白)。
|
||||
with_process: 是否解析进程名(关掉可提速)。
|
||||
"""
|
||||
require_windows("窗口查找")
|
||||
ensure_dpi_aware()
|
||||
user32 = ctypes.windll.user32
|
||||
out: List[dict] = []
|
||||
title = (title or "").strip()
|
||||
process_lc = (process or "").strip().lower()
|
||||
class_name = (class_name or "").strip()
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
|
||||
def _enum(hwnd, _lparam): # noqa: ANN001
|
||||
if visible_only and not user32.IsWindowVisible(hwnd):
|
||||
return True
|
||||
if not include_minimized and user32.IsIconic(hwnd):
|
||||
return True
|
||||
t = _window_title(hwnd)
|
||||
if title:
|
||||
if exact:
|
||||
if t != title:
|
||||
return True
|
||||
elif title not in t:
|
||||
return True
|
||||
if class_name and class_name not in _window_class(hwnd):
|
||||
return True
|
||||
w_pid = _window_pid(hwnd)
|
||||
if pid and w_pid != int(pid):
|
||||
return True
|
||||
info = {
|
||||
"hwnd": int(hwnd), "title": t, "class_name": _window_class(hwnd),
|
||||
"pid": w_pid, "process": "", "rect": _window_rect_raw(hwnd),
|
||||
"minimized": False, "visible": True,
|
||||
}
|
||||
if process_lc:
|
||||
name = _process_name(w_pid) if with_process else ""
|
||||
if process_lc not in name.lower():
|
||||
return True
|
||||
info["process"] = name
|
||||
elif with_process:
|
||||
info["process"] = _process_name(w_pid)
|
||||
if not info["title"] and not class_name:
|
||||
return True # 无标题的壳窗口,除非按类名找,否则跳过
|
||||
out.append(info)
|
||||
return True
|
||||
|
||||
user32.EnumWindows(_enum, 0)
|
||||
out.sort(key=lambda w: len(w["title"]))
|
||||
return out
|
||||
|
||||
|
||||
def wait_window(title: str = "", timeout: float = 10.0, interval: float = 0.3,
|
||||
**kwargs) -> Optional[dict]:
|
||||
"""等待窗口出现(参数同 find_windows),超时返回 None。"""
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
wins = find_windows(title=title, **kwargs)
|
||||
if wins:
|
||||
return wins[0]
|
||||
if time.time() >= deadline:
|
||||
return None
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
|
||||
|
||||
# ==================== 窗口操作(Window 对象用) ====================
|
||||
SW_MINIMIZE = 6
|
||||
SW_MAXIMIZE = 3
|
||||
WM_CLOSE = 0x0010
|
||||
|
||||
|
||||
def is_window(hwnd: int) -> bool:
|
||||
"""句柄是否仍然有效(窗口没被关掉)。"""
|
||||
return bool(ctypes.windll.user32.IsWindow(wintypes.HWND(int(hwnd))))
|
||||
|
||||
|
||||
def foreground_hwnd() -> int:
|
||||
"""当前前台窗口句柄(0 = 没有)。"""
|
||||
return int(ctypes.windll.user32.GetForegroundWindow() or 0)
|
||||
|
||||
|
||||
def is_foreground(hwnd: int) -> bool:
|
||||
"""该窗口是否在前台。"""
|
||||
return foreground_hwnd() == int(hwnd)
|
||||
|
||||
|
||||
def show_window(hwnd: int, cmd: int) -> None:
|
||||
ctypes.windll.user32.ShowWindow(wintypes.HWND(int(hwnd)), cmd)
|
||||
|
||||
|
||||
def minimize_window(hwnd: int) -> None:
|
||||
show_window(hwnd, SW_MINIMIZE)
|
||||
|
||||
|
||||
def maximize_window(hwnd: int) -> None:
|
||||
show_window(hwnd, SW_MAXIMIZE)
|
||||
|
||||
|
||||
def restore_window(hwnd: int) -> None:
|
||||
show_window(hwnd, SW_RESTORE)
|
||||
|
||||
|
||||
def close_window(hwnd: int, wait: float = 0.0) -> None:
|
||||
"""发送关闭消息(等同点右上角 ×;应用可能弹「是否保存」确认框)。"""
|
||||
ctypes.windll.user32.PostMessageW(wintypes.HWND(int(hwnd)), WM_CLOSE, 0, 0)
|
||||
if wait:
|
||||
time.sleep(wait)
|
||||
|
||||
|
||||
PROCESS_TERMINATE = 0x0001
|
||||
|
||||
|
||||
def terminate_process(pid: int, wait: float = 0.5) -> None:
|
||||
"""强制结束进程(TerminateProcess)。会杀掉该进程的所有窗口,数据可能丢失,慎用。"""
|
||||
require_windows("结束进程")
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
kernel32.OpenProcess.restype = ctypes.c_void_p
|
||||
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
||||
handle = kernel32.OpenProcess(PROCESS_TERMINATE, False, int(pid))
|
||||
if not handle:
|
||||
raise RuntimeError(f"无法结束进程 {pid}(权限不足,或进程已退出)")
|
||||
try:
|
||||
if not kernel32.TerminateProcess(ctypes.c_void_p(handle), 1):
|
||||
raise RuntimeError(f"TerminateProcess 调用失败:进程 {pid}")
|
||||
finally:
|
||||
kernel32.CloseHandle(ctypes.c_void_p(handle))
|
||||
if wait:
|
||||
time.sleep(wait)
|
||||
|
||||
|
||||
def move_window(hwnd: int, x: int, y: int,
|
||||
width: Optional[int] = None, height: Optional[int] = None) -> None:
|
||||
"""移动窗口(不传宽高则保持原尺寸)。"""
|
||||
left, top, right, bottom = _window_rect_raw(hwnd)
|
||||
w = int(width) if width else max(1, right - left)
|
||||
h = int(height) if height else max(1, bottom - top)
|
||||
ctypes.windll.user32.MoveWindow(wintypes.HWND(int(hwnd)), int(x), int(y), w, h, True)
|
||||
|
||||
|
||||
def child_windows(window: Union[int, str], with_process: bool = False) -> List[dict]:
|
||||
"""列出子窗口(hwnd/类名/标题/矩形),找弹窗、内嵌控件时用。"""
|
||||
require_windows("子窗口枚举")
|
||||
ensure_dpi_aware()
|
||||
hwnd = resolve_hwnd(window)
|
||||
user32 = ctypes.windll.user32
|
||||
out: List[dict] = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
|
||||
def _enum(child, _lparam): # noqa: ANN001
|
||||
out.append({
|
||||
"hwnd": int(child), "title": _window_title(child),
|
||||
"class_name": _window_class(child), "pid": _window_pid(child),
|
||||
"process": "", "rect": _window_rect_raw(child),
|
||||
"minimized": False, "visible": bool(user32.IsWindowVisible(child)),
|
||||
})
|
||||
return True
|
||||
|
||||
user32.EnumChildWindows(wintypes.HWND(hwnd), _enum, 0)
|
||||
return out
|
||||
|
||||
|
||||
def screen_size() -> Tuple[int, int]:
|
||||
"""主屏物理像素尺寸 (width, height)。"""
|
||||
require_windows("屏幕尺寸读取")
|
||||
ensure_dpi_aware()
|
||||
user32 = ctypes.windll.user32
|
||||
return int(user32.GetSystemMetrics(0)), int(user32.GetSystemMetrics(1))
|
||||
@@ -0,0 +1,83 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""截图:全屏 / 指定区域 / 指定窗口,统一返回 BGR ndarray + 区域原点。
|
||||
|
||||
坐标约定:截图得到的图,其左上角对应屏幕上的 origin(物理像素)。
|
||||
匹配结果 + origin = 屏幕坐标,才可用于点击。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Optional, Sequence, Tuple, Union
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ._win32 import ensure_dpi_aware, window_rect
|
||||
|
||||
try:
|
||||
import cv2
|
||||
except ImportError as _e: # pragma: no cover
|
||||
raise RuntimeError("缺少依赖 opencv-python,请安装:pip install opencv-python numpy pillow") from _e
|
||||
|
||||
try:
|
||||
from PIL import ImageGrab
|
||||
except ImportError as _e: # pragma: no cover
|
||||
raise RuntimeError("缺少依赖 pillow,请安装:pip install pillow") from _e
|
||||
|
||||
Region = Sequence[int] # (left, top, right, bottom)
|
||||
|
||||
|
||||
def resolve_region(region: Optional[Region] = None,
|
||||
window: Union[int, str, None] = None) -> Optional[Tuple[int, int, int, int]]:
|
||||
"""解析截图区域:window 优先,其次 region,都没有返回 None(=全屏)。"""
|
||||
if window is not None:
|
||||
return tuple(int(v) for v in window_rect(window)) # type: ignore[return-value]
|
||||
if region is not None:
|
||||
if len(region) != 4:
|
||||
raise ValueError(f"region 必须是 (left, top, right, bottom),收到:{region}")
|
||||
left, top, right, bottom = (int(v) for v in region)
|
||||
if right <= left or bottom <= top:
|
||||
raise ValueError(f"region 无效(right<=left 或 bottom<=top):{region}")
|
||||
return left, top, right, bottom
|
||||
return None
|
||||
|
||||
|
||||
def grab(region: Optional[Region] = None,
|
||||
window: Union[int, str, None] = None) -> Tuple[np.ndarray, Tuple[int, int, int, int]]:
|
||||
"""截屏,返回 (BGR 图, 屏幕区域 (left, top, right, bottom))。
|
||||
|
||||
- 不传参数 = 全屏(多显示器时包含所有屏幕,坐标为虚拟屏幕坐标,可能为负);
|
||||
- 传 window = 只截该窗口矩形(含被其它窗口遮挡的部分?不——截的是屏幕实际显示内容);
|
||||
- 传 region = 只截该区域。
|
||||
"""
|
||||
ensure_dpi_aware()
|
||||
reg = resolve_region(region, window)
|
||||
bbox = tuple(reg) if reg else None
|
||||
shot = ImageGrab.grab(bbox=bbox, all_screens=True)
|
||||
img = cv2.cvtColor(np.asarray(shot), cv2.COLOR_RGB2BGR)
|
||||
if reg is None:
|
||||
reg = (0, 0, img.shape[1], img.shape[0])
|
||||
return img, reg
|
||||
|
||||
|
||||
def save_image(img: np.ndarray, path: str) -> str:
|
||||
"""保存图片(支持中文路径),返回绝对路径。"""
|
||||
path = os.path.abspath(path)
|
||||
parent = os.path.dirname(path)
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
ext = os.path.splitext(path)[1] or ".png"
|
||||
ok, buf = cv2.imencode(ext, img)
|
||||
if not ok:
|
||||
raise RuntimeError(f"图片编码失败:{path}")
|
||||
buf.tofile(path) # 用 tofile 而不是 imwrite,兼容中文路径
|
||||
return path
|
||||
|
||||
|
||||
def screenshot(path: str = "", region: Optional[Region] = None,
|
||||
window: Union[int, str, None] = None) -> str:
|
||||
"""截图并保存;path 为空时保存到当前目录 shot_<时间戳>.png。返回文件路径。"""
|
||||
img, _ = grab(region=region, window=window)
|
||||
if not path:
|
||||
path = os.path.join(os.getcwd(), f"shot_{time.strftime('%Y%m%d_%H%M%S')}.png")
|
||||
return save_image(img, path)
|
||||
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""剪贴板读写(纯 ctypes,不依赖 pyperclip)。
|
||||
|
||||
桌面自动化里剪贴板有两个关键用途:
|
||||
1. 输入中文/长文本:写剪贴板 + Ctrl+V,比逐字发送稳定得多(不受输入法影响);
|
||||
2. 读取界面文本:全选复制后读剪贴板,比 OCR 准确(但会覆盖用户剪贴板,用完可 restore)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
from typing import Optional
|
||||
|
||||
from ._win32 import require_windows
|
||||
|
||||
CF_UNICODETEXT = 13
|
||||
GMEM_MOVEABLE = 0x0002
|
||||
|
||||
_OPEN_RETRY = 8 # 剪贴板可能被其它进程短暂占用,重试打开
|
||||
_OPEN_INTERVAL = 0.03
|
||||
|
||||
|
||||
def _open() -> None:
|
||||
"""打开剪贴板(带重试),失败抛错。"""
|
||||
user32 = ctypes.windll.user32
|
||||
for _ in range(_OPEN_RETRY):
|
||||
if user32.OpenClipboard(None):
|
||||
return
|
||||
time.sleep(_OPEN_INTERVAL)
|
||||
raise RuntimeError("打开剪贴板失败(可能被其它程序占用)")
|
||||
|
||||
|
||||
def _close() -> None:
|
||||
try:
|
||||
ctypes.windll.user32.CloseClipboard()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def set_text(text: str) -> None:
|
||||
"""把文本写入剪贴板(覆盖原内容)。"""
|
||||
require_windows("剪贴板写入")
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
user32 = ctypes.windll.user32
|
||||
kernel32.GlobalAlloc.restype = ctypes.c_void_p
|
||||
kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t]
|
||||
kernel32.GlobalLock.restype = ctypes.c_void_p
|
||||
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
|
||||
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
|
||||
user32.SetClipboardData.argtypes = [wintypes.UINT, ctypes.c_void_p]
|
||||
user32.SetClipboardData.restype = ctypes.c_void_p
|
||||
|
||||
data = (str(text) + "\x00").encode("utf-16-le")
|
||||
_open()
|
||||
handle = None
|
||||
try:
|
||||
user32.EmptyClipboard()
|
||||
handle = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
|
||||
if not handle:
|
||||
raise RuntimeError("剪贴板内存分配失败")
|
||||
ptr = kernel32.GlobalLock(handle)
|
||||
if not ptr:
|
||||
raise RuntimeError("剪贴板内存锁定失败")
|
||||
try:
|
||||
ctypes.memmove(ptr, data, len(data))
|
||||
finally:
|
||||
kernel32.GlobalUnlock(handle)
|
||||
if not user32.SetClipboardData(CF_UNICODETEXT, handle):
|
||||
raise RuntimeError("写入剪贴板失败")
|
||||
handle = None # 所有权已交系统,不能再释放
|
||||
finally:
|
||||
if handle:
|
||||
kernel32.GlobalFree(ctypes.c_void_p(handle))
|
||||
_close()
|
||||
|
||||
|
||||
def get_text() -> str:
|
||||
"""读取剪贴板文本;剪贴板里没有文本时返回空串(不会抛错)。"""
|
||||
require_windows("剪贴板读取")
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
user32 = ctypes.windll.user32
|
||||
user32.GetClipboardData.argtypes = [wintypes.UINT]
|
||||
user32.GetClipboardData.restype = ctypes.c_void_p
|
||||
kernel32.GlobalLock.restype = ctypes.c_void_p
|
||||
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
|
||||
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
|
||||
|
||||
_open()
|
||||
try:
|
||||
if not user32.IsClipboardFormatAvailable(CF_UNICODETEXT):
|
||||
return ""
|
||||
handle = user32.GetClipboardData(CF_UNICODETEXT)
|
||||
if not handle:
|
||||
return ""
|
||||
ptr = kernel32.GlobalLock(ctypes.c_void_p(handle))
|
||||
if not ptr:
|
||||
return ""
|
||||
try:
|
||||
return ctypes.wstring_at(ptr) or ""
|
||||
finally:
|
||||
kernel32.GlobalUnlock(ctypes.c_void_p(handle))
|
||||
finally:
|
||||
_close()
|
||||
|
||||
|
||||
def paste(text: str, restore: bool = True, delay: float = 0.05) -> str:
|
||||
"""写剪贴板 → Ctrl+V 粘贴 →(可选)恢复原剪贴板内容。返回被恢复的原文本。
|
||||
|
||||
Args:
|
||||
text: 要粘贴的文本(中文、长文本都走这条最稳)。
|
||||
restore: 粘贴后把剪贴板恢复成原内容,避免污染用户剪贴板。
|
||||
delay: 写入剪贴板后等待时间(秒),太短可能粘贴到旧内容。
|
||||
"""
|
||||
from . import keys # 延迟导入,避免循环依赖
|
||||
old: Optional[str] = None
|
||||
if restore:
|
||||
try:
|
||||
old = get_text()
|
||||
except Exception: # noqa: BLE001
|
||||
old = None
|
||||
set_text(text)
|
||||
time.sleep(max(0.02, delay))
|
||||
keys.hotkey("ctrl", "v")
|
||||
if restore and old is not None:
|
||||
time.sleep(max(0.05, delay))
|
||||
try:
|
||||
set_text(old)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return old or ""
|
||||
@@ -0,0 +1,207 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""找色与界面差异:不需要模板图的「轻量识图」。
|
||||
|
||||
典型用途:
|
||||
- find_color:找状态点(红/绿圆点)、高亮行、进度条颜色,判断「有没有变红/变绿」;
|
||||
- diff:比对两次截图,判断界面有没有变化(比找具体元素更鲁棒,也能判断卡死/无响应)。
|
||||
|
||||
颜色约定:对外一律用 RGB(`"#FF3B30"` / `(255, 59, 48)` / `"255,59,48"`),内部转 BGR。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import cv2
|
||||
except ImportError as _e: # pragma: no cover
|
||||
raise RuntimeError("缺少依赖 opencv-python,请安装:pip install opencv-python numpy pillow") from _e
|
||||
|
||||
from . import capture
|
||||
|
||||
RGB = Tuple[int, int, int]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ColorMatch:
|
||||
"""一块同色区域(连通域)的位置与面积。"""
|
||||
|
||||
left: int
|
||||
top: int
|
||||
width: int
|
||||
height: int
|
||||
area: int
|
||||
color: RGB
|
||||
|
||||
@property
|
||||
def center(self) -> Tuple[int, int]:
|
||||
return self.left + self.width // 2, self.top + self.height // 2
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"left": int(self.left), "top": int(self.top),
|
||||
"width": int(self.width), "height": int(self.height),
|
||||
"area": int(self.area), "color": list(self.color),
|
||||
"center": list(self.center)}
|
||||
|
||||
def __str__(self) -> str:
|
||||
cx, cy = self.center
|
||||
return (f"ColorMatch({self.color} ({self.left},{self.top}) {self.width}x{self.height} "
|
||||
f"area={self.area} center=({cx},{cy}))")
|
||||
|
||||
|
||||
# ==================== 颜色解析 ====================
|
||||
def parse_color(color: Union[str, Sequence[int]]) -> RGB:
|
||||
"""解析颜色为 (r, g, b);支持 "#RRGGBB"、"#RGB"、"(r,g,b)"、"r,g,b"。"""
|
||||
if isinstance(color, str):
|
||||
s = color.strip().lstrip("#")
|
||||
if "," in s:
|
||||
parts = [p.strip() for p in s.split(",")]
|
||||
else:
|
||||
if len(s) == 3:
|
||||
s = "".join(ch * 2 for ch in s)
|
||||
if len(s) != 6:
|
||||
raise ValueError(f"颜色格式不正确:{color}(支持 #RRGGBB 或 r,g,b)")
|
||||
parts = [s[0:2], s[2:4], s[4:6]]
|
||||
try:
|
||||
return tuple(int(p, 16) for p in parts) # type: ignore[return-value]
|
||||
except ValueError as e:
|
||||
raise ValueError(f"颜色格式不正确:{color}") from e
|
||||
values = []
|
||||
for p in parts:
|
||||
try:
|
||||
v = int(float(p))
|
||||
except ValueError as e:
|
||||
raise ValueError(f"颜色格式不正确:{color}") from e
|
||||
values.append(max(0, min(255, v)))
|
||||
if len(values) != 3:
|
||||
raise ValueError(f"颜色需要 3 个分量:{color}")
|
||||
return values[0], values[1], values[2] # type: ignore[return-value]
|
||||
if isinstance(color, (tuple, list)) and len(color) == 3:
|
||||
return tuple(max(0, min(255, int(v))) for v in color) # type: ignore[return-value]
|
||||
raise ValueError(f"颜色格式不正确:{color}")
|
||||
|
||||
|
||||
def _rgb_to_bgr(rgb: RGB) -> Tuple[int, int, int]:
|
||||
return int(rgb[2]), int(rgb[1]), int(rgb[0])
|
||||
|
||||
|
||||
# ==================== 找色 ====================
|
||||
def find_color_in(image: np.ndarray, color: Union[str, Sequence[int]],
|
||||
tolerance: int = 12, min_area: int = 4,
|
||||
max_results: int = 0, origin: Tuple[int, int] = (0, 0)) -> List[ColorMatch]:
|
||||
"""在一张图里找指定颜色(及容差范围内)的连通区域。"""
|
||||
rgb = parse_color(color)
|
||||
b, g, r = _rgb_to_bgr(rgb)
|
||||
tol = max(0, int(tolerance))
|
||||
lower = np.array([max(0, b - tol), max(0, g - tol), max(0, r - tol)], dtype=np.uint8)
|
||||
upper = np.array([min(255, b + tol), min(255, g + tol), min(255, r + tol)], dtype=np.uint8)
|
||||
mask = cv2.inRange(image, lower, upper)
|
||||
count, _labels, stats, _centroids = cv2.connectedComponentsWithStats(mask, connectivity=8)
|
||||
out: List[ColorMatch] = []
|
||||
for i in range(1, count): # 0 = 背景
|
||||
x, y, w, h, area = (int(v) for v in stats[i][:5])
|
||||
if area < max(0, int(min_area)):
|
||||
continue
|
||||
out.append(ColorMatch(left=x + int(origin[0]), top=y + int(origin[1]),
|
||||
width=w, height=h, area=area, color=rgb))
|
||||
out.sort(key=lambda c: c.area, reverse=True)
|
||||
if max_results and max_results > 0:
|
||||
out = out[:max_results]
|
||||
return out
|
||||
|
||||
|
||||
def find_color(color: Union[str, Sequence[int]], tolerance: int = 12,
|
||||
region: Optional[Sequence[int]] = None,
|
||||
window: Union[int, str, None] = None,
|
||||
min_area: int = 4, max_results: int = 0) -> List[ColorMatch]:
|
||||
"""实时截图找色,返回区域列表(坐标已换算成屏幕坐标,按面积降序)。"""
|
||||
img, reg = capture.grab(region=region, window=window)
|
||||
return find_color_in(img, color, tolerance=tolerance, min_area=min_area,
|
||||
max_results=max_results, origin=(reg[0], reg[1]))
|
||||
|
||||
|
||||
def find_colors(colors: Sequence[Union[str, Sequence[int]]], tolerance: int = 12,
|
||||
region: Optional[Sequence[int]] = None,
|
||||
window: Union[int, str, None] = None,
|
||||
min_area: int = 4, max_results: int = 0) -> Dict[str, List[ColorMatch]]:
|
||||
"""一次截图、找多种颜色(避免多次截屏),返回 {颜色文本: [ColorMatch...]}。"""
|
||||
img, reg = capture.grab(region=region, window=window)
|
||||
out: Dict[str, List[ColorMatch]] = {}
|
||||
for c in colors:
|
||||
rgb = parse_color(c)
|
||||
out[str(c)] = find_color_in(img, rgb, tolerance=tolerance, min_area=min_area,
|
||||
max_results=max_results, origin=(reg[0], reg[1]))
|
||||
return out
|
||||
|
||||
|
||||
# ==================== 界面差异 ====================
|
||||
def _load(image: Union[str, np.ndarray]) -> np.ndarray:
|
||||
if isinstance(image, np.ndarray):
|
||||
return image
|
||||
from .matcher import load_template # 复用「兼容中文路径」的读取
|
||||
return load_template(str(image))
|
||||
|
||||
|
||||
def diff(a: Union[str, np.ndarray], b: Optional[Union[str, np.ndarray]] = None,
|
||||
tolerance: int = 10, min_area: int = 30,
|
||||
region: Optional[Sequence[int]] = None,
|
||||
window: Union[int, str, None] = None) -> dict:
|
||||
"""比对两张图(或「给定图 vs 当前截图」),返回变化比例与变化区域。
|
||||
|
||||
Args:
|
||||
a: 基准图(路径或 ndarray)。
|
||||
b: 对比图;None 时现场按 region/window 截一帧(要求与 a 同尺寸)。
|
||||
tolerance: 像素差阈值(0~255),越大越宽松。
|
||||
min_area: 变化区域最小面积(过滤噪点/光标闪烁)。
|
||||
region / window: b 为 None 时的截图范围。
|
||||
|
||||
Returns:
|
||||
{"changed": bool, "changed_ratio": float, "boxes": [{"left","top","width","height","center"}],
|
||||
"image": 差异可视化 ndarray(变化区域画红框)}
|
||||
"""
|
||||
img_a = _load(a)
|
||||
if b is None:
|
||||
img_b, reg = capture.grab(region=region, window=window)
|
||||
ox, oy = int(reg[0]), int(reg[1])
|
||||
else:
|
||||
img_b = _load(b)
|
||||
ox, oy = 0, 0
|
||||
|
||||
if img_a.shape[:2] != img_b.shape[:2]:
|
||||
img_b = cv2.resize(img_b, (img_a.shape[1], img_a.shape[0]), interpolation=cv2.INTER_AREA)
|
||||
|
||||
gray_a = cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY) if img_a.ndim == 3 else img_a
|
||||
gray_b = cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY) if img_b.ndim == 3 else img_b
|
||||
delta = cv2.absdiff(gray_a, gray_b)
|
||||
_thr, mask = cv2.threshold(delta, max(0, int(tolerance)), 255, cv2.THRESH_BINARY)
|
||||
changed_px = int(np.count_nonzero(mask))
|
||||
total_px = int(mask.shape[0] * mask.shape[1]) or 1
|
||||
|
||||
boxes: List[dict] = []
|
||||
count, _labels, stats, _c = cv2.connectedComponentsWithStats(mask, connectivity=8)
|
||||
for i in range(1, count):
|
||||
x, y, w, h, area = (int(v) for v in stats[i][:5])
|
||||
if area < max(0, int(min_area)):
|
||||
continue
|
||||
boxes.append({"left": x + ox, "top": y + oy, "width": w, "height": h,
|
||||
"center": [x + ox + w // 2, y + oy + h // 2]})
|
||||
boxes.sort(key=lambda bx: (bx["top"], bx["left"]))
|
||||
|
||||
vis = img_b.copy() if img_b.ndim == 3 else cv2.cvtColor(img_b, cv2.COLOR_GRAY2BGR)
|
||||
for bx in boxes:
|
||||
cv2.rectangle(vis, (bx["left"] - ox, bx["top"] - oy),
|
||||
(bx["left"] - ox + bx["width"], bx["top"] - oy + bx["height"]), (0, 0, 255), 2)
|
||||
|
||||
return {"changed": bool(boxes) or changed_px > 0,
|
||||
"changed_ratio": round(changed_px / total_px, 4),
|
||||
"boxes": boxes, "image": vis}
|
||||
|
||||
|
||||
def diff_ratio(a: Union[str, np.ndarray], b: Optional[Union[str, np.ndarray]] = None,
|
||||
tolerance: int = 10, region: Optional[Sequence[int]] = None,
|
||||
window: Union[int, str, None] = None) -> float:
|
||||
"""只要变化比例(0~1)时用这个,比 diff() 轻。"""
|
||||
return float(diff(a, b, tolerance=tolerance, min_area=1,
|
||||
region=region, window=window)["changed_ratio"])
|
||||
@@ -0,0 +1,217 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""文件与文件夹(对应影刀 file / dir 组指令):判断存在、建目录、读写文本、复制移动删除、遍历、等文件。
|
||||
|
||||
设计取舍:只封「高频且容易写错的小动作」(编码回退、目标目录自动创建、等文件落地),
|
||||
不重复造 pandas / openpyxl / shutil 的轮子。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Union
|
||||
|
||||
PathLike = Union[str, os.PathLike]
|
||||
|
||||
# 读文本时的编码回退顺序(Windows 上 Excel 导出的 csv/txt 常是 GBK)
|
||||
_TEXT_ENCODINGS = ("utf-8-sig", "gbk")
|
||||
|
||||
|
||||
# ==================== 判断 / 创建 ====================
|
||||
def exists(path: PathLike) -> bool:
|
||||
"""路径是否存在(文件或文件夹;影刀「IF 文件存在」)。"""
|
||||
return os.path.exists(str(path))
|
||||
|
||||
|
||||
def file_exists(path: PathLike) -> bool:
|
||||
"""是否是已存在的文件(不含目录)。"""
|
||||
return os.path.isfile(str(path))
|
||||
|
||||
|
||||
def dir_exists(path: PathLike) -> bool:
|
||||
"""是否是已存在的文件夹。"""
|
||||
return os.path.isdir(str(path))
|
||||
|
||||
|
||||
def ensure_dir(path: PathLike) -> str:
|
||||
"""确保目录存在(不存在则递归创建),返回绝对路径。"""
|
||||
p = os.path.abspath(str(path))
|
||||
os.makedirs(p, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def make_dir(parent: PathLike, name: str = "") -> str:
|
||||
"""创建文件夹(影刀「创建文件夹」):parent 下建 name,name 为空则直接创建 parent。"""
|
||||
target = os.path.abspath(os.path.join(str(parent), str(name))) if str(name) else os.path.abspath(str(parent))
|
||||
os.makedirs(target, exist_ok=True)
|
||||
return target
|
||||
|
||||
|
||||
# ==================== 读写文本 ====================
|
||||
def read_text(path: PathLike, encoding: Optional[str] = None) -> str:
|
||||
"""读文本文件。encoding 为空时依次尝试 UTF-8(带BOM) → GBK。
|
||||
|
||||
中文路径、GBK 编码的 csv/log 都能直接读,不用每次手写 try/except。
|
||||
"""
|
||||
p = str(path)
|
||||
if not os.path.isfile(p):
|
||||
raise RuntimeError(f"文件不存在:{p}")
|
||||
if encoding:
|
||||
return Path(p).read_text(encoding=encoding)
|
||||
last_err: Optional[Exception] = None
|
||||
for enc in _TEXT_ENCODINGS:
|
||||
try:
|
||||
return Path(p).read_text(encoding=enc)
|
||||
except UnicodeDecodeError as e:
|
||||
last_err = e
|
||||
raise RuntimeError(f"无法识别文本编码(试过 {_TEXT_ENCODINGS}):{p}({last_err})")
|
||||
|
||||
|
||||
def write_text(path: PathLike, text: str, encoding: str = "utf-8",
|
||||
append: bool = False) -> str:
|
||||
"""写文本文件(自动创建父目录),返回绝对路径。"""
|
||||
p = os.path.abspath(str(path))
|
||||
parent = os.path.dirname(p)
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
with open(p, "a" if append else "w", encoding=encoding, newline="") as f:
|
||||
f.write("" if text is None else str(text))
|
||||
return p
|
||||
|
||||
|
||||
def append_line(path: PathLike, text: str, encoding: str = "utf-8") -> str:
|
||||
"""追加一行(自动补换行)。"""
|
||||
return write_text(path, str(text) + "\n", encoding=encoding, append=True)
|
||||
|
||||
|
||||
# ==================== 复制 / 移动 / 删除 ====================
|
||||
def copy(src: PathLike, dst: PathLike, overwrite: bool = True) -> str:
|
||||
"""复制文件或文件夹;dst 是已存在目录时把 src 放进去。返回目标路径。"""
|
||||
s, d = str(src), str(dst)
|
||||
if not os.path.exists(s):
|
||||
raise RuntimeError(f"源路径不存在:{s}")
|
||||
if os.path.isdir(d):
|
||||
d = os.path.join(d, os.path.basename(s.rstrip("\\/")))
|
||||
parent = os.path.dirname(os.path.abspath(d))
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
if os.path.exists(d) and not overwrite:
|
||||
raise RuntimeError(f"目标已存在且 overwrite=False:{d}")
|
||||
if os.path.isdir(s):
|
||||
shutil.copytree(s, d, dirs_exist_ok=overwrite)
|
||||
else:
|
||||
shutil.copy2(s, d)
|
||||
return os.path.abspath(d)
|
||||
|
||||
|
||||
def move(src: PathLike, dst: PathLike, overwrite: bool = True) -> str:
|
||||
"""移动/重命名文件或文件夹;dst 是已存在目录时移入该目录。返回目标路径。"""
|
||||
s, d = str(src), str(dst)
|
||||
if not os.path.exists(s):
|
||||
raise RuntimeError(f"源路径不存在:{s}")
|
||||
if os.path.isdir(d):
|
||||
d = os.path.join(d, os.path.basename(s.rstrip("\\/")))
|
||||
parent = os.path.dirname(os.path.abspath(d))
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
if os.path.exists(d):
|
||||
if not overwrite:
|
||||
raise RuntimeError(f"目标已存在且 overwrite=False:{d}")
|
||||
delete(d)
|
||||
shutil.move(s, d)
|
||||
return os.path.abspath(d)
|
||||
|
||||
|
||||
def delete(path: PathLike, missing_ok: bool = True) -> bool:
|
||||
"""删除文件或文件夹(递归)。返回是否真的删掉了东西。"""
|
||||
p = str(path)
|
||||
if not os.path.exists(p):
|
||||
if missing_ok:
|
||||
return False
|
||||
raise RuntimeError(f"路径不存在:{p}")
|
||||
if os.path.isdir(p):
|
||||
shutil.rmtree(p)
|
||||
else:
|
||||
os.remove(p)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 遍历 / 等待 ====================
|
||||
def list_files(folder: PathLike, pattern: str = "*", recursive: bool = False,
|
||||
ext: Union[str, List[str], None] = None) -> List[str]:
|
||||
"""列出文件(返回绝对路径,按名称排序)。
|
||||
|
||||
Args:
|
||||
pattern: 文件名通配符,如 "*.xlsx"、"工资*"。
|
||||
recursive: 是否递归子目录。
|
||||
ext: 扩展名过滤,如 ".xlsx" 或 [".xlsx", ".xls"](大小写不敏感)。
|
||||
"""
|
||||
folder = str(folder)
|
||||
if not os.path.isdir(folder):
|
||||
return []
|
||||
exts = None
|
||||
if ext:
|
||||
exts = tuple(([ext] if isinstance(ext, str) else list(ext)))
|
||||
exts = tuple((e if e.startswith(".") else "." + e).lower() for e in exts)
|
||||
|
||||
out: List[str] = []
|
||||
if recursive:
|
||||
for root, _dirs, files in os.walk(folder):
|
||||
for name in files:
|
||||
if not fnmatch.fnmatch(name, pattern):
|
||||
continue
|
||||
if exts and not name.lower().endswith(exts):
|
||||
continue
|
||||
out.append(os.path.join(root, name))
|
||||
else:
|
||||
for name in os.listdir(folder):
|
||||
full = os.path.join(folder, name)
|
||||
if not os.path.isfile(full):
|
||||
continue
|
||||
if not fnmatch.fnmatch(name, pattern):
|
||||
continue
|
||||
if exts and not name.lower().endswith(exts):
|
||||
continue
|
||||
out.append(full)
|
||||
out.sort()
|
||||
return out
|
||||
|
||||
|
||||
def newest_file(folder: PathLike, pattern: str = "*", recursive: bool = False) -> Optional[str]:
|
||||
"""目录里最新的文件(按修改时间),没有返回 None(下载目录里取最新导出文件时用)。"""
|
||||
files = list_files(folder, pattern=pattern, recursive=recursive)
|
||||
if not files:
|
||||
return None
|
||||
return max(files, key=lambda p: os.path.getmtime(p))
|
||||
|
||||
|
||||
def wait_file(path: PathLike, timeout: float = 30.0, interval: float = 0.5,
|
||||
min_size: int = 1) -> bool:
|
||||
"""等待文件出现且大小稳定(>= min_size),超时返回 False。用于等下载/导出落地。"""
|
||||
p = str(path)
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
try:
|
||||
if os.path.isfile(p) and os.path.getsize(p) >= max(0, int(min_size)):
|
||||
time.sleep(0.2) # 再确认一次,避免读到写了一半的文件
|
||||
if os.path.isfile(p) and os.path.getsize(p) >= max(0, int(min_size)):
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
|
||||
|
||||
def wait_file_gone(path: PathLike, timeout: float = 30.0, interval: float = 0.5) -> bool:
|
||||
"""等待文件消失(如临时锁文件释放),超时返回 False。"""
|
||||
p = str(path)
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
if not os.path.exists(p):
|
||||
return True
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
@@ -0,0 +1,265 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""键盘输入(纯 ctypes SendInput,不依赖 pyautogui / keyboard)。
|
||||
|
||||
三种用法:
|
||||
- `type_text("abc")` 逐字符 Unicode 注入,不经过输入法;
|
||||
- `type_text("中文内容", method="clipboard")` 写剪贴板 + Ctrl+V(中文/长文本最稳);
|
||||
- `press("enter")` / `hotkey("ctrl", "s")` 单键与组合键。
|
||||
|
||||
限制:
|
||||
- 只支持命名键 + 字母/数字/F1~F12;符号请用 type_text(避免键盘布局差异);
|
||||
- 目标窗口以管理员权限运行时,普通权限进程的输入会被 UIPI 拦截(SendInput 返回 0)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
from typing import Iterable, List, Optional, Sequence
|
||||
|
||||
from ._win32 import require_windows
|
||||
|
||||
logger = logging.getLogger("desktopauto")
|
||||
|
||||
INPUT_KEYBOARD = 1
|
||||
KEYEVENTF_EXTENDEDKEY = 0x0001
|
||||
KEYEVENTF_KEYUP = 0x0002
|
||||
KEYEVENTF_UNICODE = 0x0004
|
||||
|
||||
_BATCH = 64 # 每批发送的键盘事件数(太多会拖慢目标窗口处理)
|
||||
|
||||
|
||||
# ==================== SendInput 结构 ====================
|
||||
class KEYBDINPUT(ctypes.Structure):
|
||||
_fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD),
|
||||
("time", wintypes.DWORD), ("dwExtraInfo", ctypes.c_void_p)]
|
||||
|
||||
|
||||
class MOUSEINPUT(ctypes.Structure):
|
||||
_fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD),
|
||||
("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD),
|
||||
("dwExtraInfo", ctypes.c_void_p)]
|
||||
|
||||
|
||||
class HARDWAREINPUT(ctypes.Structure):
|
||||
_fields_ = [("uMsg", wintypes.DWORD), ("wParamL", wintypes.WORD), ("wParamH", wintypes.WORD)]
|
||||
|
||||
|
||||
class _INPUTUNION(ctypes.Union):
|
||||
_fields_ = [("ki", KEYBDINPUT), ("mi", MOUSEINPUT), ("hi", HARDWAREINPUT)]
|
||||
|
||||
|
||||
class INPUT(ctypes.Structure):
|
||||
_fields_ = [("type", wintypes.DWORD), ("union", _INPUTUNION)]
|
||||
|
||||
|
||||
def _key_input(vk: int, flags: int, scan: int = 0) -> INPUT:
|
||||
ki = KEYBDINPUT(wVk=vk, wScan=scan, dwFlags=flags, time=0, dwExtraInfo=None)
|
||||
return INPUT(type=INPUT_KEYBOARD, union=_INPUTUNION(ki=ki))
|
||||
|
||||
|
||||
def _send(inputs: Sequence[INPUT]) -> None:
|
||||
if not inputs:
|
||||
return
|
||||
n = len(inputs)
|
||||
arr = (INPUT * n)(*inputs)
|
||||
sent = ctypes.windll.user32.SendInput(n, arr, ctypes.sizeof(INPUT))
|
||||
if sent != n:
|
||||
raise RuntimeError(
|
||||
f"键盘事件发送失败(SendInput {sent}/{n})。常见原因:目标窗口以管理员权限运行,"
|
||||
f"而本进程不是(UIPI 拦截)")
|
||||
|
||||
|
||||
# ==================== 键名 → 虚拟键码 ====================
|
||||
VK: dict = {
|
||||
"ctrl": 0x11, "control": 0x11, "shift": 0x10, "alt": 0x12, "win": 0x5B, "meta": 0x5B,
|
||||
"enter": 0x0D, "return": 0x0D, "tab": 0x09, "esc": 0x1B, "escape": 0x1B, "space": 0x20,
|
||||
"backspace": 0x08, "delete": 0x2E, "del": 0x2E, "insert": 0x2D, "ins": 0x2D,
|
||||
"home": 0x24, "end": 0x23, "pageup": 0x21, "pgup": 0x21, "pagedown": 0x22, "pgdn": 0x22,
|
||||
"up": 0x26, "down": 0x28, "left": 0x25, "right": 0x27,
|
||||
"capslock": 0x14, "printscreen": 0x2C, "prtsc": 0x2C, "apps": 0x5D, "menu": 0x5D,
|
||||
"num0": 0x60, "num1": 0x61, "num2": 0x62, "num3": 0x63, "num4": 0x64,
|
||||
"num5": 0x65, "num6": 0x66, "num7": 0x67, "num8": 0x68, "num9": 0x69,
|
||||
"numlock": 0x90, "scrolllock": 0x91, "pause": 0x13,
|
||||
}
|
||||
VK.update({f"f{i}": 0x6F + i for i in range(1, 13)}) # f1=0x70 ... f12=0x7B
|
||||
|
||||
|
||||
def to_vk(key: str) -> int:
|
||||
"""把键名转虚拟键码;支持 ctrl/enter/f5/a/0 等,未知键抛 ValueError。"""
|
||||
k = str(key).strip().lower()
|
||||
if not k:
|
||||
raise ValueError("键名不能为空")
|
||||
if k in VK:
|
||||
return VK[k]
|
||||
if len(k) == 1 and (k.isalpha() or k.isdigit()):
|
||||
return ord(k.upper())
|
||||
raise ValueError(f"不支持的键名:{key}(可用:字母/数字/F1-F12/ctrl/shift/alt/enter/tab/esc/"
|
||||
f"space/backspace/delete/home/end/pageup/pagedown/up/down/left/right 等;"
|
||||
f"符号请用 type_text)")
|
||||
|
||||
|
||||
# ==================== 单键 / 组合键 ====================
|
||||
def press(key: str, times: int = 1, interval: float = 0.05) -> None:
|
||||
"""按一次(或连按多次)某个键。"""
|
||||
require_windows("键盘按键")
|
||||
vk = to_vk(key)
|
||||
for i in range(max(1, int(times))):
|
||||
_send([_key_input(vk, 0), _key_input(vk, KEYEVENTF_KEYUP)])
|
||||
if i < times - 1:
|
||||
time.sleep(max(0.01, interval))
|
||||
|
||||
|
||||
def key_down(key: str) -> None:
|
||||
"""按住某个键(配合 key_up 做长按/拖选)。"""
|
||||
require_windows("键盘按键")
|
||||
_send([_key_input(to_vk(key), 0)])
|
||||
|
||||
|
||||
def key_up(key: str) -> None:
|
||||
"""松开某个键。"""
|
||||
require_windows("键盘按键")
|
||||
_send([_key_input(to_vk(key), KEYEVENTF_KEYUP)])
|
||||
|
||||
|
||||
def hotkey(*keys: str, interval: float = 0.02) -> None:
|
||||
"""组合键:按顺序按下,再反向松开。hotkey("ctrl", "shift", "s")。"""
|
||||
require_windows("组合键")
|
||||
if not keys:
|
||||
raise ValueError("hotkey 至少需要一个键")
|
||||
vks: List[int] = [to_vk(k) for k in keys]
|
||||
for vk in vks:
|
||||
_send([_key_input(vk, 0)])
|
||||
time.sleep(max(0.005, interval))
|
||||
for vk in reversed(vks):
|
||||
_send([_key_input(vk, KEYEVENTF_KEYUP)])
|
||||
time.sleep(max(0.005, interval))
|
||||
|
||||
|
||||
# ==================== 文本输入 ====================
|
||||
def type_text(text: str, method: str = "auto", interval: float = 0.01,
|
||||
restore_clipboard: bool = True) -> None:
|
||||
"""输入文本。
|
||||
|
||||
Args:
|
||||
text: 要输入的内容。
|
||||
method: auto=含非 ASCII 自动走剪贴板,否则 Unicode 注入;
|
||||
unicode=强制逐字符注入;clipboard=强制复制粘贴(中文最稳)。
|
||||
interval: 字符间隔(unicode 模式),或剪贴板模式的等待时间。
|
||||
restore_clipboard: 剪贴板模式下,粘贴完恢复原剪贴板内容。
|
||||
"""
|
||||
require_windows("文本输入")
|
||||
text = "" if text is None else str(text)
|
||||
if not text:
|
||||
return
|
||||
method = (method or "auto").lower()
|
||||
if method == "auto":
|
||||
method = "clipboard" if any(ord(c) > 127 for c in text) else "unicode"
|
||||
if method not in ("unicode", "clipboard"):
|
||||
raise ValueError(f"不支持的输入方式:{method}(可选 auto/unicode/clipboard)")
|
||||
|
||||
if method == "clipboard":
|
||||
from . import clipboard # 延迟导入,避免循环依赖
|
||||
clipboard.paste(text, restore=restore_clipboard, delay=max(0.05, interval))
|
||||
return
|
||||
|
||||
# Unicode 注入:把文本按 UTF-16 编码成一组 KEYEVENTF_UNICODE 事件
|
||||
units = text.encode("utf-16-le")
|
||||
inputs: List[INPUT] = []
|
||||
for i in range(0, len(units), 2):
|
||||
code = int.from_bytes(units[i:i + 2], "little")
|
||||
inputs.append(_key_input(0, KEYEVENTF_UNICODE, scan=code))
|
||||
inputs.append(_key_input(0, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, scan=code))
|
||||
for start in range(0, len(inputs), _BATCH * 2):
|
||||
_send(inputs[start:start + _BATCH * 2])
|
||||
if interval:
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
def write(text: str, method: str = "auto") -> None:
|
||||
"""type_text 的别名(语义更贴近「往当前焦点写内容」)。"""
|
||||
type_text(text, method=method)
|
||||
|
||||
|
||||
# ==================== 影刀 / AutoHotkey 风格按键串 ====================
|
||||
_MOD_PREFIX = {"^": "ctrl", "+": "shift", "%": "alt"}
|
||||
_TYPE_TEXT = "text"
|
||||
_TYPE_KEY = "key"
|
||||
_TYPE_COMBO = "combo"
|
||||
|
||||
|
||||
def parse_send_keys(keys_text: str) -> List[tuple]:
|
||||
"""解析按键串为事件序列:`{ENTER}`=单键、`^a`=Ctrl+A、`%{F4}`=Alt+F4、普通字符=文本。
|
||||
|
||||
返回 [("text", "abc"), ("key", "enter"), ("combo", ["ctrl", "a"]), ...]
|
||||
"""
|
||||
tokens: List[tuple] = []
|
||||
buf: List[str] = []
|
||||
|
||||
def _flush():
|
||||
if buf:
|
||||
tokens.append((_TYPE_TEXT, "".join(buf)))
|
||||
buf.clear()
|
||||
|
||||
s = str(keys_text or "")
|
||||
i = 0
|
||||
while i < len(s):
|
||||
ch = s[i]
|
||||
if ch == "{":
|
||||
j = s.find("}", i)
|
||||
if j == -1:
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
name = s[i + 1:j].strip()
|
||||
_flush()
|
||||
if name:
|
||||
tokens.append((_TYPE_KEY, name))
|
||||
i = j + 1
|
||||
continue
|
||||
if ch in _MOD_PREFIX:
|
||||
_flush()
|
||||
mod = _MOD_PREFIX[ch]
|
||||
i += 1
|
||||
if i >= len(s):
|
||||
tokens.append((_TYPE_KEY, mod))
|
||||
continue
|
||||
if s[i] == "{":
|
||||
j = s.find("}", i)
|
||||
name = s[i + 1:j].strip() if j != -1 else s[i + 1:]
|
||||
if name:
|
||||
tokens.append((_TYPE_COMBO, [mod, name]))
|
||||
i = (j + 1) if j != -1 else len(s)
|
||||
else:
|
||||
tokens.append((_TYPE_COMBO, [mod, s[i]]))
|
||||
i += 1
|
||||
continue
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
_flush()
|
||||
return tokens
|
||||
|
||||
|
||||
def send_keys(keys_text: str, interval: float = 0.02, delay_after: float = 0.0) -> None:
|
||||
"""发送按键串(兼容影刀「键盘输入」指令的写法)。
|
||||
|
||||
示例:
|
||||
send_keys("{ENTER}") # 回车
|
||||
send_keys("^a") # Ctrl+A 全选
|
||||
send_keys("%{F4}") # Alt+F4
|
||||
send_keys("^a{DELETE}") # 全选后删除
|
||||
send_keys("abc{ENTER}") # 输入 abc 再回车
|
||||
"""
|
||||
require_windows("键盘输入")
|
||||
for kind, val in parse_send_keys(keys_text):
|
||||
if kind == _TYPE_TEXT:
|
||||
type_text(val)
|
||||
elif kind == _TYPE_KEY:
|
||||
press(val)
|
||||
else:
|
||||
hotkey(*val)
|
||||
if interval:
|
||||
time.sleep(max(0.0, interval))
|
||||
if delay_after and delay_after > 0:
|
||||
time.sleep(float(delay_after))
|
||||
@@ -0,0 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""离线识图标记:在一张给定的图片上找模板并画框标注(不碰真实屏幕/鼠标)。
|
||||
|
||||
用途:
|
||||
- 模板调优:不用真跑自动化,先拿一张截图验证「能不能找到、找到在哪」;
|
||||
- 回归测试:固定截图 + 固定模板,验证改版后识别是否还准;
|
||||
- 上线前预演:标记图上的框中心 = 真实点击会落下的位置,先看一眼再开跑。
|
||||
|
||||
与 Screen 的区别:Screen 走实时截屏 + 真实点击;本模块纯离屏计算,输出一张标注图。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Dict, List, Optional, Sequence, Union
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import cv2
|
||||
except ImportError as _e: # pragma: no cover
|
||||
raise RuntimeError("缺少依赖 opencv-python,请安装:pip install opencv-python numpy pillow") from _e
|
||||
|
||||
from . import capture, matcher as _m
|
||||
from .matcher import Match
|
||||
|
||||
# 多个模板依次使用的框颜色(BGR)
|
||||
_COLORS = [
|
||||
(0, 200, 0), # 绿
|
||||
(255, 140, 0), # 蓝
|
||||
(0, 128, 255), # 橙
|
||||
(200, 0, 200), # 紫
|
||||
(0, 220, 220), # 黄
|
||||
]
|
||||
|
||||
Template = Union[str, np.ndarray]
|
||||
|
||||
|
||||
def _label_text(index: int, score: float) -> str:
|
||||
"""框上标注:序号 + 相似度。只用 ASCII,避免 cv2.putText 画中文变问号。"""
|
||||
return f"#{index} {score:.3f}"
|
||||
|
||||
|
||||
def mark(image: Union[str, np.ndarray],
|
||||
templates: Sequence[Template],
|
||||
out_path: str = "",
|
||||
threshold: float = _m.DEFAULT_THRESHOLD,
|
||||
scales: Sequence[float] = (1.0,),
|
||||
gray: bool = True,
|
||||
draw_click_point: bool = True) -> Dict[str, object]:
|
||||
"""在大图里找多个模板并画框标记,返回结果 dict(不修改原图,除输出文件外无副作用)。
|
||||
|
||||
Args:
|
||||
image: 大图(路径或 BGR ndarray)。
|
||||
templates: 模板列表(路径或 ndarray),同一模板的命中用同一种颜色。
|
||||
out_path: 标注图输出路径;留空则不落盘,只返回内存图(见返回的 image)。
|
||||
threshold: 相似度阈值。
|
||||
scales: 模板缩放集合(跨分辨率时用,如 (0.9, 1.0, 1.1))。
|
||||
gray: 灰度匹配(默认 True)。
|
||||
draw_click_point: 是否在框中心画十字(代表真实点击会落的位置)。
|
||||
|
||||
Returns:
|
||||
{
|
||||
"out": 标注图路径(未落盘时为空串),
|
||||
"image": 标注后的 BGR ndarray,
|
||||
"size": {"width": w, "height": h},
|
||||
"items": [{"index": 1, "template": 文件名, "count": n, "matches": [{...}, ...]}],
|
||||
"total": 命中总数,
|
||||
}
|
||||
"""
|
||||
if isinstance(image, np.ndarray):
|
||||
base = image.copy()
|
||||
else:
|
||||
path = str(image)
|
||||
if not os.path.isfile(path):
|
||||
raise RuntimeError(f"待识别的图片不存在:{path}")
|
||||
base = _m.load_template(path) # 复用「兼容中文路径 + 透明合成」的读取逻辑
|
||||
|
||||
if isinstance(templates, (str, np.ndarray)):
|
||||
templates = [templates]
|
||||
if not templates:
|
||||
raise RuntimeError("至少需要一个模板图")
|
||||
|
||||
items: List[dict] = []
|
||||
total = 0
|
||||
for idx, tpl in enumerate(templates, start=1):
|
||||
matches = _m.match_in(base, tpl, threshold=threshold, scales=scales, gray=gray)
|
||||
total += len(matches)
|
||||
items.append({
|
||||
"index": idx,
|
||||
"template": os.path.basename(str(tpl)) if isinstance(tpl, str) else f"ndarray_{idx}",
|
||||
"count": len(matches),
|
||||
"matches": [m.to_dict() for m in matches],
|
||||
})
|
||||
_draw(base, matches, idx, _COLORS[(idx - 1) % len(_COLORS)], draw_click_point)
|
||||
|
||||
out = ""
|
||||
if out_path:
|
||||
out = capture.save_image(base, out_path)
|
||||
|
||||
return {
|
||||
"out": out,
|
||||
"image": base,
|
||||
"size": {"width": int(base.shape[1]), "height": int(base.shape[0])},
|
||||
"items": items,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
|
||||
def _draw(img: np.ndarray, matches: Sequence[Match], index: int,
|
||||
color: tuple, draw_click_point: bool) -> None:
|
||||
"""在图上画命中框 + 标签 + 中心十字(原地修改)。"""
|
||||
for m in matches:
|
||||
p1 = (int(m.left), int(m.top))
|
||||
p2 = (int(m.left + m.width), int(m.top + m.height))
|
||||
cv2.rectangle(img, p1, p2, color, 2)
|
||||
text = _label_text(index, m.score)
|
||||
ty = p1[1] - 6 if p1[1] >= 14 else p2[1] + 14
|
||||
cv2.putText(img, text, (p1[0], ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA)
|
||||
if draw_click_point:
|
||||
cx, cy = m.center
|
||||
cv2.drawMarker(img, (int(cx), int(cy)), color, cv2.MARKER_CROSS, 12, 1)
|
||||
|
||||
|
||||
def summarize(result: Dict[str, object]) -> str:
|
||||
"""把 mark() 的结果拼成一段可读文本(日志/CLI 输出用)。"""
|
||||
lines = [f"图片尺寸:{result['size']['width']}x{result['size']['height']},命中合计 {result['total']} 处"]
|
||||
for item in result["items"]: # type: ignore[union-attr]
|
||||
lines.append(f" #{item['index']} {item['template']}:{item['count']} 处")
|
||||
for m in item["matches"]:
|
||||
lines.append(f" score={m['score']:.3f} 框=({m['left']},{m['top']}) "
|
||||
f"{m['width']}x{m['height']} 点击点={tuple(m['center'])}")
|
||||
if result.get("out"):
|
||||
lines.append(f"标注图:{result['out']}")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,219 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""模板匹配核心:在一张「屏幕图」里找「模板图」,返回命中位置与相似度。
|
||||
|
||||
算法:cv2.matchTemplate(归一化相关系数),支持
|
||||
- 灰度匹配(默认,快且对细微色差不敏感)或彩色匹配;
|
||||
- 多尺度(scales):模板与屏幕缩放不一致时(不同 DPI 截的图)仍能命中;
|
||||
- 多目标:一次返回所有过阈值的位置,重叠框按相似度去重(NMS);
|
||||
- 透明 PNG:先按白底合成,避免透明区域变黑边导致匹配不上。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Sequence, Tuple, Union
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import cv2
|
||||
except ImportError as _e: # pragma: no cover
|
||||
raise RuntimeError("缺少依赖 opencv-python,请安装:pip install opencv-python numpy pillow") from _e
|
||||
|
||||
DEFAULT_THRESHOLD = 0.85
|
||||
MIN_TEMPLATE_SIDE = 6 # 模板缩放后最小边长(小于此尺寸不可靠)
|
||||
MIN_TEMPLATE_STD = 6.0 # 模板灰度标准差低于此值视为「无纹理」(纯色/近似纯色)
|
||||
|
||||
logger = logging.getLogger("desktopauto")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Match:
|
||||
"""一次命中:匹配框在屏幕上的物理像素位置、尺寸与相似度。"""
|
||||
|
||||
left: int
|
||||
top: int
|
||||
width: int
|
||||
height: int
|
||||
score: float
|
||||
|
||||
@property
|
||||
def center(self) -> Tuple[int, int]:
|
||||
"""匹配框中心点(点击默认点这里)。"""
|
||||
return self.left + self.width // 2, self.top + self.height // 2
|
||||
|
||||
@property
|
||||
def region(self) -> Tuple[int, int, int, int]:
|
||||
"""(left, top, right, bottom)。"""
|
||||
return self.left, self.top, self.left + self.width, self.top + self.height
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"left": int(self.left), "top": int(self.top),
|
||||
"width": int(self.width), "height": int(self.height),
|
||||
"score": round(float(self.score), 4), "center": list(self.center)}
|
||||
|
||||
def __str__(self) -> str:
|
||||
cx, cy = self.center
|
||||
return (f"Match(({self.left},{self.top}) {self.width}x{self.height} "
|
||||
f"score={self.score:.3f} center=({cx},{cy}))")
|
||||
|
||||
|
||||
# ==================== 模板加载 ====================
|
||||
def load_template(template: Union[str, np.ndarray]) -> np.ndarray:
|
||||
"""加载模板为 BGR 图;带透明通道的 PNG 合成到白底(避免透明区变黑)。"""
|
||||
if isinstance(template, np.ndarray):
|
||||
img = template
|
||||
else:
|
||||
path = str(template)
|
||||
if not os.path.isfile(path):
|
||||
raise RuntimeError(f"模板图不存在:{path}")
|
||||
data = np.fromfile(path, dtype=np.uint8) # 兼容中文路径
|
||||
img = cv2.imdecode(data, cv2.IMREAD_UNCHANGED)
|
||||
if img is None:
|
||||
raise RuntimeError(f"模板图无法解码(不是有效图片):{path}")
|
||||
if img.ndim == 2:
|
||||
return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
||||
if img.shape[2] == 4:
|
||||
bgr = img[:, :, :3].astype(np.float32)
|
||||
alpha = (img[:, :, 3:4].astype(np.float32) / 255.0)
|
||||
return (bgr * alpha + 255.0 * (1.0 - alpha)).astype(np.uint8)
|
||||
return img[:, :, :3]
|
||||
|
||||
|
||||
def _to_gray(img: np.ndarray) -> np.ndarray:
|
||||
return img if img.ndim == 2 else cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
|
||||
# ==================== 去重 ====================
|
||||
def _nms(matches: List[Match], overlap: float = 0.5) -> List[Match]:
|
||||
"""按分数从高到低保留,丢弃与已保留框重叠(交并比 > overlap)的候选。"""
|
||||
kept: List[Match] = []
|
||||
for m in sorted(matches, key=lambda x: x.score, reverse=True):
|
||||
drop = False
|
||||
for k in kept:
|
||||
ix = max(0, min(m.left + m.width, k.left + k.width) - max(m.left, k.left))
|
||||
iy = max(0, min(m.top + m.height, k.top + k.height) - max(m.top, k.top))
|
||||
inter = ix * iy
|
||||
if inter <= 0:
|
||||
continue
|
||||
union = m.width * m.height + k.width * k.height - inter
|
||||
if union > 0 and inter / union > overlap:
|
||||
drop = True
|
||||
break
|
||||
if not drop:
|
||||
kept.append(m)
|
||||
return kept
|
||||
|
||||
|
||||
# ==================== 匹配 ====================
|
||||
def match_in(image: np.ndarray,
|
||||
template: Union[str, np.ndarray],
|
||||
threshold: float = DEFAULT_THRESHOLD,
|
||||
scales: Sequence[float] = (1.0,),
|
||||
gray: bool = True,
|
||||
max_results: int = 0,
|
||||
origin: Tuple[int, int] = (0, 0)) -> List[Match]:
|
||||
"""在 image 中匹配模板,返回按相似度降序的 Match 列表(坐标已加 origin)。
|
||||
|
||||
Args:
|
||||
image: 屏幕图(BGR 或灰度)。
|
||||
template: 模板路径或图像。
|
||||
threshold: 相似度阈值 0~1,越大越严格。
|
||||
scales: 模板缩放比例集合,如 (0.9, 1.0, 1.1);默认只按原尺寸。
|
||||
gray: True=灰度匹配(默认),False=彩色匹配。
|
||||
max_results: 最多返回几条(0=不限)。
|
||||
origin: image 左上角对应的屏幕坐标(区域/窗口截图时用于换算)。
|
||||
"""
|
||||
if image is None or getattr(image, "size", 0) == 0:
|
||||
raise RuntimeError("屏幕图为空(截图失败)")
|
||||
tpl_bgr = load_template(template)
|
||||
screen = _to_gray(image) if gray else image
|
||||
|
||||
results: List[Match] = []
|
||||
tpl_h, tpl_w = tpl_bgr.shape[:2]
|
||||
scr_h, scr_w = screen.shape[:2]
|
||||
|
||||
for scale in (scales or (1.0,)):
|
||||
try:
|
||||
scale = float(scale)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if scale <= 0:
|
||||
continue
|
||||
w = max(1, int(round(tpl_w * scale)))
|
||||
h = max(1, int(round(tpl_h * scale)))
|
||||
if w < MIN_TEMPLATE_SIDE or h < MIN_TEMPLATE_SIDE:
|
||||
continue
|
||||
if w > scr_w or h > scr_h:
|
||||
continue # 模板比屏幕还大,跳过该尺度
|
||||
tpl = cv2.resize(tpl_bgr, (w, h), interpolation=cv2.INTER_AREA) if (w, h) != (tpl_w, tpl_h) else tpl_bgr
|
||||
tpl_use = _to_gray(tpl) if gray else tpl
|
||||
# 纯色/近似纯色模板:归一化相关系数会把「任何均匀区域」判成高相关(分数不可信),
|
||||
# 改走平方差匹配(TM_SQDIFF_NORMED,越小越像),再折算成相似度 1-value。
|
||||
low_texture = float(np.asarray(tpl_use, dtype=np.float32).std()) < MIN_TEMPLATE_STD
|
||||
method = cv2.TM_SQDIFF_NORMED if low_texture else cv2.TM_CCOEFF_NORMED
|
||||
try:
|
||||
res = cv2.matchTemplate(screen, tpl_use, method)
|
||||
except cv2.error as e: # 极小图/通道不一致等
|
||||
raise RuntimeError(f"模板匹配失败(模板 {w}x{h},屏幕 {scr_w}x{scr_h}):{e}") from e
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
res = 1.0 - res
|
||||
logger.debug("模板纹理过低(std<%.1f),改用平方差匹配", MIN_TEMPLATE_STD)
|
||||
|
||||
ys, xs = np.where(res >= float(threshold))
|
||||
if len(xs) == 0:
|
||||
continue
|
||||
scores = res[ys, xs]
|
||||
# 同一尺度内先按分数粗筛,避免超大图产生海量候选
|
||||
order = np.argsort(-scores)[: max(64, max_results * 4 if max_results else 64)]
|
||||
for idx in order:
|
||||
x, y = int(xs[idx]), int(ys[idx])
|
||||
results.append(Match(
|
||||
left=x + int(origin[0]), top=y + int(origin[1]),
|
||||
width=w, height=h, score=float(scores[idx])))
|
||||
|
||||
results = _nms(results)
|
||||
if max_results and max_results > 0:
|
||||
results = results[:max_results]
|
||||
return results
|
||||
|
||||
|
||||
def match_any_in(image: np.ndarray,
|
||||
templates: Sequence[Union[str, np.ndarray]],
|
||||
threshold: float = DEFAULT_THRESHOLD,
|
||||
scales: Sequence[float] = (1.0,),
|
||||
gray: bool = True,
|
||||
origin: Tuple[int, int] = (0, 0)) -> Tuple[Optional[Match], int]:
|
||||
"""在一组模板里找「最像的一个」(一个按钮有多种状态时用),返回 (命中, 模板下标)。
|
||||
|
||||
都没命中返回 (None, -1);多个模板同时命中时取相似度最高的。
|
||||
"""
|
||||
best: Optional[Match] = None
|
||||
best_idx = -1
|
||||
for idx, tpl in enumerate(templates or ()):
|
||||
hits = match_in(image, tpl, threshold=threshold, scales=scales, gray=gray,
|
||||
max_results=1, origin=origin)
|
||||
if hits and (best is None or hits[0].score > best.score):
|
||||
best, best_idx = hits[0], idx
|
||||
return best, best_idx
|
||||
|
||||
|
||||
def annotate(image: np.ndarray, matches: Sequence[Match],
|
||||
origin: Tuple[int, int] = (0, 0), color: Tuple[int, int, int] = (0, 200, 0)) -> np.ndarray:
|
||||
"""把命中框画到图上(调试用),origin 用于把屏幕坐标换回图内坐标。"""
|
||||
out = image.copy()
|
||||
ox, oy = int(origin[0]), int(origin[1])
|
||||
for m in matches:
|
||||
p1 = (m.left - ox, m.top - oy)
|
||||
p2 = (p1[0] + m.width, p1[1] + m.height)
|
||||
cv2.rectangle(out, p1, p2, color, 2)
|
||||
label = f"{m.score:.3f}"
|
||||
ty = max(12, p1[1] - 5)
|
||||
cv2.putText(out, label, (p1[0], ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA)
|
||||
return out
|
||||
|
||||
|
||||
def best(matches: Sequence[Match]) -> Optional[Match]:
|
||||
"""取相似度最高的命中;没有返回 None。"""
|
||||
return max(matches, key=lambda m: m.score) if matches else None
|
||||
@@ -0,0 +1,270 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""文字识别(OCR):把图上的文字连坐标一起返回,支持按文字查找/点击。
|
||||
|
||||
后端:RapidOCR(PP-OCRv6,onnxruntime 推理,纯离线,模型随包)。首次调用才加载引擎
|
||||
(约 0.5s),之后复用;单张 1920x1080 整屏识别约 2~4s(CPU),因此:
|
||||
- 能缩小范围就缩小(region / window),速度与准确率都会更好;
|
||||
- 要在一屏里查多个词,先用 read_text() 拿全量,再本地过滤,别反复 OCR。
|
||||
|
||||
文字匹配默认「包含 + 忽略大小写 + 忽略空白」,因为 OCR 常在词间插空格,
|
||||
例如识别成「导 出 数 据」时,query="导出数据" 仍应命中。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Sequence, Union
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import cv2
|
||||
except ImportError as _e: # pragma: no cover
|
||||
raise RuntimeError("缺少依赖 opencv-python,请安装:pip install opencv-python numpy pillow") from _e
|
||||
|
||||
from . import capture
|
||||
from .matcher import load_template
|
||||
|
||||
logger = logging.getLogger("desktopauto")
|
||||
|
||||
_ENGINE = None
|
||||
_ENGINE_LOCK = threading.Lock()
|
||||
|
||||
# 中文字体(标注图用),按优先级探测
|
||||
_FONT_CANDIDATES = (
|
||||
r"C:\Windows\Fonts\msyh.ttc", # 微软雅黑
|
||||
r"C:\Windows\Fonts\msyhbd.ttc",
|
||||
r"C:\Windows\Fonts\simhei.ttf", # 黑体
|
||||
r"C:\Windows\Fonts\simsun.ttc", # 宋体
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TextItem:
|
||||
"""一段被识别出来的文字及其在屏幕上的位置(物理像素)。"""
|
||||
|
||||
text: str
|
||||
left: int
|
||||
top: int
|
||||
width: int
|
||||
height: int
|
||||
score: float
|
||||
|
||||
@property
|
||||
def center(self) -> tuple:
|
||||
return self.left + self.width // 2, self.top + self.height // 2
|
||||
|
||||
@property
|
||||
def region(self) -> tuple:
|
||||
return self.left, self.top, self.left + self.width, self.top + self.height
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"text": self.text, "left": int(self.left), "top": int(self.top),
|
||||
"width": int(self.width), "height": int(self.height),
|
||||
"score": round(float(self.score), 4), "center": list(self.center)}
|
||||
|
||||
def __str__(self) -> str:
|
||||
cx, cy = self.center
|
||||
return f"TextItem('{self.text}' ({self.left},{self.top}) {self.width}x{self.height} score={self.score:.3f} center=({cx},{cy}))"
|
||||
|
||||
|
||||
# ==================== 引擎 ====================
|
||||
def _get_engine():
|
||||
"""懒加载 RapidOCR 单例(模型随包,离线可用)。"""
|
||||
global _ENGINE
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
with _ENGINE_LOCK:
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
try:
|
||||
from rapidocr import RapidOCR # noqa: PLC0415
|
||||
except ImportError as e:
|
||||
raise RuntimeError(
|
||||
"未安装 OCR 依赖,请执行:pip install rapidocr onnxruntime\n"
|
||||
"(模型随包内置,无需联网下载;识别失败时可删除 rapidocr/models 重新解压)"
|
||||
) from e
|
||||
try:
|
||||
_ENGINE = RapidOCR(params={"Global.log_level": "WARNING"})
|
||||
except Exception: # noqa: BLE001 老版本不支持 params
|
||||
_ENGINE = RapidOCR()
|
||||
logging.getLogger("RapidOCR").setLevel(logging.WARNING)
|
||||
logger.debug("RapidOCR 引擎已初始化")
|
||||
return _ENGINE
|
||||
|
||||
|
||||
def available() -> bool:
|
||||
"""OCR 后端是否可用(不触发模型加载)。"""
|
||||
try:
|
||||
import importlib.util # noqa: PLC0415
|
||||
return importlib.util.find_spec("rapidocr") is not None
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 识别 ====================
|
||||
def recognize(image: Union[str, np.ndarray],
|
||||
min_score: float = 0.0,
|
||||
sort: bool = True) -> List[TextItem]:
|
||||
"""识别整张图上的文字,返回 TextItem 列表(坐标已加上截图区域原点时由调用方处理)。
|
||||
|
||||
Args:
|
||||
image: 图片路径或 BGR ndarray。
|
||||
min_score: 识别置信度下限(过滤明显识别错的碎片)。
|
||||
sort: 是否按「从上到下、从左到右」排序(阅读顺序,便于人看日志)。
|
||||
"""
|
||||
arr = load_template(image) if not isinstance(image, np.ndarray) else image
|
||||
if arr is None or arr.size == 0:
|
||||
raise RuntimeError("待识别图片为空")
|
||||
|
||||
engine = _get_engine()
|
||||
try:
|
||||
out = engine(arr)
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise RuntimeError(f"OCR 识别失败:{e}") from e
|
||||
|
||||
boxes = getattr(out, "boxes", None)
|
||||
txts = getattr(out, "txts", None)
|
||||
scores = getattr(out, "scores", None)
|
||||
if boxes is None or txts is None:
|
||||
return []
|
||||
|
||||
items: List[TextItem] = []
|
||||
for box, text, score in zip(boxes, txts, scores if scores is not None else []):
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
score = float(score) if score is not None else 1.0
|
||||
if score < float(min_score):
|
||||
continue
|
||||
pts = np.asarray(box, dtype=np.float32).reshape(-1, 2)
|
||||
left = int(np.floor(pts[:, 0].min()))
|
||||
top = int(np.floor(pts[:, 1].min()))
|
||||
right = int(np.ceil(pts[:, 0].max()))
|
||||
bottom = int(np.ceil(pts[:, 1].max()))
|
||||
if right <= left or bottom <= top:
|
||||
continue
|
||||
items.append(TextItem(text=text, left=left, top=top,
|
||||
width=right - left, height=bottom - top, score=score))
|
||||
|
||||
if sort:
|
||||
items.sort(key=lambda it: (it.top // 8, it.left)) # 同行(±8px)再按列
|
||||
return items
|
||||
|
||||
|
||||
def offset(items: Sequence[TextItem], origin: tuple) -> List[TextItem]:
|
||||
"""把「图内坐标」平移到「屏幕坐标」(region/window 截图时用)。"""
|
||||
ox, oy = int(origin[0]), int(origin[1])
|
||||
if ox == 0 and oy == 0:
|
||||
return list(items)
|
||||
return [TextItem(it.text, it.left + ox, it.top + oy, it.width, it.height, it.score)
|
||||
for it in items]
|
||||
|
||||
|
||||
# ==================== 文字匹配 ====================
|
||||
def _norm(text: str, case_sensitive: bool = False) -> str:
|
||||
"""归一化:去所有空白(OCR 常在字间插空格),并可选转小写。"""
|
||||
s = re.sub(r"\s+", "", str(text or ""))
|
||||
return s if case_sensitive else s.lower()
|
||||
|
||||
|
||||
def match_text(items: Sequence[TextItem], query: str,
|
||||
exact: bool = False, regex: bool = False,
|
||||
case_sensitive: bool = False) -> List[TextItem]:
|
||||
"""在识别结果里筛出匹配 query 的文本(默认「包含」匹配)。"""
|
||||
if query is None or str(query) == "":
|
||||
raise ValueError("query 不能为空")
|
||||
q = str(query)
|
||||
if regex:
|
||||
pattern = re.compile(q if case_sensitive else q, re.I if not case_sensitive else 0)
|
||||
return [it for it in items if pattern.search(it.text)]
|
||||
qn = _norm(q, case_sensitive)
|
||||
if exact:
|
||||
return [it for it in items if _norm(it.text, case_sensitive) == qn]
|
||||
return [it for it in items if qn in _norm(it.text, case_sensitive)]
|
||||
|
||||
|
||||
def best_text(items: Sequence[TextItem]) -> Optional[TextItem]:
|
||||
"""取置信度最高的文本(同分取面积大的,通常是完整按钮文字而不是碎片)。"""
|
||||
if not items:
|
||||
return None
|
||||
return max(items, key=lambda it: (it.score, it.width * it.height))
|
||||
|
||||
|
||||
# ==================== 标注 ====================
|
||||
def _load_font(size: int = 16):
|
||||
"""加载中文字体(标注图用),失败返回 None(退化为 cv2 ASCII 标注)。"""
|
||||
try:
|
||||
from PIL import ImageFont # noqa: PLC0415
|
||||
except ImportError: # pragma: no cover
|
||||
return None
|
||||
for path in _FONT_CANDIDATES:
|
||||
if os.path.isfile(path):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def mark_text(image: Union[str, np.ndarray],
|
||||
items: Sequence[TextItem],
|
||||
out_path: str = "",
|
||||
only: Optional[Sequence[TextItem]] = None,
|
||||
box_color: tuple = (0, 200, 0),
|
||||
text_color: tuple = (0, 0, 255)) -> str:
|
||||
"""把识别到的文字框 + 文本画到图上并保存,返回输出路径。
|
||||
|
||||
Args:
|
||||
items: 全部识别结果(用于画框)。
|
||||
only: 若给,则只强调这些(颜色加粗);其余淡一点。
|
||||
box_color/text_color: BGR 颜色。
|
||||
"""
|
||||
base = load_template(image) if not isinstance(image, np.ndarray) else image.copy()
|
||||
hi = {id(it) for it in (only or [])}
|
||||
labels: List[TextItem] = []
|
||||
for it in items:
|
||||
is_hi = (not only) or id(it) in hi
|
||||
color = box_color if is_hi else (170, 170, 170)
|
||||
cv2.rectangle(base, (it.left, it.top), (it.left + it.width, it.top + it.height), color, 2 if is_hi else 1)
|
||||
# 指定了 only 时只给目标写文字,其余只留淡框,避免整屏文字糊在图上
|
||||
if is_hi:
|
||||
labels.append(it)
|
||||
|
||||
out_path = out_path or os.path.join(os.getcwd(), "ocr_marked.png")
|
||||
out_path = os.path.abspath(out_path)
|
||||
parent = os.path.dirname(out_path)
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
|
||||
font = _load_font(14)
|
||||
if font is None: # 无中文字体:退回 cv2(只能画 ASCII,中文会变问号,但框仍然准)
|
||||
for it in labels:
|
||||
cv2.putText(base, f"{it.score:.2f}", (it.left, max(12, it.top - 2)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.4, text_color, 1, cv2.LINE_AA)
|
||||
return capture.save_image(base, out_path)
|
||||
|
||||
from PIL import Image, ImageDraw # noqa: PLC0415
|
||||
pil = Image.fromarray(cv2.cvtColor(base, cv2.COLOR_BGR2RGB))
|
||||
draw = ImageDraw.Draw(pil)
|
||||
for it in labels:
|
||||
label = it.text if len(it.text) <= 24 else it.text[:24] + "…"
|
||||
ty = it.top - 16 if it.top >= 16 else it.top + it.height + 1
|
||||
draw.text((it.left, ty), label, fill=(text_color[2], text_color[1], text_color[0]), font=font)
|
||||
pil.save(out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
def summarize(items: Sequence[TextItem], limit: int = 0) -> str:
|
||||
"""把识别结果拼成可读文本(日志用)。"""
|
||||
lines = [f"识别到 {len(items)} 段文字"]
|
||||
for it in (items if not limit else items[:limit]):
|
||||
cx, cy = it.center
|
||||
lines.append(f" '{it.text}' score={it.score:.3f} 框=({it.left},{it.top}) "
|
||||
f"{it.width}x{it.height} 中心=({cx},{cy})")
|
||||
if limit and len(items) > limit:
|
||||
lines.append(f" ...(省略 {len(items) - limit} 段)")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,192 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""进程:运行或打开程序/文件/网址、查询是否在运行、终止程序。
|
||||
|
||||
对应 RPA 的「运行或打开」「终止程序」:
|
||||
- run_or_open:.exe/.bat → 启动;文档/文件夹/网址 → 默认程序打开
|
||||
- list_processes / is_running / wait_process:查进程
|
||||
- kill_process:按 pid / 进程名 / Window 对象终止(等价于任务管理器结束进程)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
from typing import List, Optional, Sequence, Union
|
||||
|
||||
from ._win32 import _process_name, require_windows, terminate_process
|
||||
|
||||
TH32CS_SNAPPROCESS = 0x00000002
|
||||
_INVALID_HANDLE = -1
|
||||
|
||||
# 走 subprocess 启动的扩展名(其余交给系统默认程序)
|
||||
_EXEC_EXTS = (".exe", ".bat", ".cmd", ".com")
|
||||
|
||||
|
||||
class PROCESSENTRY32W(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("dwSize", wintypes.DWORD),
|
||||
("cntUsage", wintypes.DWORD),
|
||||
("th32ProcessID", wintypes.DWORD),
|
||||
("th32DefaultHeapID", ctypes.c_void_p),
|
||||
("th32ModuleID", wintypes.DWORD),
|
||||
("cntThreads", wintypes.DWORD),
|
||||
("th32ParentProcessID", wintypes.DWORD),
|
||||
("pcPriClassBase", ctypes.c_long),
|
||||
("dwFlags", wintypes.DWORD),
|
||||
("szExeFile", wintypes.WCHAR * 260),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 查询 ====================
|
||||
def list_processes(name: str = "", with_path: bool = False) -> List[dict]:
|
||||
"""枚举进程,返回 [{"pid", "name", "path"}]。
|
||||
|
||||
Args:
|
||||
name: 可执行名过滤(包含匹配、不区分大小写,如 "DingTalk"、"notepad");空=全部。
|
||||
with_path: 是否补全完整路径(每个进程多一次 OpenProcess,数量大时慢)。
|
||||
"""
|
||||
require_windows("进程枚举")
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
kernel32.CreateToolhelp32Snapshot.restype = ctypes.c_void_p
|
||||
kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
|
||||
kernel32.Process32FirstW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]
|
||||
kernel32.Process32NextW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]
|
||||
|
||||
snap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
|
||||
if not snap or snap == _INVALID_HANDLE:
|
||||
raise RuntimeError("创建进程快照失败")
|
||||
key = (name or "").strip().lower()
|
||||
out: List[dict] = []
|
||||
try:
|
||||
entry = PROCESSENTRY32W()
|
||||
entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
|
||||
ok = kernel32.Process32FirstW(snap, ctypes.byref(entry))
|
||||
while ok:
|
||||
exe = entry.szExeFile or ""
|
||||
pid = int(entry.th32ProcessID)
|
||||
if not key or key in exe.lower():
|
||||
item = {"pid": pid, "name": exe, "path": ""}
|
||||
if with_path:
|
||||
item["path"] = _process_name(pid)
|
||||
out.append(item)
|
||||
ok = kernel32.Process32NextW(snap, ctypes.byref(entry))
|
||||
finally:
|
||||
kernel32.CloseHandle(ctypes.c_void_p(snap))
|
||||
return out
|
||||
|
||||
|
||||
def is_running(name: str) -> bool:
|
||||
"""进程是否在运行(按可执行名包含匹配)。"""
|
||||
return bool(list_processes(name))
|
||||
|
||||
|
||||
def wait_process(name: str, timeout: float = 30.0, interval: float = 0.5,
|
||||
until: str = "start") -> bool:
|
||||
"""等待进程出现(until="start")或消失(until="exit"),超时返回 False。"""
|
||||
if until not in ("start", "exit"):
|
||||
raise ValueError(f"until 只能是 start / exit,收到:{until}")
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
running = is_running(name)
|
||||
if (until == "start" and running) or (until == "exit" and not running):
|
||||
return True
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.1, float(interval)))
|
||||
|
||||
|
||||
# ==================== 启动 / 打开 ====================
|
||||
def launch(target: str, args: Sequence[str] = (), cwd: Optional[str] = None,
|
||||
wait: float = 0.0) -> subprocess.Popen:
|
||||
"""启动程序(.exe/.bat/.cmd),返回 Popen。
|
||||
|
||||
Args:
|
||||
target: 可执行文件路径,或 PATH 里的命令名(如 "notepad.exe")。
|
||||
args: 命令行参数。
|
||||
cwd: 工作目录。
|
||||
wait: 启动后等待秒数(给程序一点时间出窗口,配合 wait_process/get_window 用)。
|
||||
"""
|
||||
require_windows("启动程序")
|
||||
target = str(target)
|
||||
if not target:
|
||||
raise ValueError("target 不能为空")
|
||||
cmd: Union[str, List[str]]
|
||||
if os.path.exists(target):
|
||||
cmd = [target, *[str(a) for a in args]]
|
||||
proc = subprocess.Popen(cmd, cwd=cwd,
|
||||
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0))
|
||||
else:
|
||||
# 交给 PATH 解析(命令名);仍找不到时由系统报错
|
||||
cmd = " ".join([f'"{target}"', *[f'"{a}"' for a in args]])
|
||||
proc = subprocess.Popen(cmd, cwd=cwd, shell=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0))
|
||||
if wait and wait > 0:
|
||||
time.sleep(float(wait))
|
||||
return proc
|
||||
|
||||
|
||||
def open_path(path: str) -> str:
|
||||
"""用系统默认程序打开文件 / 文件夹 / 网址,返回原路径。"""
|
||||
require_windows("打开文件")
|
||||
p = str(path)
|
||||
is_url = p.lower().startswith(("http://", "https://", "mailto:", "file://"))
|
||||
if not (is_url or os.path.exists(p)):
|
||||
raise RuntimeError(f"路径不存在:{p}")
|
||||
os.startfile(p) # noqa: S606 等价于双击
|
||||
return p
|
||||
|
||||
|
||||
def open_url(url: str) -> str:
|
||||
"""用默认浏览器打开网址。"""
|
||||
return open_path(url)
|
||||
|
||||
|
||||
def run_or_open(target: str, args: Sequence[str] = (), wait: float = 0.0
|
||||
) -> Optional[subprocess.Popen]:
|
||||
"""运行或打开(RPA「运行或打开」):
|
||||
|
||||
- `.exe/.bat/.cmd/.com` 或带参数 → 启动进程,返回 Popen;
|
||||
- 文档 / 文件夹 / 网址 → 用默认程序打开,返回 None。
|
||||
"""
|
||||
t = str(target)
|
||||
ext = os.path.splitext(t)[1].lower()
|
||||
if ext in _EXEC_EXTS or args:
|
||||
return launch(t, args=args, wait=wait)
|
||||
open_path(t)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 终止 ====================
|
||||
def kill_process(target: Union[int, str], wait: float = 0.5) -> List[int]:
|
||||
"""终止程序:pid / 进程名 / Window 对象(有 .pid 属性)都支持,返回被终止的 pid 列表。
|
||||
|
||||
- 传进程名时,同名的**所有**实例都会被终止(如 3 个 notepad 全关);
|
||||
- 找不到进程直接抛错(不会静默什么都不做)。
|
||||
"""
|
||||
require_windows("终止进程")
|
||||
pids: List[int] = []
|
||||
if isinstance(target, int):
|
||||
pids = [int(target)]
|
||||
elif isinstance(target, str):
|
||||
hits = list_processes(target)
|
||||
pids = [h["pid"] for h in hits]
|
||||
if not pids:
|
||||
raise RuntimeError(f"未找到进程:{target}(进程名是否写错?)")
|
||||
elif hasattr(target, "pid"): # Window 对象(鸭子类型,避免循环导入)
|
||||
pids = [int(getattr(target, "pid"))]
|
||||
else:
|
||||
raise ValueError(f"kill_process 不支持的目标类型:{type(target).__name__}")
|
||||
|
||||
failed: List[str] = []
|
||||
for pid in pids:
|
||||
try:
|
||||
terminate_process(pid, wait=0)
|
||||
except Exception as e: # noqa: BLE001 权限不足等
|
||||
failed.append(f"{pid}({e})")
|
||||
if wait and wait > 0:
|
||||
time.sleep(float(wait))
|
||||
if failed and len(failed) == len(pids):
|
||||
raise RuntimeError(f"终止进程失败:{', '.join(failed)}")
|
||||
return pids
|
||||
@@ -0,0 +1,653 @@
|
||||
# -*- 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:通用文字识别(含位置)
|
||||
@@ -0,0 +1,326 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""窗口相关 API(对外友好封装,底层在 _win32)。
|
||||
|
||||
用途:把识图范围限定到某个窗口,避免全屏里同款按钮/图标误命中;
|
||||
点击前先激活窗口,避免点到被其它窗口遮挡的位置。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
from ._win32 import activate_window as _activate
|
||||
from ._win32 import child_windows as _children
|
||||
from ._win32 import close_window as _close
|
||||
from ._win32 import find_windows as _find
|
||||
from ._win32 import foreground_hwnd as _foreground_hwnd
|
||||
from ._win32 import is_foreground as _is_foreground
|
||||
from ._win32 import is_window as _is_window
|
||||
from ._win32 import list_windows as _list
|
||||
from ._win32 import maximize_window as _maximize
|
||||
from ._win32 import minimize_window as _minimize
|
||||
from ._win32 import move_window as _move
|
||||
from ._win32 import restore_window as _restore
|
||||
from ._win32 import terminate_process as _terminate
|
||||
from ._win32 import wait_window as _wait
|
||||
from ._win32 import window_info as _info
|
||||
from ._win32 import window_rect as _rect
|
||||
|
||||
__all__ = ["Window", "get_window", "foreground_window", "close_window",
|
||||
"list_windows", "find_window", "find_windows", "wait_window",
|
||||
"child_windows", "window_info", "window_rect", "activate_window"]
|
||||
|
||||
|
||||
def list_windows(keyword: str = "", visible_only: bool = True) -> List[Tuple[int, str]]:
|
||||
"""列出顶层窗口 [(hwnd, 标题)];keyword 非空时按标题模糊过滤。"""
|
||||
return _list(keyword, visible_only)
|
||||
|
||||
|
||||
def find_window(keyword: str) -> int:
|
||||
"""按标题关键字找窗口,返回 hwnd;找不到抛错,多个命中取标题最短的主窗口。"""
|
||||
hits = _list(keyword)
|
||||
if not hits:
|
||||
raise RuntimeError(f"未找到标题含「{keyword}」的可见窗口(窗口是否已打开/最小化?)")
|
||||
hits.sort(key=lambda x: len(x[1]))
|
||||
return hits[0][0]
|
||||
|
||||
|
||||
def window_rect(window: Union[int, str]) -> Tuple[int, int, int, int]:
|
||||
"""窗口屏幕矩形 (left, top, right, bottom)。window 可为 hwnd 或标题关键字。"""
|
||||
return _rect(window)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def find_windows(title: str = "", exact: bool = False, pid: int = 0,
|
||||
process: str = "", class_name: str = "",
|
||||
visible_only: bool = True, include_minimized: bool = False) -> List[dict]:
|
||||
"""多条件查找窗口(标题/进程/PID/类名),返回窗口信息列表(主窗口在前)。
|
||||
|
||||
比 list_windows 强的地方:能区分「两个钉钉」「标题带文件名」这类情况,
|
||||
例如 find_windows(process="DingTalk.exe")、find_windows(title="工资卡", exact=True)。
|
||||
"""
|
||||
return _find(title=title, exact=exact, pid=pid, process=process,
|
||||
class_name=class_name, visible_only=visible_only,
|
||||
include_minimized=include_minimized)
|
||||
|
||||
|
||||
def wait_window(title: str = "", timeout: float = 10.0, interval: float = 0.3,
|
||||
**kwargs) -> Optional[dict]:
|
||||
"""等窗口出现(参数同 find_windows),超时返回 None。"""
|
||||
return _wait(title=title, timeout=timeout, interval=interval, **kwargs)
|
||||
|
||||
|
||||
def window_info(hwnd: int) -> dict:
|
||||
"""单个窗口的完整信息(标题/类名/PID/进程名/矩形/是否最小化)。"""
|
||||
return _info(hwnd)
|
||||
|
||||
|
||||
def child_windows(window: Union[int, str]) -> List[dict]:
|
||||
"""列出窗口的子窗口(找内嵌控件、弹层时用)。"""
|
||||
return _children(window)
|
||||
|
||||
|
||||
# ==================== 窗口对象 ====================
|
||||
class Window:
|
||||
"""窗口对象:一次拿到,后面反复用(激活/关闭/移动/截图/子窗口/绑定 Screen)。
|
||||
|
||||
```python
|
||||
w = get_window(process="DingTalk.exe")
|
||||
w.activate()
|
||||
print(w.title, w.rect, w.pid)
|
||||
w.screen(threshold=0.9).click("img/btn.png") # 直接拿到绑定该窗口的 Screen
|
||||
w.close()
|
||||
```
|
||||
|
||||
说明:`rect` 用 DWM 扩展边框(与截图/点击坐标一致),比 `GetWindowRect` 少几像素阴影。
|
||||
"""
|
||||
|
||||
def __init__(self, hwnd: int):
|
||||
hwnd = int(hwnd)
|
||||
if not _is_window(hwnd):
|
||||
raise RuntimeError(f"窗口句柄无效:{hwnd}(窗口可能已关闭)")
|
||||
self._hwnd = hwnd
|
||||
|
||||
# ---------- 基础信息(实时读取,窗口关了会抛错) ----------
|
||||
@property
|
||||
def hwnd(self) -> int:
|
||||
return self._hwnd
|
||||
|
||||
@property
|
||||
def title(self) -> str:
|
||||
return _info(self._hwnd)["title"]
|
||||
|
||||
@property
|
||||
def class_name(self) -> str:
|
||||
return _info(self._hwnd)["class_name"]
|
||||
|
||||
@property
|
||||
def pid(self) -> int:
|
||||
return _info(self._hwnd)["pid"]
|
||||
|
||||
@property
|
||||
def process(self) -> str:
|
||||
return _info(self._hwnd)["process"]
|
||||
|
||||
@property
|
||||
def rect(self) -> Tuple[int, int, int, int]:
|
||||
"""(left, top, right, bottom),DWM 扩展边框,与截图/点击坐标一致。"""
|
||||
return _rect(self._hwnd)
|
||||
|
||||
@property
|
||||
def left(self) -> int:
|
||||
return self.rect[0]
|
||||
|
||||
@property
|
||||
def top(self) -> int:
|
||||
return self.rect[1]
|
||||
|
||||
@property
|
||||
def width(self) -> int:
|
||||
left, _top, right, _bottom = self.rect
|
||||
return max(0, right - left)
|
||||
|
||||
@property
|
||||
def height(self) -> int:
|
||||
_left, top, _right, bottom = self.rect
|
||||
return max(0, bottom - top)
|
||||
|
||||
@property
|
||||
def center(self) -> Tuple[int, int]:
|
||||
return self.left + self.width // 2, self.top + self.height // 2
|
||||
|
||||
@property
|
||||
def minimized(self) -> bool:
|
||||
return bool(_info(self._hwnd)["minimized"])
|
||||
|
||||
@property
|
||||
def visible(self) -> bool:
|
||||
return bool(_info(self._hwnd)["visible"])
|
||||
|
||||
def info(self) -> dict:
|
||||
"""完整信息 dict(title/class_name/pid/process/rect/minimized/visible)。"""
|
||||
return _info(self._hwnd)
|
||||
|
||||
def exists(self) -> bool:
|
||||
"""窗口是否还在(关闭后返回 False,不会抛错)。"""
|
||||
return _is_window(self._hwnd)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
try:
|
||||
return f"<Window hwnd={self._hwnd} '{self.title}' {self.width}x{self.height}>"
|
||||
except Exception: # noqa: BLE001
|
||||
return f"<Window hwnd={self._hwnd} (已失效)>"
|
||||
|
||||
# ---------- 操作 ----------
|
||||
def activate(self) -> "Window":
|
||||
"""激活到前台(还原最小化 + 置前),返回自身便于链式调用。"""
|
||||
_activate(self._hwnd)
|
||||
return self
|
||||
|
||||
def is_foreground(self) -> bool:
|
||||
"""当前是否在前台。"""
|
||||
return _is_foreground(self._hwnd)
|
||||
|
||||
def minimize(self) -> "Window":
|
||||
_minimize(self._hwnd)
|
||||
return self
|
||||
|
||||
def maximize(self) -> "Window":
|
||||
_maximize(self._hwnd)
|
||||
return self
|
||||
|
||||
def restore(self) -> "Window":
|
||||
_restore(self._hwnd)
|
||||
return self
|
||||
|
||||
def move(self, x: int, y: int,
|
||||
width: Optional[int] = None, height: Optional[int] = None) -> "Window":
|
||||
"""移动窗口;不传宽高保持原尺寸。"""
|
||||
_move(self._hwnd, x, y, width, height)
|
||||
return self
|
||||
|
||||
def close(self, wait: float = 0.5) -> None:
|
||||
"""关闭窗口(等同点 ×,可能弹「是否保存」确认框);只是发消息,不保证已退出。"""
|
||||
_close(self._hwnd, wait=wait)
|
||||
|
||||
def kill(self, wait: float = 0.5) -> None:
|
||||
"""强制结束该窗口所属进程(TerminateProcess):应用无响应/有确认弹框时用。
|
||||
|
||||
注意:杀掉的是整个进程,该应用的所有窗口都会消失,未保存数据会丢。
|
||||
"""
|
||||
_terminate(self.pid, wait=wait)
|
||||
|
||||
def wait_closed(self, timeout: float = 10.0, interval: float = 0.3) -> bool:
|
||||
"""等待窗口关闭,超时返回 False。"""
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
if not self.exists():
|
||||
return True
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
|
||||
def wait_ready(self, timeout: float = 10.0, interval: float = 0.3) -> bool:
|
||||
"""等待窗口可见且非最小化(启动软件后等它出来),超时返回 False。"""
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
if self.exists():
|
||||
info = self.info()
|
||||
if info["visible"] and not info["minimized"]:
|
||||
return True
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
|
||||
def children(self) -> List[dict]:
|
||||
"""子窗口列表(内嵌控件/弹层)。"""
|
||||
return _children(self._hwnd)
|
||||
|
||||
def screenshot(self, path: str = "") -> str:
|
||||
"""只截这个窗口(含窗口外框区域的实际屏幕内容)。"""
|
||||
from . import capture # 延迟导入,避免循环依赖
|
||||
return capture.screenshot(path=path, window=self._hwnd)
|
||||
|
||||
def screen(self, **kwargs):
|
||||
"""拿到绑定本窗口的 Screen(识图/OCR/点击都会限定在这个窗口内)。
|
||||
|
||||
```python
|
||||
w = get_window(process="DingTalk.exe")
|
||||
s = w.screen(threshold=0.9, debug_dir="debug")
|
||||
s.click("img/btn_send.png")
|
||||
```
|
||||
"""
|
||||
from .screen import Screen # 延迟导入,避免循环依赖
|
||||
kwargs.setdefault("activate_before_click", True)
|
||||
return Screen(window=self._hwnd, **kwargs)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
info = _info(self._hwnd)
|
||||
info["rect"] = list(self.rect)
|
||||
return info
|
||||
|
||||
|
||||
def get_window(title: str = "", exact: bool = False, pid: int = 0,
|
||||
process: str = "", class_name: str = "", index: int = 0,
|
||||
timeout: float = 0.0) -> Window:
|
||||
"""获取窗口对象(RPA 的「获取窗口对象」)。
|
||||
|
||||
Args:
|
||||
title: 标题(exact=False 包含匹配)。
|
||||
process: 进程名,如 "DingTalk.exe"。
|
||||
pid: 进程 ID。
|
||||
class_name: 窗口类名。
|
||||
index: 同名/同进程多个窗口时取第几个(0=主窗口,因为结果按标题长度排序)。
|
||||
timeout: >0 时轮询等待窗口出现(秒)。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 找不到窗口(或超时)。
|
||||
"""
|
||||
if timeout and timeout > 0:
|
||||
win = _wait(title=title, timeout=timeout, exact=exact, pid=pid,
|
||||
process=process, class_name=class_name)
|
||||
if not win:
|
||||
raise RuntimeError(
|
||||
f"等待窗口超时({timeout}s):title={title!r} process={process!r} pid={pid}")
|
||||
return Window(win["hwnd"])
|
||||
|
||||
wins = _find(title=title, exact=exact, pid=pid, process=process, class_name=class_name)
|
||||
if not wins:
|
||||
raise RuntimeError(
|
||||
f"未找到窗口:title={title!r} process={process!r} pid={pid} class_name={class_name!r}"
|
||||
f"(窗口是否已打开?最小化窗口默认不列出)")
|
||||
if index < 0 or index >= len(wins):
|
||||
raise RuntimeError(f"窗口下标越界:index={index},共找到 {len(wins)} 个窗口")
|
||||
return Window(wins[index]["hwnd"])
|
||||
|
||||
|
||||
def foreground_window() -> Optional[Window]:
|
||||
"""当前前台窗口对象(没有则返回 None)。"""
|
||||
hwnd = _foreground_hwnd()
|
||||
if not hwnd or not _is_window(hwnd):
|
||||
return None
|
||||
return Window(hwnd)
|
||||
|
||||
|
||||
def activate_window(window_or_title: Union[int, str, Window]) -> int:
|
||||
"""激活软件窗口(RPA 的「激活软件窗口」):hwnd / 标题 / Window 对象都可以。"""
|
||||
if isinstance(window_or_title, Window):
|
||||
return _activate(window_or_title.hwnd)
|
||||
return _activate(window_or_title)
|
||||
|
||||
|
||||
def close_window(window_or_title: Union[int, str, Window], wait: float = 0.5) -> None:
|
||||
"""关闭软件窗口(RPA 的「关闭软件窗口」):hwnd / 标题 / Window 对象都可以。
|
||||
|
||||
发 WM_CLOSE(等同点 ×),应用若弹「是否保存」需要你再处理;
|
||||
要确保一定关掉,用 `w.kill()` 或 `w.close()` 后再 `w.wait_closed()`。
|
||||
"""
|
||||
if isinstance(window_or_title, Window):
|
||||
hwnd = window_or_title.hwnd
|
||||
elif isinstance(window_or_title, int):
|
||||
hwnd = window_or_title
|
||||
else:
|
||||
hwnd = find_window(window_or_title)
|
||||
_close(hwnd, wait=wait)
|
||||
@@ -0,0 +1,28 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "desktopauto"
|
||||
version = "0.4.0"
|
||||
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
"opencv-python>=4.5",
|
||||
"numpy>=1.21",
|
||||
"pillow>=9.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# 文字识别(OCR):不装则只有模板匹配能力
|
||||
ocr = [
|
||||
"rapidocr>=3.0",
|
||||
"onnxruntime>=1.16",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/37du/37duAutomation"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["desktopauto"]
|
||||
@@ -0,0 +1,6 @@
|
||||
opencv-python>=4.5
|
||||
numpy>=1.21
|
||||
pillow>=9.0
|
||||
# 文字识别(OCR)能力,仅用模板匹配时可不装
|
||||
rapidocr>=3.0
|
||||
onnxruntime>=1.16
|
||||
@@ -0,0 +1,140 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把影刀工程的图像库(imagesV2.xml + resources/images/*.png)导入成 desktopauto 可直接用的模板目录。
|
||||
|
||||
影刀图像库结构(实际工程验证):
|
||||
<imageelement name="登录按钮" sourcetype="screenshot"
|
||||
filepath="resources\\images\\<uuid>.png"
|
||||
similarity="80" scalingfactor="1" adaptive="True" graying="False" />
|
||||
|
||||
映射到 desktopauto:
|
||||
similarity=80 → threshold=0.80
|
||||
graying=False → gray=False(影刀勾选"灰度匹配"时为 True)
|
||||
adaptive=True → scales=(0.9, 1.0, 1.1)(自适应缩放,跨 DPI 更稳)
|
||||
文件按中文名重命名 → images/<名称>.png,名称里的非法字符替换为 _
|
||||
|
||||
用法(改下面两个常量后直接运行,不依赖命令行参数):
|
||||
.venv\\Scripts\\python.exe libs\\desktopauto\\scripts\\import_yingdao_images.py
|
||||
|
||||
输出(模板是插件业务资源,落在插件包内随包发布;本脚本不往 AppData / 库目录写任何东西):
|
||||
plugins/XQ0001-0100/<插件目录>/images/*.png 模板图(中文名)
|
||||
plugins/XQ0001-0100/<插件目录>/images/manifest.json 名称 → {file, threshold, gray, scales}
|
||||
|
||||
插件里使用(模板随插件包一起被 __init__.py 打包发布):
|
||||
import json, os
|
||||
from desktopauto import Screen
|
||||
|
||||
_IMAGES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
|
||||
meta = json.load(open(os.path.join(_IMAGES, "manifest.json"), encoding="utf-8"))
|
||||
item = meta["登录按钮"]
|
||||
Screen(window="社保费申报").click(os.path.join(_IMAGES, item["file"]),
|
||||
threshold=item["threshold"], gray=item["gray"],
|
||||
scales=tuple(item["scales"]))
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Dict, List
|
||||
|
||||
# ==================== 配置区(改这里再运行) ====================
|
||||
# 影刀工程目录(含 imagesV2.xml 与 resources/images/ 的那一层)
|
||||
SRC_PROJECT = r"C:\Users\admin\Desktop\97e2e9b5-ad33-4288-b6d8-12a556615c99\xbot_robot"
|
||||
# 【必填】模板输出目录 = 插件包内的 images/ 目录(模板是插件业务资源,随插件 zip 发布,自包含)
|
||||
# 例:r"d:\work\code\37duAutomation\plugins\XQ0001-0100\XQ0014 社保系统增减员办理\images"
|
||||
OUTPUT_DIR = r"d:\work\code\37duAutomation\plugins\XQ0001-0100\XQ0013 社保费用申报导出并汇总\images"
|
||||
# ============================================================
|
||||
|
||||
_ILLEGAL = re.compile(r'[\\/:*?"<>|\s]+')
|
||||
|
||||
|
||||
def safe_name(name: str, fallback: str) -> str:
|
||||
"""把影刀模板名转成安全文件名(去掉路径非法字符与空白)。"""
|
||||
cleaned = _ILLEGAL.sub("_", (name or "").strip()).strip("_")
|
||||
return cleaned or fallback
|
||||
|
||||
|
||||
def parse_manifest(xml_path: str) -> List[dict]:
|
||||
"""解析 imagesV2.xml,返回 [{name, rel_path, threshold, gray, scales}]。"""
|
||||
tree = ET.parse(xml_path)
|
||||
root = tree.getroot()
|
||||
items: List[dict] = []
|
||||
for idx, el in enumerate(root.iter("imageelement"), start=1):
|
||||
name = (el.get("name") or "").strip()
|
||||
rel = (el.get("filepath") or "").replace("\\", os.sep)
|
||||
if not rel:
|
||||
continue
|
||||
try:
|
||||
similarity = float(el.get("similarity") or 80)
|
||||
except ValueError:
|
||||
similarity = 80.0
|
||||
threshold = max(0.1, min(1.0, similarity / 100.0))
|
||||
graying = (el.get("graying") or "False").strip().lower() in ("true", "1")
|
||||
adaptive = (el.get("adaptive") or "False").strip().lower() in ("true", "1")
|
||||
items.append({
|
||||
"name": name or f"image_{idx}",
|
||||
"rel_path": rel,
|
||||
"threshold": round(threshold, 2),
|
||||
"gray": graying,
|
||||
"scales": [0.9, 1.0, 1.1] if adaptive else [1.0],
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def main() -> int:
|
||||
out_dir = (OUTPUT_DIR or "").strip()
|
||||
if not out_dir:
|
||||
raise SystemExit(
|
||||
"请先把脚本顶部的 OUTPUT_DIR 设为插件包内的模板目录,例如:\n"
|
||||
r' OUTPUT_DIR = r"d:\work\code\37duAutomation\plugins\XQ0001-0100\XQ0014 社保系统增减员办理\images"'
|
||||
"\n模板是插件业务资源,必须随插件包发布(不放 AppData / 不放库目录)。")
|
||||
|
||||
xml_path = os.path.join(SRC_PROJECT, "imagesV2.xml")
|
||||
if not os.path.isfile(xml_path):
|
||||
raise SystemExit(f"未找到影刀图像库文件:{xml_path}")
|
||||
|
||||
items = parse_manifest(xml_path)
|
||||
out_images = os.path.abspath(out_dir)
|
||||
os.makedirs(out_images, exist_ok=True)
|
||||
|
||||
manifest: Dict[str, dict] = {}
|
||||
copied, missing, renamed = 0, 0, 0
|
||||
for item in items:
|
||||
src = os.path.join(SRC_PROJECT, item["rel_path"])
|
||||
if not os.path.isfile(src):
|
||||
print(f"[跳过] 模板文件不存在:{item['rel_path']}({item['name']})")
|
||||
missing += 1
|
||||
continue
|
||||
fname = safe_name(item["name"], os.path.splitext(os.path.basename(src))[0]) + ".png"
|
||||
dst = os.path.join(out_images, fname)
|
||||
if os.path.exists(dst) and os.path.abspath(dst) != os.path.abspath(src):
|
||||
base, ext = os.path.splitext(fname)
|
||||
n = 2
|
||||
while os.path.exists(dst):
|
||||
dst = os.path.join(out_images, f"{base}_{n}{ext}")
|
||||
n += 1
|
||||
renamed += 1
|
||||
shutil.copy2(src, dst)
|
||||
copied += 1
|
||||
manifest[item["name"]] = {
|
||||
"file": os.path.basename(dst), # 与 manifest.json 同目录,插件内直接拼路径
|
||||
"threshold": item["threshold"],
|
||||
"gray": item["gray"],
|
||||
"scales": item["scales"],
|
||||
}
|
||||
|
||||
manifest_path = os.path.join(out_images, "manifest.json")
|
||||
with open(manifest_path, "w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"解析模板:{len(items)} 个")
|
||||
print(f"已复制:{copied} 个(重名改名 {renamed} 个),缺失 {missing} 个")
|
||||
print(f"模板目录:{out_images}")
|
||||
print(f"清单文件:{manifest_path}")
|
||||
return 0 if copied else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user