Files
37duAutomation/libs/desktopauto/desktopauto/ocr.py
T
puddy eeeaed1e14 feat(sdk): desktopauto 0.5.3 银行卡/证件 OCR 增强、dingtalk 1.1.0、aitable 0.1.3
- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致
- dingtalk:AI 表格读写与错误封装扩充
- aitable:client/cli/自测与打包配置更新
2026-11-18 18:56:09 +08:00

283 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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 _silence_rapidocr() -> None:
"""把 RapidOCR 自带的控制台日志压到 ERROR。
RapidOCR 在 import 时给 "RapidOCR" logger 挂了 stderr handler,识别不到文字等
WARNING 会直接写 stderr,被执行机当成 ERROR 刷进运行日志(`[ERROR] [WARNING] ...`)。
这里只压掉 WARNING 及以下的噪音,ERROR 仍然保留。
"""
lg = logging.getLogger("RapidOCR")
lg.setLevel(logging.ERROR)
lg.propagate = False
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": "ERROR"})
except Exception: # noqa: BLE001 老版本不支持 params
_ENGINE = RapidOCR()
_silence_rapidocr()
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)