141 lines
6.2 KiB
Python
141 lines
6.2 KiB
Python
# -*- 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())
|