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/自测与打包配置更新
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "desktopauto",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.3",
|
||||
"modules": {
|
||||
"desktopauto": {
|
||||
"exports": [
|
||||
@@ -501,8 +501,10 @@
|
||||
"cv2",
|
||||
"dataclass",
|
||||
"expand_pts",
|
||||
"find_card_color",
|
||||
"find_cards",
|
||||
"four_point_warp",
|
||||
"locate_bank_card",
|
||||
"np",
|
||||
"order_points",
|
||||
"quad_area",
|
||||
@@ -518,8 +520,10 @@
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"expand_pts": "(pts: 'np.ndarray', ratio: 'float', shape: 'Tuple[int, int]') -> 'np.ndarray'",
|
||||
"find_card_color": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[CardRegion]'",
|
||||
"find_cards": "(img: 'np.ndarray', max_cards: 'int' = 3, warp_width: 'int' = 0) -> 'List[CardRegion]'",
|
||||
"four_point_warp": "(img: 'np.ndarray', pts: 'Sequence[Sequence[float]]', width: 'int' = 0, height: 'int' = 0) -> 'Tuple[np.ndarray, np.ndarray]'",
|
||||
"locate_bank_card": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[np.ndarray]'",
|
||||
"order_points": "(pts: 'Sequence[Sequence[float]]') -> 'np.ndarray'",
|
||||
"quad_area": "(pts: 'np.ndarray') -> 'float'",
|
||||
"sqrt_": "(x: 'float') -> 'float'",
|
||||
@@ -808,6 +812,7 @@
|
||||
"idline",
|
||||
"imread",
|
||||
"join_text",
|
||||
"locate_bank_card",
|
||||
"logger",
|
||||
"logging",
|
||||
"normalize_text",
|
||||
@@ -850,6 +855,7 @@
|
||||
"idline": "(views: 'Sequence[View]', kind: 'str') -> 'List[Line]'",
|
||||
"imread": "(path: 'str') -> 'np.ndarray'",
|
||||
"join_text": "(items: 'List[Line]') -> 'str'",
|
||||
"locate_bank_card": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[np.ndarray]'",
|
||||
"normalize_text": "(text: 'str') -> 'str'",
|
||||
"number_runs": "(text: 'str', min_len: 'int' = 6) -> 'List[str]'",
|
||||
"ocr_lines": "(img: 'np.ndarray', min_score: 'float' = 0.0) -> 'List[Line]'",
|
||||
|
||||
@@ -104,4 +104,4 @@ __all__ = [
|
||||
"mark", "summarize",
|
||||
]
|
||||
|
||||
__version__ = "0.5.0"
|
||||
__version__ = "0.5.3"
|
||||
|
||||
@@ -10,7 +10,7 @@ import numpy as np
|
||||
|
||||
from . import matcher
|
||||
|
||||
EXPECTED_VERSION = "0.5.0"
|
||||
EXPECTED_VERSION = "0.5.3"
|
||||
|
||||
#: 插件实际用到的门面 API,缺失即视为破坏性变更
|
||||
REQUIRED_EXPORTS = (
|
||||
|
||||
@@ -14,9 +14,10 @@ BANK_KEYWORDS = ("银行", "银联", "UnionPay", "UNIONPAY", "Debit", "Credit",
|
||||
"信用卡", "储蓄卡", "一卡通", "招商", "农业", "工商", "建设", "民生",
|
||||
"兴业", "浦发", "交通", "邮政", "中信", "光大", "华夏", "广发", "平安")
|
||||
|
||||
BANK_NAMES = ("中国工商银行", "中国农业银行", "中国建设银行", "中国银行", "招商银行",
|
||||
"中国民生银行", "兴业银行", "浦发银行", "交通银行", "中国邮政储蓄银行",
|
||||
"中信银行", "中国光大银行", "华夏银行", "广发银行", "平安银行")
|
||||
BANK_NAMES = ("重庆农村商业银行", "重庆三峡银行", "中国工商银行", "中国农业银行",
|
||||
"中国建设银行", "中国银行", "招商银行", "中国民生银行", "兴业银行",
|
||||
"浦发银行", "交通银行", "中国邮政储蓄银行", "中信银行", "中国光大银行",
|
||||
"华夏银行", "广发银行", "平安银行")
|
||||
|
||||
_VALID_BANK_LEN = (16, 18, 19)
|
||||
|
||||
@@ -64,7 +65,9 @@ def _bank_from_face(text: str) -> str:
|
||||
"招商": "招商银行", "民生": "中国民生银行", "兴业": "兴业银行",
|
||||
"浦发": "浦发银行", "交通": "交通银行", "邮政": "中国邮政储蓄银行",
|
||||
"中信": "中信银行", "光大": "中国光大银行", "华夏": "华夏银行",
|
||||
"广发": "广发银行", "平安": "平安银行"}
|
||||
"广发": "广发银行", "平安": "平安银行",
|
||||
"重庆农商": "重庆农村商业银行", "重庆农村商业": "重庆农村商业银行",
|
||||
"三峡": "重庆三峡银行"}
|
||||
for k, v in short.items():
|
||||
if k + "银行" in text or k in text:
|
||||
return v
|
||||
|
||||
@@ -141,3 +141,126 @@ def expand_pts(pts: np.ndarray, ratio: float, shape: Tuple[int, int]) -> np.ndar
|
||||
"""把四边形向外扩一点(卡片边缘会把字裁掉时用)。"""
|
||||
c = pts.mean(axis=0)
|
||||
return (pts - c) * (1.0 + ratio) + c
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 色块兜底定位
|
||||
# Canny 找四边形要求卡边基本连续,反光/压边/桌面同色时常直接失败(实测有的卡图
|
||||
# 一张都找不到)。卡面通常是一整块同色区域,所以再补两条更宽松的路子:
|
||||
# 1) 量化主色相 → 色块掩膜 → 最大轮廓 → 最小外接矩形;
|
||||
# 2) Canny 边缘闭运算桥接反光断口 → 最大几个轮廓 → 最小外接矩形。
|
||||
|
||||
def _mask_card_rects(small: np.ndarray) -> List[Tuple]:
|
||||
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
|
||||
h, w = small.shape[:2]
|
||||
sel = (hsv[..., 1] > 60) & (hsv[..., 2] > 25)
|
||||
if int(sel.sum()) < h * w * 0.02:
|
||||
return []
|
||||
hue = hsv[..., 0][sel].astype(np.int32)
|
||||
hist = np.bincount(hue // 15, minlength=12)[:12]
|
||||
out: List[Tuple] = []
|
||||
for t in np.argsort(hist)[::-1][:2]:
|
||||
if hist[t] < h * w * 0.01:
|
||||
continue
|
||||
lo = int(t * 15)
|
||||
m = cv2.inRange(hsv, (lo, 60, 25), (lo + 14, 255, 255))
|
||||
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((41, 41), np.uint8))
|
||||
m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((11, 11), np.uint8))
|
||||
cnts, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
if not cnts:
|
||||
continue
|
||||
c = max(cnts, key=cv2.contourArea)
|
||||
if cv2.contourArea(c) < h * w * 0.05:
|
||||
continue
|
||||
out.append(cv2.minAreaRect(c))
|
||||
return out
|
||||
|
||||
|
||||
def _edge_card_rects(small: np.ndarray) -> List[Tuple]:
|
||||
h, w = small.shape[:2]
|
||||
edges = cv2.Canny(cv2.GaussianBlur(to_gray(small), (5, 5), 0), 40, 120)
|
||||
# 大核闭运算把反光造成的断口接上,否则轮廓不闭合
|
||||
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((15, 15), np.uint8))
|
||||
cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
out: List[Tuple] = []
|
||||
for c in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]:
|
||||
if cv2.contourArea(c) < h * w * 0.05:
|
||||
continue
|
||||
out.append(cv2.minAreaRect(c))
|
||||
return out
|
||||
|
||||
|
||||
def _warp_card(img: np.ndarray, rect: Tuple, width: int) -> np.ndarray:
|
||||
"""按最小外接矩形矫正,并保证「卡长边 → 图宽」(否则会横拉成瘦长条)。"""
|
||||
(cx, cy), (rw, rh), ang = rect
|
||||
box = cv2.boxPoints(((cx, cy), (rw, rh), ang)).astype(np.float32)
|
||||
pts = order_points(box)
|
||||
e_w = float(np.linalg.norm(pts[1] - pts[0])) # 将映射到「宽」的那条边
|
||||
e_h = float(np.linalg.norm(pts[3] - pts[0])) # 将映射到「高」的那条边
|
||||
if e_w < e_h: # 横边是短边 → 卡长边在竖直方向
|
||||
pts = np.roll(pts, -1, axis=0)
|
||||
w = int(width)
|
||||
h = int(round(width / CARD_ASPECT))
|
||||
m = cv2.getPerspectiveTransform(
|
||||
pts, np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]))
|
||||
return cv2.warpPerspective(img, m, (w, h), flags=cv2.INTER_CUBIC)
|
||||
|
||||
|
||||
def find_card_color(img: np.ndarray, warp_width: int = 1712) -> Optional[CardRegion]:
|
||||
"""色块/边缘兜底找卡(find_cards 失败时用),返回已矫正的卡图。
|
||||
|
||||
比例按 85.6:54 还原,长边对应图宽;方向(上下/左右)不在这里判,由调用方
|
||||
根据 OCR 结果决定,避免再引入一次不可靠的方向猜测。
|
||||
"""
|
||||
h, w = img.shape[:2]
|
||||
scale = 1000.0 / max(h, w)
|
||||
if scale < 1.0:
|
||||
small = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
|
||||
inv = 1.0 / scale
|
||||
else:
|
||||
small, inv = img, 1.0
|
||||
rects = _mask_card_rects(small) + _edge_card_rects(small)
|
||||
best, best_score = None, 0.0
|
||||
for rect in rects:
|
||||
(cx, cy), (rw, rh), ang = rect
|
||||
if min(rw, rh) <= 0:
|
||||
continue
|
||||
# 只按长宽比评分,不奖励面积:边缘法经常把「卡+桌面」框成一个同样比例的大矩形,
|
||||
# 按面积优选就会选中那个,矫正后的卡反而变小、卡号更难认。
|
||||
score = _aspect_score(max(rw, rh) / min(rw, rh))
|
||||
if score > best_score:
|
||||
best, best_score = rect, score
|
||||
if best is None:
|
||||
return None
|
||||
(cx, cy), (rw, rh), ang = best
|
||||
rect_full = ((cx * inv, cy * inv), (rw * inv, rh * inv), ang)
|
||||
pts = order_points(cv2.boxPoints(rect_full).astype(np.float32))
|
||||
region = CardRegion(pts=pts, area=rw * rh * inv * inv,
|
||||
aspect=max(rw, rh) / min(rw, rh), score=best_score,
|
||||
source="color")
|
||||
region.warped = _warp_card(img, rect_full, warp_width)
|
||||
return region
|
||||
|
||||
|
||||
def _digit_score(lines) -> int:
|
||||
n = sum(1 for x in lines for ch in x.text if ch.isdigit())
|
||||
rows = sum(1 for x in lines if sum(ch.isdigit() for ch in x.text) >= 4)
|
||||
return n + 5 * rows
|
||||
|
||||
|
||||
def locate_bank_card(img: np.ndarray, warp_width: int = 1712) -> Optional[np.ndarray]:
|
||||
"""色块兜底找卡 + 用 OCR 结果判方向,返回「摆正的卡图」;找不到返回 None。"""
|
||||
region = find_card_color(img, warp_width=warp_width)
|
||||
if region is None or region.warped is None or region.warped.size == 0:
|
||||
return None
|
||||
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
|
||||
|
||||
card = region.warped
|
||||
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
|
||||
for k in (0, 2)]
|
||||
scored.sort(reverse=True)
|
||||
if scored[0][0] <= 0: # 0/180 都读不到数字,说明卡是横躺的
|
||||
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
|
||||
for k in (1, 3)]
|
||||
scored.sort(reverse=True)
|
||||
k = scored[0][1]
|
||||
return np.ascontiguousarray(np.rot90(card, k))
|
||||
|
||||
@@ -57,6 +57,18 @@ def engine_available() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
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():
|
||||
global _ENGINE
|
||||
if _ENGINE is not None:
|
||||
@@ -68,7 +80,7 @@ def _get_engine():
|
||||
|
||||
# 固定线程数:默认会按核数开线程,在共享办公机上反而抖动严重(同一张图 2s~13s)
|
||||
params = {
|
||||
"Global.log_level": "WARNING",
|
||||
"Global.log_level": "ERROR",
|
||||
"EngineConfig.onnxruntime.intra_op_num_threads": 4,
|
||||
"EngineConfig.onnxruntime.inter_op_num_threads": 1,
|
||||
}
|
||||
@@ -76,7 +88,7 @@ def _get_engine():
|
||||
_ENGINE = RapidOCR(params=params)
|
||||
except Exception: # noqa: BLE001 旧版本不支持 params
|
||||
_ENGINE = RapidOCR()
|
||||
logging.getLogger("RapidOCR").setLevel(logging.WARNING)
|
||||
_silence_rapidocr()
|
||||
return _ENGINE
|
||||
|
||||
|
||||
|
||||
@@ -166,7 +166,8 @@ def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
|
||||
) -> List[Tuple[int, int, int, int]]:
|
||||
"""定位卡号带的若干候选(按可能性排序),返回 [(x1, y1, x2, y2), ...]。
|
||||
|
||||
只做「纵向定位」:横向跨度交给 _SPAN_RATIOS 先验,避免被花纹干扰。
|
||||
返回的 x 跨度是 MSER 行自己的实际范围(不再写死整图 3%~97%),
|
||||
这样卡片没占满画面、或者只是裁出来的卡图,分组窗口都能对得上。
|
||||
"""
|
||||
if gray is None or gray.size == 0:
|
||||
return []
|
||||
@@ -189,13 +190,14 @@ def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
|
||||
continue
|
||||
med_h = float(np.median([b[3] for b in row]))
|
||||
score = 2.0 * span + min(len(row), 12) / 12.0 + 12.0 * (med_h / small.shape[0])
|
||||
scraped.append((score, float(np.median([b[1] + b[3] / 2.0 for b in row])), med_h, row))
|
||||
scraped.append((score, float(np.median([b[1] + b[3] / 2.0 for b in row])), med_h,
|
||||
float(x1), float(x2)))
|
||||
scraped.sort(key=lambda x: -x[0])
|
||||
|
||||
inv = 1.0 / scale if scale < 1.0 else 1.0
|
||||
out: List[Tuple[int, int, int, int]] = []
|
||||
centers: List[float] = []
|
||||
for _score, yc_s, med_h_s, _row in scraped:
|
||||
for _score, yc_s, med_h_s, x1_s, x2_s in scraped:
|
||||
yc, med_h = yc_s * inv, med_h_s * inv
|
||||
if any(abs(yc - c) < max(med_h * 0.6, 8) for c in centers):
|
||||
continue
|
||||
@@ -204,7 +206,10 @@ def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
|
||||
half = max(half, h * 0.030)
|
||||
y1 = max(0, int(yc - half))
|
||||
y2 = min(h, int(yc + half))
|
||||
out.append((int(w * 0.03), y1, int(w * 0.97), y2))
|
||||
# x 跨度用 MSER 行自己的实际范围(原来写死 3%~97%,卡片没占满画面时分组窗口会整体错位)
|
||||
x1, x2 = int(x1_s * inv), int(x2_s * inv)
|
||||
pad = max(4, int((x2 - x1) * 0.04))
|
||||
out.append((max(0, x1 - pad), y1, min(w, x2 + pad), y2))
|
||||
centers.append(yc)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
@@ -378,11 +383,47 @@ def _bank_from_text(text: str) -> str:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 对外接口
|
||||
def _warp_fallback(bgr: np.ndarray) -> Optional[np.ndarray]:
|
||||
"""整图找不到卡号带时的兜底:按色块/边缘找卡并摆正,失败返回 None。"""
|
||||
try:
|
||||
from .cards import locate_bank_card # noqa: PLC0415 避免循环引用
|
||||
return locate_bank_card(bgr)
|
||||
except Exception: # noqa: BLE001 兜底链路不允许把主流程带崩
|
||||
logger.debug("找卡兜底失败", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def _text_bands(bgr: np.ndarray) -> List[Tuple[int, int, int, int]]:
|
||||
"""MSER 找不到卡号带时的兜底:用 OCR 检出的数字行定 y、卡宽定 x。
|
||||
|
||||
浮雕卡片的数字是「同色凸起」,MSER 经常整行都检测不到;而 OCR 检测网络对
|
||||
这类卡面仍能框出部分数字(哪怕只读到 4 位),用它定纵向位置更稳。
|
||||
"""
|
||||
try:
|
||||
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
|
||||
ls = ocr_lines(bgr)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
h, w = bgr.shape[:2]
|
||||
rows = [ln for ln in ls if sum(1 for ch in ln.text if ch.isdigit()) >= 2]
|
||||
rows.sort(key=lambda ln: -ln.width)
|
||||
out: List[Tuple[int, int, int, int]] = []
|
||||
for ln in rows[:2]:
|
||||
cy = (ln.top + ln.bottom) / 2.0
|
||||
half = max(24, int(ln.height * 0.75))
|
||||
out.append((int(w * _SPAN_RATIOS[0][0]), max(0, int(cy - half)),
|
||||
int(w * _SPAN_RATIOS[0][1]), min(h, int(cy + half))))
|
||||
return out
|
||||
|
||||
|
||||
def _band_probe(gray: np.ndarray, band: Tuple[int, int, int, int]) -> int:
|
||||
"""便宜地试读一条带子:只跑 morph 一路,数「正好 4 位」的分组个数。"""
|
||||
_, y1, _, y2 = band
|
||||
xa, y1, xb, y2 = band
|
||||
h, w = gray.shape[:2]
|
||||
xa, xb = int(w * _SPAN_RATIOS[0][0]), int(w * _SPAN_RATIOS[0][1])
|
||||
if xb - xa < w * 0.6: # 带子比整图窄:按带子自己的跨度切
|
||||
xa, xb = max(0, xa), min(w, xb)
|
||||
else:
|
||||
xa, xb = int(w * _SPAN_RATIOS[0][0]), int(w * _SPAN_RATIOS[0][1])
|
||||
gw = (xb - xa) / 4.0
|
||||
good = 0
|
||||
for i in range(4):
|
||||
@@ -415,9 +456,20 @@ def read_bank_card_number(image, face_text: str = "") -> NumberReading:
|
||||
candidate/failed,不硬猜。
|
||||
"""
|
||||
t0 = time.time()
|
||||
gray = to_gray(image) if isinstance(image, np.ndarray) else to_gray(imread(str(image)))
|
||||
src = image if isinstance(image, np.ndarray) else imread(str(image))
|
||||
if src is None or getattr(src, "size", 0) == 0:
|
||||
return NumberReading(elapsed_s=time.time() - t0)
|
||||
gray = to_gray(src)
|
||||
res = NumberReading()
|
||||
bands = find_number_bands(gray)
|
||||
if not bands and getattr(src, "ndim", 0) == 3:
|
||||
# 整图定位不到卡号带(卡没占满画面、拍歪、反光打断):先自动找卡摆正再试
|
||||
warped = _warp_fallback(src)
|
||||
if warped is not None:
|
||||
gray = to_gray(warped)
|
||||
bands = find_number_bands(gray) or _text_bands(warped)
|
||||
if not bands and getattr(src, "ndim", 0) == 3:
|
||||
bands = _text_bands(src)
|
||||
if not bands:
|
||||
res.elapsed_s = time.time() - t0
|
||||
return res
|
||||
@@ -431,10 +483,16 @@ def read_bank_card_number(image, face_text: str = "") -> NumberReading:
|
||||
best: Optional[NumberReading] = None
|
||||
best_key = (-1, -1, -1, -1)
|
||||
for band in ordered[:2]:
|
||||
_, y1, _, y2 = band
|
||||
bx1, y1, bx2, y2 = band
|
||||
pad = max(4, int((y2 - y1) * 0.06))
|
||||
y1, y2 = max(0, y1 - pad), min(h, y2 + pad)
|
||||
for (ra, rb) in _SPAN_RATIOS:
|
||||
spans = []
|
||||
if 0 < bx2 - bx1 < w * 0.85:
|
||||
# 带子明显比整图窄:优先用它自己的实际跨度(卡没占满画面时固定百分比会错位)
|
||||
pw = max(4, int((bx2 - bx1) * 0.04))
|
||||
spans.append((max(0, bx1 - pw) / float(w), min(w, bx2 + pw) / float(w)))
|
||||
spans.extend(_SPAN_RATIOS)
|
||||
for (ra, rb) in spans:
|
||||
xa, xb = int(w * ra), int(w * rb)
|
||||
gw = (xb - xa) / 4.0
|
||||
groups = [_pick_group(gray, int(round(xa + gw * i)),
|
||||
|
||||
@@ -20,7 +20,7 @@ import cv2
|
||||
import numpy as np
|
||||
|
||||
from . import bankcard, idcard
|
||||
from .cards import find_cards
|
||||
from .cards import find_cards, locate_bank_card
|
||||
from .engine import Line, join_text, lines as ocr_lines, row_texts, text_line
|
||||
from .img import apply_exif, gray_variants, imread, resize_side, rotate90, to_gray
|
||||
from .validators import (_CONFUSABLE, PRIMARY, card_candidates, id_candidates,
|
||||
@@ -353,9 +353,21 @@ def analyze_image(path: str, expected_name: str = "",
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
|
||||
# ---- 6) 兜底:整图几乎没识别到文字时,试一次卡片四边形矫正
|
||||
if not fast and len([ln for v in views for ln in v.lines]) < 3:
|
||||
for i, r in enumerate(find_cards(img_work, max_cards=2, warp_width=1712)):
|
||||
# ---- 6) 兜底:卡号/身份证没读出来时,试一次卡片矫正
|
||||
# 注意条件不能只看「几乎没文字」:手机拍卡常能认出「招商银行/银联」几行,
|
||||
# 文字够多但卡号一个都没检出,这时同样需要矫正后再认一遍。
|
||||
if not fast and (len([ln for v in views for ln in v.lines]) < 3
|
||||
or (not (bank_res.found and bank_res.luhn_ok)
|
||||
and bankcard.looks_like_bank_card(
|
||||
" ".join(v.text for v in views)))):
|
||||
quads = list(find_cards(img_work, max_cards=2, warp_width=1712))
|
||||
if not quads:
|
||||
# Canny 四边形找不到(反光打断卡边)时,退到色块/边缘兜底
|
||||
flat = locate_bank_card(img_work, warp_width=1712)
|
||||
if flat is not None:
|
||||
add_view(View(name="quad1", image=flat, source="quad",
|
||||
rect=(0, 0, flat.shape[1], flat.shape[0])))
|
||||
for i, r in enumerate(quads):
|
||||
if r.warped is not None and r.warped.size:
|
||||
add_view(View(name=f"quad{i + 1}", image=r.warped, source="quad",
|
||||
rect=cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))))
|
||||
|
||||
@@ -231,51 +231,62 @@ class CardCandidate:
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断
|
||||
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断。
|
||||
# 与插件 XQ0005「银行卡检查」的已核验工资卡 BIN 对齐(重庆农商/三峡等本地卡种),
|
||||
# 同一 BIN 只能对应一家银行,勿重复登记(Python dict 重复键会静默覆盖)。
|
||||
BIN_BANK: Dict[str, str] = {
|
||||
# 工商银行
|
||||
"622202": "中国工商银行", "622203": "中国工商银行", "622200": "中国工商银行",
|
||||
"622208": "中国工商银行", "621226": "中国工商银行", "955880": "中国工商银行",
|
||||
"955882": "中国工商银行", "621225": "中国工商银行",
|
||||
"622200": "中国工商银行", "622202": "中国工商银行", "622203": "中国工商银行",
|
||||
"622208": "中国工商银行", "621225": "中国工商银行", "621226": "中国工商银行",
|
||||
"955880": "中国工商银行", "955882": "中国工商银行",
|
||||
# 农业银行
|
||||
"622848": "中国农业银行", "622845": "中国农业银行", "622846": "中国农业银行",
|
||||
"622849": "中国农业银行", "621336": "中国农业银行", "622841": "中国农业银行",
|
||||
"621336": "中国农业银行", "622841": "中国农业银行", "622845": "中国农业银行",
|
||||
"622846": "中国农业银行", "622848": "中国农业银行", "622849": "中国农业银行",
|
||||
# 建设银行
|
||||
"621700": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
|
||||
"622280": "中国建设银行", "621081": "中国建设银行",
|
||||
"621081": "中国建设银行", "621499": "中国建设银行", "621700": "中国建设银行",
|
||||
"622280": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
|
||||
# 中国银行
|
||||
"621661": "中国银行", "621660": "中国银行", "621662": "中国银行",
|
||||
"621663": "中国银行", "621665": "中国银行", "601382": "中国银行",
|
||||
"456351": "中国银行", "621785": "中国银行", "621786": "中国银行",
|
||||
"456351": "中国银行", "601382": "中国银行", "621660": "中国银行",
|
||||
"621661": "中国银行", "621662": "中国银行", "621663": "中国银行",
|
||||
"621665": "中国银行", "621785": "中国银行", "621786": "中国银行",
|
||||
"621787": "中国银行", "621788": "中国银行", "621789": "中国银行",
|
||||
# 招商银行
|
||||
"621483": "招商银行", "622588": "招商银行", "621286": "招商银行",
|
||||
"622575": "招商银行", "622576": "招商银行", "622577": "招商银行",
|
||||
"622578": "招商银行", "622579": "招商银行",
|
||||
"621286": "招商银行", "621483": "招商银行", "621485": "招商银行",
|
||||
"621486": "招商银行", "622575": "招商银行", "622576": "招商银行",
|
||||
"622577": "招商银行", "622578": "招商银行", "622579": "招商银行",
|
||||
"622588": "招商银行", "622609": "招商银行",
|
||||
# 民生银行
|
||||
"622622": "中国民生银行", "622600": "中国民生银行", "622601": "中国民生银行",
|
||||
"622602": "中国民生银行", "622603": "中国民生银行", "622615": "中国民生银行",
|
||||
"622617": "中国民生银行", "622619": "中国民生银行", "622621": "中国民生银行",
|
||||
"622623": "中国民生银行", "421393": "中国民生银行",
|
||||
"421393": "中国民生银行", "621691": "中国民生银行", "622600": "中国民生银行",
|
||||
"622601": "中国民生银行", "622602": "中国民生银行", "622603": "中国民生银行",
|
||||
"622615": "中国民生银行", "622617": "中国民生银行", "622619": "中国民生银行",
|
||||
"622620": "中国民生银行", "622621": "中国民生银行", "622622": "中国民生银行",
|
||||
"622623": "中国民生银行",
|
||||
# 兴业银行
|
||||
"622908": "兴业银行", "622909": "兴业银行", "621084": "兴业银行",
|
||||
"621084": "兴业银行", "622908": "兴业银行", "622909": "兴业银行",
|
||||
# 浦发银行
|
||||
"622521": "浦发银行", "622522": "浦发银行", "622523": "浦发银行",
|
||||
"622516": "浦发银行", "622517": "浦发银行", "622518": "浦发银行",
|
||||
"622525": "浦发银行", "622526": "浦发银行",
|
||||
"621792": "浦发银行", "621793": "浦发银行", "622516": "浦发银行",
|
||||
"622517": "浦发银行", "622518": "浦发银行", "622521": "浦发银行",
|
||||
"622522": "浦发银行", "622523": "浦发银行", "622525": "浦发银行",
|
||||
"622526": "浦发银行",
|
||||
# 交通银行
|
||||
"622260": "交通银行", "622262": "交通银行", "622250": "交通银行",
|
||||
"622251": "交通银行", "622252": "交通银行", "622253": "交通银行",
|
||||
"622254": "交通银行", "622255": "交通银行",
|
||||
"622250": "交通银行", "622251": "交通银行", "622252": "交通银行",
|
||||
"622253": "交通银行", "622254": "交通银行", "622255": "交通银行",
|
||||
"622260": "交通银行", "622262": "交通银行",
|
||||
# 邮储银行
|
||||
"620062": "中国邮政储蓄银行", "621095": "中国邮政储蓄银行",
|
||||
"622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行",
|
||||
"621095": "中国邮政储蓄银行", "620062": "中国邮政储蓄银行", "955100": "中国邮政储蓄银行",
|
||||
"955100": "中国邮政储蓄银行",
|
||||
# 中信 / 光大 / 华夏 / 广发 / 平安
|
||||
"622690": "中信银行", "622691": "中信银行", "622692": "中信银行",
|
||||
"622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行",
|
||||
"622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行",
|
||||
"622568": "广发银行", "622576": "广发银行",
|
||||
"623020": "华夏银行",
|
||||
"622568": "广发银行",
|
||||
"622155": "平安银行", "622156": "平安银行", "622157": "平安银行",
|
||||
# 重庆本地(工资卡主力卡种,XQ0005 实际数据核验)
|
||||
"621258": "重庆农村商业银行", "621465": "重庆农村商业银行",
|
||||
"621528": "重庆农村商业银行", "622867": "重庆农村商业银行",
|
||||
"621755": "重庆三峡银行",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -72,6 +72,18 @@ class TextItem:
|
||||
|
||||
|
||||
# ==================== 引擎 ====================
|
||||
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
|
||||
@@ -88,10 +100,10 @@ def _get_engine():
|
||||
"(模型随包内置,无需联网下载;识别失败时可删除 rapidocr/models 重新解压)"
|
||||
) from e
|
||||
try:
|
||||
_ENGINE = RapidOCR(params={"Global.log_level": "WARNING"})
|
||||
_ENGINE = RapidOCR(params={"Global.log_level": "ERROR"})
|
||||
except Exception: # noqa: BLE001 老版本不支持 params
|
||||
_ENGINE = RapidOCR()
|
||||
logging.getLogger("RapidOCR").setLevel(logging.WARNING)
|
||||
_silence_rapidocr()
|
||||
logger.debug("RapidOCR 引擎已初始化")
|
||||
return _ENGINE
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "desktopauto"
|
||||
version = "0.5.0"
|
||||
version = "0.5.3"
|
||||
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别、键鼠输入、窗口与进程管理"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "desktopauto",
|
||||
"name": "桌面自动化 SDK",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.3",
|
||||
"description": "屏幕识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别(号码纠错/命中分析)、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)",
|
||||
"provides": [
|
||||
"desktopauto"
|
||||
|
||||
Reference in New Issue
Block a user