# -*- 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") # ---- 18. 浮雕卡号裁决(离线,不依赖图片/OCR) ---- from desktopauto.cardocr import enhance as _en # noqa: PLC0415 from desktopauto.cardocr.validators import luhn_ok as _luhn # noqa: PLC0415 def _fake_group(digits, votes=None): g = _en.GroupRead(rect=(0, 0, 10, 10), offset=0.0) g.digits = digits g.reads = {"eq": digits} g.votes = votes or [{c: 1} for c in digits] return g clean = [_fake_group("6214"), _fake_group("8323"), _fake_group("7766"), _fake_group("0399")] r_clean = _en._resolve(clean, "招商银行") ok(r_clean.status == "ok" and r_clean.confidence == "high", f"投票串本身合法 → ok/high(实际 {r_clean.status}/{r_clean.confidence})") ok(r_clean.number == "6214832377660399" and r_clean.luhn_ok, f"卡号裁决正确({r_clean.number})") ok(r_clean.bank == "招商银行", f"BIN 命中招商银行({r_clean.bank})") ok(_luhn("6214832377660399") and not _luhn("6214832377660390"), "Luhn:尾号 99 合法、90 非法") # 尾位 6 被反光误认成 8 → 应在易混对里改回 6,并降级为候选(不硬猜) noisy = [_fake_group("6214"), _fake_group("8323"), _fake_group("7788"), _fake_group("0399")] r_noisy = _en._resolve(noisy, "招商银行") ok(r_noisy.status == "candidate" and r_noisy.number != "6214832377880399", f"误认为 8 时不直接采信({r_noisy.number}/{r_noisy.status})") ok(all(c["luhn_ok"] for c in r_noisy.candidates), "候选全部通过 Luhn") # 卡面银行与 BIN 冲突 → 该候选必须被剔除 conflicted = _en._resolve(clean, "中国工商银行") ok(conflicted.number == "" and conflicted.status == "failed", "卡面银行与 BIN 冲突时不给号码(宁可失败)") # 空白投票(完全没读出)→ failed,不抛异常 blank = _en._resolve([_fake_group("0000")] * 4, "") ok(blank.status in ("failed", "candidate"), "全 0 投票不抛异常") print(f"\n全部通过:{_passed} 项;临时目录 {TMP}") return 0 if __name__ == "__main__": try: sys.exit(main()) except AssertionError as e: print(e) sys.exit(1)