feat(sdk): hr_sdk 0.2.4 工资卡导入、desktopauto 0.5.0 证件照识别、新增插件 XQ0084
- hr_sdk.wage_import:DrissionPage 注入 cookie 打开 HR 门户,页面内 WS 订阅 + fetch 上传,解析 over: 结果;build_xlsx 第 9 列卡号强制数值(修复「卡号必须是数字」) - 纯 HTTP 导入不可用:服务端异步任务与浏览器会话强绑定,且前端无轮询接口(已核实),结果通道只能用浏览器上下文 - desktopauto 0.5.0 新增 cardocr:身份证/银行卡 OCR、号码纠错、Luhn 与模 11-2 校验、交叉核对 - 新增插件 XQ0084 银行卡更新EHR系统:AI 表格待处理行 → 影像识别 → 一致性核对/异常名单 - .gitignore 忽略 tests/aitable_probe/_out/(含员工证件照,禁止入库)
This commit is contained in:
@@ -105,3 +105,6 @@ vc_redist_x86/
|
||||
.assets/
|
||||
# lotsmall 联调账号配置(含明文密码,勿入库)
|
||||
tests/lotsmall_probe/account.json
|
||||
|
||||
# aitable 探针落盘产物(银行卡/身份证照片等员工隐私材料,禁止入库)
|
||||
tests/aitable_probe/_out/
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
| 截图(全屏/区域/窗口) | `screenshot(path)` |
|
||||
| **离线图片标记**(不碰屏幕,框出命中位置) | `mark(image, [tpl1, tpl2], out_path)` |
|
||||
| **文字识别取坐标** | `read_text()` → `[TextItem(text, center, score)]` |
|
||||
| **身份证 / 银行卡照片识别** | `ocr_card(path)` / `ocr_cards(folder)` → 号码、姓名、发卡行、校验结果 |
|
||||
| **按文字判断/等待/点击** | `text_exists("导出")` / `wait_text` / `click_text` |
|
||||
| **多状态按钮** | `find_any([tpl可用, tpl禁用])` → `(命中, 模板名)` |
|
||||
| **输入文本(中文)** | `paste("内容")`(写剪贴板+Ctrl+V)/ `type_text` |
|
||||
@@ -382,6 +383,62 @@ python -m desktopauto --mode ocr --window "钉钉" --text "工作台"
|
||||
| 坐标 | 实时截图返回**屏幕物理像素**,可直接 `click_text`;离线图(`mark` / `--image`)返回图内坐标 |
|
||||
| 稳定性 | OCR 是「看图」不是无障碍接口,界面改版就可能失效;重要流程建议「模板匹配 + OCR」互为兜底 |
|
||||
|
||||
## 证件照识别(身份证 / 银行卡)
|
||||
|
||||
拍照上传的身份证人像面、银行卡卡号面 → 结构化字段。纯离线(RapidOCR + onnxruntime),
|
||||
模型随包,不联网;识别结果用**身份证校验码(模 11-2)/ 银行卡 Luhn** 把 OCR 认错的数字纠回来。
|
||||
|
||||
```python
|
||||
from desktopauto import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(r"D:\照片\张三\银行卡.jpg", expected_name="张三")
|
||||
print(res["bank_card"]["number"], # 6214 8338 3144 5443
|
||||
res["bank_card"]["luhn_ok"], # True
|
||||
res["bank_card"]["bank"], # 招商银行(BIN + 卡面文字双通道)
|
||||
res["flags"]) # ['duplicate_photo'] 等
|
||||
|
||||
rows = ocr_cards(r"D:\照片") # 按「姓名/图片」目录批量,同人多图合并、同图去重
|
||||
```
|
||||
|
||||
输出(每个人的一条记录):
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `id_card.number / checksum_ok / name / gender / birth / address / issue / valid_to` | 身份证:号码、校验是否通过、姓名、性别、出生、住址、签发机关、有效期 |
|
||||
| `bank_card.number / luhn_ok / length / bank / expiry / card_type` | 银行卡:卡号、Luhn、位数、发卡行、有效期、卡类型 |
|
||||
| `confidence` | `high / medium / low`(身份证、卡号各一份) |
|
||||
| `flags` | `id_not_found` `card_not_found` `id_checksum_fail` `card_luhn_fail` `duplicate_photo` `low_resolution` `rotated_90` … |
|
||||
| `digit_runs` | 照片里所有数字片段(和已知号码比对时找证据) |
|
||||
|
||||
识别策略(为什么不是「一步 OCR 全图」):
|
||||
|
||||
1. **粗识别**:缩到 1440 长边定位文字块(快);
|
||||
2. **精修**:字段缺失时回原图按原生分辨率切块重识别(准);
|
||||
3. **多路兜底**:灰度/CLAHE 整图、短边<800px 的缩略图 4 倍放大、数字带黑帽/Otsu/锐化(窄条图跳过检测网络,单路 0.1~0.3s);
|
||||
4. **按行抓号码**:同一行合并、不同行切开,避免把卡号后面的有效期连成假号码;
|
||||
5. **校验位裁判**:易混字符(`b→6/8`、`O→0`、`l→1`…)枚举候选,只有通过校验的才接受;多位可纠时**只认唯一解**,歧义宁可标人工。
|
||||
|
||||
实测(10 人真实样本,人工填真值):身份证号 **100%**、姓名 **80%**、银行卡号 **55.6%** 逐位正确;
|
||||
**认出来的 100% 正确**,错在「读不出」(缩略图/浮雕/反光),不读错。读不出的会带 `card_not_found` 交人工。
|
||||
|
||||
批量核对闭环(Excel 留「待填正确答案」列,填完回读算准确率):
|
||||
|
||||
```python
|
||||
from desktopauto import cardocr
|
||||
cardocr.write_review_workbook(rows, "核对表.xlsx") # 需要 openpyxl
|
||||
print(cardocr.verify_workbook("核对表.xlsx")) # 准确率统计
|
||||
```
|
||||
|
||||
命令行:
|
||||
|
||||
```powershell
|
||||
python -m desktopauto.cardocr scan D:\照片 --json result.json --xlsx 核对表.xlsx
|
||||
python -m desktopauto.cardocr image D:\照片\张三\银行卡.jpg --name 张三
|
||||
```
|
||||
|
||||
依赖:OCR 需 `rapidocr` + `onnxruntime`(可选依赖 `desktopauto[ocr]` / `desktopauto[card]`),
|
||||
导出/回读 Excel 另需 `openpyxl`(`desktopauto[report]`);没装 openpyxl 时导入本库不受影响。
|
||||
|
||||
## 模板图怎么准备
|
||||
|
||||
1. 用 `--mode shot` 截一张,再用画图工具裁出**目标区域**(比目标稍大一点、带完整边框/图标);
|
||||
|
||||
@@ -285,6 +285,45 @@ def main() -> int:
|
||||
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
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""desktopauto —— 屏幕识图 / 文字识别 / 鼠标键盘 工具库(面向无元素树的桌面自动化)。
|
||||
"""desktopauto —— 屏幕识图 / 文字识别 / 鼠标键盘 / 证件照 OCR 工具库(面向无元素树的桌面自动化)。
|
||||
|
||||
只依赖 opencv-python + numpy + pillow(OCR 另需 rapidocr + onnxruntime),
|
||||
鼠标键盘窗口全部走 ctypes 调系统 API,不依赖 pyautogui / pywin32 / 任何底座代码。
|
||||
@@ -14,11 +14,18 @@
|
||||
s.hotkey("ctrl", "enter") # 组合键
|
||||
s.wait_stable_text = s.wait_text("发送成功") # 文字确认
|
||||
|
||||
证件照识别(身份证 / 银行卡,离线,供插件核对上传材料):
|
||||
from desktopauto import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(path, expected_name="张三") # 单张
|
||||
rows = ocr_cards(folder) # 按「姓名/图片」目录批量
|
||||
|
||||
分组:
|
||||
截图 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
|
||||
证件照 ocr_card / ocr_cards / cardocr(身份证、银行卡号码与姓名)
|
||||
输入 paste / type_text / press / hotkey / key_down / key_up
|
||||
鼠标 scroll / drag(click 已含左/右/中键与连击)
|
||||
窗口 list_windows / find_window(s) / wait_window / child_windows /
|
||||
@@ -30,9 +37,11 @@
|
||||
模板不存在/无法解码、窗口找不到、依赖缺失 → RuntimeError(配置错误,需要修);
|
||||
图/文字没匹配到 → None / False(业务上的「不存在」,不是异常)。
|
||||
"""
|
||||
from . import clipboard, colors, fs, keys, ocr, process
|
||||
from . import cardocr, clipboard, colors, fs, keys, ocr, process
|
||||
from ._win32 import click_at
|
||||
from .capture import screenshot
|
||||
from .cardocr import analyze_folder, analyze_image
|
||||
from .cardocr.enhance import read_bank_card_number
|
||||
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)
|
||||
@@ -52,6 +61,10 @@ from .window import (
|
||||
foreground_window, get_window, list_windows, wait_window, window_info, window_rect,
|
||||
)
|
||||
|
||||
# 证件照识别的插件级别名(名字直白,少一层记忆)
|
||||
ocr_card = analyze_image
|
||||
ocr_cards = analyze_folder
|
||||
|
||||
__all__ = [
|
||||
# 门面
|
||||
"Screen",
|
||||
@@ -67,6 +80,9 @@ __all__ = [
|
||||
"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",
|
||||
# 证件照(身份证 / 银行卡)
|
||||
"cardocr", "ocr_card", "ocr_cards", "analyze_image", "analyze_folder",
|
||||
"read_bank_card_number",
|
||||
# RPA 指令别名
|
||||
"image_exists", "wait_image", "click_image", "hover_image", "wait_text_exists",
|
||||
# 输入
|
||||
@@ -88,4 +104,4 @@ __all__ = [
|
||||
"mark", "summarize",
|
||||
]
|
||||
|
||||
__version__ = "0.4.0"
|
||||
__version__ = "0.5.0"
|
||||
|
||||
@@ -10,13 +10,14 @@ import numpy as np
|
||||
|
||||
from . import matcher
|
||||
|
||||
EXPECTED_VERSION = "0.4.0"
|
||||
EXPECTED_VERSION = "0.5.0"
|
||||
|
||||
#: 插件实际用到的门面 API,缺失即视为破坏性变更
|
||||
REQUIRED_EXPORTS = (
|
||||
"Screen", "find", "find_all", "exists", "click", "click_at", "hotkey",
|
||||
"paste", "screenshot", "find_windows", "get_window", "Window",
|
||||
"mark", "summarize", "ocr", "fs", "keys", "sleep",
|
||||
"cardocr", "ocr_card", "ocr_cards",
|
||||
)
|
||||
|
||||
|
||||
@@ -42,5 +43,17 @@ def main() -> int:
|
||||
if hit.center != (hit.left + 30, hit.top + 15):
|
||||
raise AssertionError(f"中心点换算错误:{hit.center}")
|
||||
|
||||
# 证件照识别:只校验纯算法(不加载 OCR 模型、不读图片)
|
||||
from .cardocr import match, validators # noqa: PLC0415
|
||||
|
||||
if not validators.id_checksum_ok("530425198904041120"):
|
||||
raise AssertionError("身份证校验码算法异常")
|
||||
if not validators.luhn_ok("6214833831445443"):
|
||||
raise AssertionError("银行卡 Luhn 算法异常")
|
||||
runs = ["6214832337534461", "621483237534461"]
|
||||
cov, status, _ = match.coverage("6214832377534461", runs, id_digits="530425198904041120")
|
||||
if status not in ("strong", "exact") or cov < 0.85:
|
||||
raise AssertionError(f"卡号命中分析异常:cov={cov:.2f} status={status}")
|
||||
|
||||
print(f"[OK] desktopauto {version} SDK 冒烟通过({len(REQUIRED_EXPORTS)} 项门面 API)")
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份证 / 银行卡照片识别(纯离线 OCR),供插件直接调用。
|
||||
|
||||
能力:
|
||||
照片 → 卡片定位/透视矫正 → 多遍 OCR → 字段提取 → 身份证校验码 / 银行卡 Luhn 纠错
|
||||
身份证:号码、姓名、性别、民族、出生、住址、签发机关、有效期
|
||||
银行卡:卡号、发卡行、有效期、卡类型
|
||||
批量:按「姓名/图片」目录跑,同人多图合并,自动去重(两列传同一张图)
|
||||
核对:导出带「待填正确答案」的 Excel;已知号码时做命中分析(一致/高度疑似/部分命中/读不出)
|
||||
|
||||
插件里最简单的用法:
|
||||
from desktopauto import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(r"D:\\照片\\张三\\银行卡.jpg", expected_name="张三")
|
||||
print(res["bank_card"]["number"], res["bank_card"]["luhn_ok"], res["flags"])
|
||||
|
||||
rows = ocr_cards(r"D:\\照片") # [{folder, id_card, bank_card, flags, ...}]
|
||||
|
||||
依赖:opencv-python / numpy / pillow(本库已有)+ rapidocr / onnxruntime(OCR 可选依赖)。
|
||||
模型随 rapidocr 包内置,纯离线,不联网。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .match import check_person, check_persons
|
||||
from .pipeline import analyze_folder, analyze_image
|
||||
|
||||
__version__ = "0.4.1"
|
||||
|
||||
__all__ = [
|
||||
"analyze_image", "analyze_folder",
|
||||
"check_person", "check_persons",
|
||||
"write_review_workbook", "verify_workbook",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
|
||||
def write_review_workbook(persons, path, source_root: str = "") -> str:
|
||||
"""导出带「待填正确答案」列的核对工作簿(需要 openpyxl)。"""
|
||||
try:
|
||||
from .review import write_review_workbook as _impl # noqa: PLC0415
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise RuntimeError("需要 openpyxl 才能导出核对工作簿:pip install openpyxl") from e
|
||||
return _impl(persons, path, source_root=source_root)
|
||||
|
||||
|
||||
def verify_workbook(path: str) -> dict:
|
||||
"""回读人工填好的核对工作簿,统计识别准确率(需要 openpyxl)。"""
|
||||
try:
|
||||
from .review import verify_workbook as _impl # noqa: PLC0415
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise RuntimeError("需要 openpyxl 才能回读核对工作簿:pip install openpyxl") from e
|
||||
return _impl(path)
|
||||
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""python -m desktopauto.cardocr scan <目录> [--json out.json] [--xlsx 核对表.xlsx]"""
|
||||
from .cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""银行卡字段抽取:卡号 / 发卡行 / 有效期 / 卡类型。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from .engine import Line, join_text
|
||||
from .validators import (BIN_BANK, CardCandidate, bin_bank, card_candidates,
|
||||
luhn_ok, normalize_text)
|
||||
|
||||
BANK_KEYWORDS = ("银行", "银联", "UnionPay", "UNIONPAY", "Debit", "Credit", "借记卡",
|
||||
"信用卡", "储蓄卡", "一卡通", "招商", "农业", "工商", "建设", "民生",
|
||||
"兴业", "浦发", "交通", "邮政", "中信", "光大", "华夏", "广发", "平安")
|
||||
|
||||
BANK_NAMES = ("中国工商银行", "中国农业银行", "中国建设银行", "中国银行", "招商银行",
|
||||
"中国民生银行", "兴业银行", "浦发银行", "交通银行", "中国邮政储蓄银行",
|
||||
"中信银行", "中国光大银行", "华夏银行", "广发银行", "平安银行")
|
||||
|
||||
_VALID_BANK_LEN = (16, 18, 19)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BankCardResult:
|
||||
number: str = ""
|
||||
luhn_ok: bool = False
|
||||
length: int = 0
|
||||
bank: str = ""
|
||||
bank_source: str = "" # bin / face / ""
|
||||
expiry: str = ""
|
||||
card_type: str = ""
|
||||
found: bool = False
|
||||
confidence: str = "low"
|
||||
evidence: List[str] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"found": self.found,
|
||||
"number": self.number,
|
||||
"luhn_ok": self.luhn_ok,
|
||||
"length": self.length,
|
||||
"bank": self.bank,
|
||||
"bank_source": self.bank_source,
|
||||
"expiry": self.expiry,
|
||||
"card_type": self.card_type,
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"candidates": self.candidates,
|
||||
}
|
||||
|
||||
|
||||
def looks_like_bank_card(text: str) -> bool:
|
||||
return any(k.lower() in text.lower() for k in BANK_KEYWORDS)
|
||||
|
||||
|
||||
def _bank_from_face(text: str) -> str:
|
||||
for name in BANK_NAMES:
|
||||
if name in text:
|
||||
return name
|
||||
# OCR 常见残缺写法
|
||||
short = {"工商": "中国工商银行", "农业": "中国农业银行", "建设": "中国建设银行",
|
||||
"招商": "招商银行", "民生": "中国民生银行", "兴业": "兴业银行",
|
||||
"浦发": "浦发银行", "交通": "交通银行", "邮政": "中国邮政储蓄银行",
|
||||
"中信": "中信银行", "光大": "中国光大银行", "华夏": "华夏银行",
|
||||
"广发": "广发银行", "平安": "平安银行"}
|
||||
for k, v in short.items():
|
||||
if k + "银行" in text or k in text:
|
||||
return v
|
||||
return ""
|
||||
|
||||
|
||||
def _expiry(text: str) -> str:
|
||||
m = re.search(r"(0[1-9]|1[0-2])/(2\d{1,2}|9\d)", text)
|
||||
return m.group(0) if m else ""
|
||||
|
||||
|
||||
def _card_type(text: str) -> str:
|
||||
if "Credit" in text or "信用卡" in text:
|
||||
return "信用卡"
|
||||
if "Debit" in text or "借记卡" in text or "储蓄卡" in text:
|
||||
return "借记卡"
|
||||
return ""
|
||||
|
||||
|
||||
def parse(lines: Sequence[Line], full_text: str = "",
|
||||
exclude: Sequence[str] = (), rows: Optional[Sequence[str]] = None) -> BankCardResult:
|
||||
"""从银行卡那一面的 OCR 结果里抽字段。
|
||||
|
||||
rows 是「行文本」(推荐),没有时退回 full_text。
|
||||
"""
|
||||
res = BankCardResult()
|
||||
text = full_text or join_text(lines)
|
||||
if not text:
|
||||
return res
|
||||
|
||||
cands: List[CardCandidate] = card_candidates(rows if rows else text, exclude=exclude)
|
||||
if cands:
|
||||
top = cands[0]
|
||||
res.number = top.number
|
||||
res.luhn_ok = top.luhn_ok
|
||||
res.length = top.digits
|
||||
res.found = True
|
||||
res.bank = top.bank
|
||||
res.bank_source = "bin" if top.bank else ""
|
||||
res.candidates = [{"number": c.number, "luhn_ok": c.luhn_ok,
|
||||
"length": c.digits, "bank": c.bank,
|
||||
"origin": c.origin, "edits": c.edits,
|
||||
"votes": c.votes, "score": round(c.score, 2)}
|
||||
for c in cands]
|
||||
if top.origin == "repaired":
|
||||
res.evidence.append(f"卡号经 {top.edits} 位纠错后通过 Luhn 校验")
|
||||
if not top.luhn_ok:
|
||||
res.evidence.append("⚠ 卡号未通过 Luhn 校验")
|
||||
if not res.bank:
|
||||
b = _bank_from_face(text)
|
||||
if b:
|
||||
res.bank, res.bank_source = b, "face"
|
||||
res.expiry = _expiry(text)
|
||||
res.card_type = _card_type(text)
|
||||
|
||||
if not res.found:
|
||||
res.confidence = "low"
|
||||
return res
|
||||
clean_len = res.length in _VALID_BANK_LEN
|
||||
if res.luhn_ok and clean_len and res.bank:
|
||||
res.confidence = "high"
|
||||
elif res.luhn_ok and clean_len:
|
||||
res.confidence = "medium"
|
||||
else:
|
||||
res.confidence = "low"
|
||||
if not clean_len:
|
||||
res.evidence.append(f"⚠ 卡号位数 {res.length} 不在 16/18/19")
|
||||
return res
|
||||
@@ -0,0 +1,143 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""卡片区域定位:在照片里找出身份证 / 银行卡的四边形,做透视矫正。
|
||||
|
||||
一张照片里可能同时有两张卡(很多人把两张卡摆在一起拍),所以返回多个候选。
|
||||
定位失败时由上层的整图识别兜底,不影响主流程。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from .img import CARD_ASPECT, four_point_warp, order_points, quad_area, to_gray
|
||||
|
||||
|
||||
@dataclass
|
||||
class CardRegion:
|
||||
pts: np.ndarray # 4x2 原图坐标
|
||||
area: float # 像素面积
|
||||
aspect: float # 长宽比(已归一化到 >=1)
|
||||
score: float # 越像卡片分越高
|
||||
warped: Optional[np.ndarray] = None
|
||||
source: str = "contour" # contour / fallback
|
||||
|
||||
|
||||
def _aspect_score(ar: float) -> float:
|
||||
"""长宽比越接近 1.585 分越高(身份证、银行卡同尺寸)。"""
|
||||
if ar <= 0:
|
||||
return 0.0
|
||||
# 允许 1.3~1.9 的透视偏差
|
||||
dev = abs(ar - CARD_ASPECT) / CARD_ASPECT
|
||||
if dev > 0.28:
|
||||
return 0.0
|
||||
return max(0.0, 1.0 - dev / 0.28)
|
||||
|
||||
|
||||
def _rect_score(pts: np.ndarray) -> float:
|
||||
"""四个角接近直角、对边接近等长的程度。"""
|
||||
pts = order_points(pts)
|
||||
sides = []
|
||||
for i in range(4):
|
||||
sides.append(float(np.linalg.norm(pts[(i + 1) % 4] - pts[i])))
|
||||
if min(sides) <= 0:
|
||||
return 0.0
|
||||
# 对边长度比
|
||||
pair_ok = min(sides[0], sides[2]) / max(sides[0], sides[2]) * \
|
||||
min(sides[1], sides[3]) / max(sides[1], sides[3])
|
||||
# 直角性:用相邻边点积
|
||||
ang_ok = 1.0
|
||||
for i in range(4):
|
||||
a = pts[(i - 1) % 4] - pts[i]
|
||||
b = pts[(i + 1) % 4] - pts[i]
|
||||
cosv = abs(float(np.dot(a, b)) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))
|
||||
ang_ok *= max(0.0, 1.0 - cosv)
|
||||
return float(max(0.0, pair_ok) * max(0.0, ang_ok) ** 0.25)
|
||||
|
||||
|
||||
def _candidate_quads(gray: np.ndarray) -> List[np.ndarray]:
|
||||
quads: List[np.ndarray] = []
|
||||
h, w = gray.shape[:2]
|
||||
scale = 1000.0 / max(h, w)
|
||||
if scale < 1.0:
|
||||
small = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
|
||||
inv = 1.0 / scale
|
||||
else:
|
||||
small, inv = gray, 1.0
|
||||
blur = cv2.GaussianBlur(small, (5, 5), 0)
|
||||
for lo, hi in ((40, 120), (80, 200)):
|
||||
edges = cv2.Canny(blur, lo, hi)
|
||||
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)))
|
||||
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
||||
for c in contours:
|
||||
area = cv2.contourArea(c)
|
||||
if area < (small.shape[0] * small.shape[1]) * 0.03:
|
||||
continue
|
||||
peri = cv2.arcLength(c, True)
|
||||
for eps in (0.02, 0.035, 0.05):
|
||||
ap = cv2.approxPolyDP(c, eps * peri, True)
|
||||
if len(ap) == 4:
|
||||
quads.append(np.asarray(ap, dtype=np.float32).reshape(4, 2) * inv)
|
||||
break
|
||||
# 面积由小到大的合并去重(同一张卡的多层轮廓只留一个)
|
||||
return quads
|
||||
|
||||
|
||||
def _dedupe(regions: Sequence[CardRegion], iou_thr: float = 0.6) -> List[CardRegion]:
|
||||
kept: List[CardRegion] = []
|
||||
for r in sorted(regions, key=lambda x: -x.score):
|
||||
dup = False
|
||||
for k in kept:
|
||||
# 用外接矩形 IoU 判重
|
||||
a = cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))
|
||||
b = cv2.boundingRect(np.asarray(k.pts, dtype=np.int32))
|
||||
from .img import iou_rect # noqa: PLC0415
|
||||
|
||||
if iou_rect(a, b) > iou_thr:
|
||||
dup = True
|
||||
break
|
||||
if not dup:
|
||||
kept.append(r)
|
||||
return kept
|
||||
|
||||
|
||||
def find_cards(img: np.ndarray, max_cards: int = 3,
|
||||
warp_width: int = 0) -> List[CardRegion]:
|
||||
"""在照片里定位卡片,返回按可信度排序的区域(含透视矫正图)。"""
|
||||
gray = to_gray(img)
|
||||
quads = _candidate_quads(gray)
|
||||
cands: List[CardRegion] = []
|
||||
for q in quads:
|
||||
ar_raw = max(quad_area(q), 1e-6)
|
||||
ar = 0.0
|
||||
pts = order_points(q)
|
||||
w1 = float(np.linalg.norm(pts[1] - pts[0]))
|
||||
w2 = float(np.linalg.norm(pts[2] - pts[3]))
|
||||
h1 = float(np.linalg.norm(pts[3] - pts[0]))
|
||||
h2 = float(np.linalg.norm(pts[2] - pts[1]))
|
||||
ww, hh = (w1 + w2) / 2.0, (h1 + h2) / 2.0
|
||||
if min(ww, hh) > 0:
|
||||
ar = max(ww / hh, hh / ww)
|
||||
score = _aspect_score(ar) * _rect_score(pts)
|
||||
if score <= 0.05:
|
||||
continue
|
||||
cands.append(CardRegion(pts=pts, area=ar_raw, aspect=ar, score=sqrt_(score)))
|
||||
cands = _dedupe(cands)
|
||||
out: List[CardRegion] = []
|
||||
for r in cands[:max_cards]:
|
||||
r.warped, _ = four_point_warp(img, r.pts, width=warp_width or 0)
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def sqrt_(x: float) -> float:
|
||||
return float(np.sqrt(max(0.0, x)))
|
||||
|
||||
|
||||
def expand_pts(pts: np.ndarray, ratio: float, shape: Tuple[int, int]) -> np.ndarray:
|
||||
"""把四边形向外扩一点(卡片边缘会把字裁掉时用)。"""
|
||||
c = pts.mean(axis=0)
|
||||
return (pts - c) * (1.0 + ratio) + c
|
||||
@@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命令行:scan / image / review / verify"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .match import check_persons, print_report
|
||||
from .pipeline import analyze_folder, analyze_image, summary_table
|
||||
from .review import (load_persons, load_truth_workbook, print_verify, verify_workbook,
|
||||
write_review_workbook)
|
||||
|
||||
|
||||
def _setup_stdout() -> None:
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
_setup_stdout()
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
||||
ap = argparse.ArgumentParser(prog="cardocr", description="身份证 / 银行卡照片识别")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
def common(sp):
|
||||
sp.add_argument("--json", default="", help="结果写入 JSON 文件")
|
||||
sp.add_argument("--xlsx", default="", help="结果写成核对工作簿(含待填列)")
|
||||
sp.add_argument("--mark", default="", help="标注图输出目录")
|
||||
sp.add_argument("--no-extra", action="store_true", help="关闭卡号多遍增强识别(更快)")
|
||||
sp.add_argument("--fast", action="store_true", help="只跑粗识别(最快,精度下降)")
|
||||
sp.add_argument("--limit", type=int, default=0, help="每个目录最多取几张图(0=全部)")
|
||||
|
||||
sp_scan = sub.add_parser("scan", help="按「姓名/图片」目录批量识别")
|
||||
sp_scan.add_argument("root", help="照片根目录")
|
||||
common(sp_scan)
|
||||
|
||||
sp_one = sub.add_parser("image", help="识别单张图片")
|
||||
sp_one.add_argument("path", help="图片路径")
|
||||
sp_one.add_argument("--name", default="", help="预期姓名(用于校验身份证姓名)")
|
||||
common(sp_one)
|
||||
|
||||
sp_rev = sub.add_parser("review", help="把 JSON 结果导出成核对工作簿")
|
||||
sp_rev.add_argument("--json", required=True, help="scan 输出的 JSON")
|
||||
sp_rev.add_argument("--out", required=True, help="输出的 xlsx 路径")
|
||||
|
||||
sp_ver = sub.add_parser("verify", help="回读填好的核对工作簿,算准确率")
|
||||
sp_ver.add_argument("xlsx", help="核对工作簿路径")
|
||||
|
||||
sp_chk = sub.add_parser("check", help="用人工填写的正确值做「命中分析」")
|
||||
sp_chk.add_argument("--json", required=True, help="scan 输出的 JSON")
|
||||
sp_chk.add_argument("--truth", required=True, help="填好的核对工作簿 xlsx")
|
||||
sp_chk.add_argument("--out", default="", help="命中分析结果写入 JSON")
|
||||
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if args.cmd == "scan":
|
||||
persons = analyze_folder(args.root, mark_dir=args.mark or None,
|
||||
extra_passes=not args.no_extra, fast=args.fast,
|
||||
limit=args.limit)
|
||||
print(summary_table(persons))
|
||||
payload = {"root": str(Path(args.root).resolve()), "persons": persons}
|
||||
if args.json:
|
||||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.json).write_text(json.dumps(payload, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(f"\n已写入 {args.json}")
|
||||
if args.xlsx:
|
||||
write_review_workbook(persons, args.xlsx, source_root=payload["root"])
|
||||
print(f"\n核对工作簿已写入 {args.xlsx}")
|
||||
return 0
|
||||
|
||||
if args.cmd == "image":
|
||||
res = analyze_image(args.path, expected_name=args.name, mark_dir=args.mark or None,
|
||||
extra_passes=not args.no_extra, fast=args.fast)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=1))
|
||||
if args.json:
|
||||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.json).write_text(json.dumps({"images": [res]}, ensure_ascii=False,
|
||||
indent=1), encoding="utf-8")
|
||||
return 0
|
||||
|
||||
if args.cmd == "review":
|
||||
persons = load_persons(args.json)
|
||||
write_review_workbook(persons, args.out)
|
||||
print(f"核对工作簿已写入 {args.out}({len(persons)} 行)")
|
||||
return 0
|
||||
|
||||
if args.cmd == "check":
|
||||
persons = load_persons(args.json)
|
||||
truth = load_truth_workbook(args.truth)
|
||||
rows = check_persons(persons, truth)
|
||||
print(print_report(rows))
|
||||
if args.out:
|
||||
Path(args.out).write_text(json.dumps(rows, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(f"\n命中分析已写入 {args.out}")
|
||||
return 0
|
||||
|
||||
result = verify_workbook(args.xlsx)
|
||||
print_verify(result)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,194 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""OCR 引擎封装(RapidOCR / onnxruntime,纯离线,模型随包)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, List, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger("cardocr")
|
||||
|
||||
_ENGINE = None
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Line:
|
||||
"""一段识别文本 + 图内像素框。"""
|
||||
|
||||
text: str
|
||||
left: int
|
||||
top: int
|
||||
width: int
|
||||
height: int
|
||||
score: float
|
||||
|
||||
@property
|
||||
def right(self) -> int:
|
||||
return self.left + self.width
|
||||
|
||||
@property
|
||||
def bottom(self) -> int:
|
||||
return self.top + self.height
|
||||
|
||||
@property
|
||||
def x_mid(self) -> float:
|
||||
return self.left + self.width / 2.0
|
||||
|
||||
@property
|
||||
def y_mid(self) -> float:
|
||||
return self.top + self.height / 2.0
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"text": self.text, "left": self.left, "top": self.top,
|
||||
"width": self.width, "height": self.height,
|
||||
"score": round(float(self.score), 3)}
|
||||
|
||||
|
||||
def engine_available() -> bool:
|
||||
try:
|
||||
import importlib.util # noqa: PLC0415
|
||||
|
||||
return importlib.util.find_spec("rapidocr") is not None
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _get_engine():
|
||||
global _ENGINE
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
with _LOCK:
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
from rapidocr import RapidOCR # noqa: PLC0415
|
||||
|
||||
# 固定线程数:默认会按核数开线程,在共享办公机上反而抖动严重(同一张图 2s~13s)
|
||||
params = {
|
||||
"Global.log_level": "WARNING",
|
||||
"EngineConfig.onnxruntime.intra_op_num_threads": 4,
|
||||
"EngineConfig.onnxruntime.inter_op_num_threads": 1,
|
||||
}
|
||||
try:
|
||||
_ENGINE = RapidOCR(params=params)
|
||||
except Exception: # noqa: BLE001 旧版本不支持 params
|
||||
_ENGINE = RapidOCR()
|
||||
logging.getLogger("RapidOCR").setLevel(logging.WARNING)
|
||||
return _ENGINE
|
||||
|
||||
|
||||
def lines(img: np.ndarray, min_score: float = 0.0) -> List[Line]:
|
||||
"""对一张 BGR / 灰度图做识别,返回按阅读顺序排序的文本行。"""
|
||||
if img is None or img.size == 0:
|
||||
return []
|
||||
if img.ndim == 3:
|
||||
bgr = img
|
||||
else:
|
||||
bgr = np.dstack([img, img, img])
|
||||
engine = _get_engine()
|
||||
# 显式给全开关:RapidOCR 会把上次调用的开关记在实例上,写错一次后面全错
|
||||
out = engine(np.ascontiguousarray(bgr), use_det=True, use_cls=True, use_rec=True)
|
||||
boxes = getattr(out, "boxes", None)
|
||||
txts = getattr(out, "txts", None)
|
||||
scores = getattr(out, "scores", None)
|
||||
if boxes is None or txts is None:
|
||||
return []
|
||||
res: List[Line] = []
|
||||
for i, (box, text) in enumerate(zip(boxes, txts)):
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
score = float(scores[i]) if scores is not None and i < len(scores) else 1.0
|
||||
if score < min_score:
|
||||
continue
|
||||
pts = np.asarray(box, dtype=np.float32).reshape(-1, 2)
|
||||
l, t = int(np.floor(pts[:, 0].min())), int(np.floor(pts[:, 1].min()))
|
||||
r, b = int(np.ceil(pts[:, 0].max())), int(np.ceil(pts[:, 1].max()))
|
||||
if r <= l or b <= t:
|
||||
continue
|
||||
res.append(Line(text=text, left=l, top=t, width=r - l, height=b - t, score=score))
|
||||
res.sort(key=lambda x: (x.top // 10, x.left))
|
||||
return res
|
||||
|
||||
|
||||
def text_line(img: np.ndarray) -> str:
|
||||
"""把「只含一行文字」的裁剪图直接送进识别网络(跳过检测网络,快约 10 倍)。
|
||||
|
||||
卡号带这种窄条图只有一行字,检测/分类没有意义,跳过能省掉一次 1~5s 的推理。
|
||||
"""
|
||||
if img is None or img.size == 0:
|
||||
return ""
|
||||
if img.ndim == 2:
|
||||
bgr = np.dstack([img, img, img])
|
||||
else:
|
||||
bgr = img
|
||||
engine = _get_engine()
|
||||
try:
|
||||
try:
|
||||
out = engine(np.ascontiguousarray(bgr), use_det=False, use_cls=False)
|
||||
finally:
|
||||
# 这两个开关会写进引擎实例,必须恢复,否则后面的整图识别会全部变成「无框」
|
||||
engine.update_params(use_det=True, use_cls=True, use_rec=True)
|
||||
except TypeError: # 老版本不支持这些开关
|
||||
return join_text(lines(img))
|
||||
except Exception: # noqa: BLE001
|
||||
return join_text(lines(img))
|
||||
txts = getattr(out, "txts", None)
|
||||
if not txts:
|
||||
return ""
|
||||
return " ".join(str(t) for t in txts if t)
|
||||
|
||||
|
||||
def join_text(items: List[Line]) -> str:
|
||||
"""把多行文本拼成一段(换行变空格,便于人看 / 关键词判断,不用于抓号码)。"""
|
||||
return " ".join(x.text for x in items)
|
||||
|
||||
|
||||
def row_texts(items: List[Line], y_tol: float = 0.75, gap_factor: float = 1.6) -> List[str]:
|
||||
"""把同一视觉行上的文字框合并成「行文本」,再按横向间距切成若干段。
|
||||
|
||||
抓号码必须在「行」粒度上做:整图拼接会把相邻两行的数字连成一个假号码
|
||||
(例如卡号 5443 后面紧跟有效期里的 2000,会被读成 19 位)。
|
||||
"""
|
||||
if not items:
|
||||
return []
|
||||
med_h = float(np.median([x.height for x in items]))
|
||||
clusters: List[List[Line]] = []
|
||||
for ln in sorted(items, key=lambda x: x.y_mid):
|
||||
for cl in clusters:
|
||||
if abs(ln.y_mid - cl[-1].y_mid) <= y_tol * max(med_h, ln.height):
|
||||
cl.append(ln)
|
||||
break
|
||||
else:
|
||||
clusters.append([ln])
|
||||
rows: List[str] = []
|
||||
for cl in clusters:
|
||||
cl.sort(key=lambda x: x.left)
|
||||
parts: List[str] = [cl[0].text]
|
||||
last = cl[0]
|
||||
for ln in cl[1:]:
|
||||
if ln.left - last.right <= gap_factor * med_h:
|
||||
parts[-1] = parts[-1] + " " + ln.text
|
||||
else:
|
||||
parts.append(ln.text)
|
||||
last = ln
|
||||
rows.extend(parts)
|
||||
return rows
|
||||
|
||||
|
||||
def row_texts_multi(views: Iterable) -> List[str]:
|
||||
"""多个视图的行文本汇总(每个视图单独分行,避免跨卡片串号)。"""
|
||||
out: List[str] = []
|
||||
for v in views:
|
||||
out.extend(row_texts(v.lines))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
def load(path: str) -> Optional[np.ndarray]:
|
||||
from .img import imread # noqa: PLC0415
|
||||
|
||||
return imread(path)
|
||||
@@ -0,0 +1,462 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浮雕/反光银行卡号增强识别(卡号带定位 + 4 位分组识别 + Luhn 裁决)。
|
||||
|
||||
为什么单独一层:普通整图 OCR 会把 16 位卡号当成「一行长文本」送进识别网络,
|
||||
而识别网络输入宽度有限(约 320px),16 位挤在一起每个字只剩十几像素,必然丢字;
|
||||
浮雕数字(卡面暗、字是同色凸起)又会和背景花纹混在一起,检测网络经常直接看不见。
|
||||
|
||||
这一层不改模型,只改「怎么喂」:
|
||||
1. 用 MSER 找到「一排字高一致的大字」,定位卡号带(它比背景花纹更成块);
|
||||
多行候选按「跨度 + 字高」排序,再用一次便宜的试读挑出真正能读出 4 位的那条;
|
||||
2. 按卡片宽度先验把卡号带切成 4 组,每组左右微调,挑「能稳定读出 4 位」的窗口;
|
||||
3. 每组在多路增强(灰度/均衡/CLAHE/梯度/形态学梯度)上各识别一次,逐位投票;
|
||||
4. 用 Luhn + 位数 + BIN/卡面银行 做裁决;投票有分歧时在「易混数字」里做
|
||||
代价递增的有限搜索,只返回通过 Luhn 的候选,并按「改动代价」排序。
|
||||
|
||||
原则:宁可返回候选 + 需人工,也不硬猜一个通过不了校验的号码。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from .engine import text_line
|
||||
from .img import imread, to_gray
|
||||
from .validators import bin_bank, digitize, luhn_ok, prefix_ok
|
||||
|
||||
logger = logging.getLogger("cardocr")
|
||||
|
||||
# 卡号带的 y 区间先验(标准卡面比例):卡号一般在卡高 40%~92% 处(含拍歪/留白)
|
||||
_BAND_Y_RATIO = (0.40, 0.92)
|
||||
# 卡号横向跨度先验(占卡宽比例),按可能性排序;主假设失败才试后面的
|
||||
_SPAN_RATIOS = ((0.045, 0.955), (0.060, 0.920), (0.075, 0.900))
|
||||
# 分组窗口的左右微调量(相对组宽)
|
||||
_OFFSETS = (0.0, 0.10, -0.10, 0.20, -0.20)
|
||||
# 识别通路:灰度 / 全局均衡 / CLAHE / 梯度 / 形态学梯度(后两者对浮雕边缘最敏感)
|
||||
_VARIANTS = ("gray", "eq", "clahe", "grad", "morph")
|
||||
_PROBE = ("eq", "morph") # 挑窗口时只跑这两路,省时间
|
||||
_MAX_CANDIDATES = 5
|
||||
_MAX_COST = 5 # 候选最多容许的「改动代价」总和
|
||||
_MAX_NODES = 300000 # 搜索节点上限,防病态图卡死
|
||||
_MAX_BANDS = 3
|
||||
|
||||
# 浮雕数字的易混对:反光会把 6 认成 8、0 认成 9、7 认成 2、5 认成 6
|
||||
_EMBOSS_CONFUSION: Dict[str, str] = {
|
||||
"0": "089", "1": "17", "2": "27", "3": "38", "4": "4",
|
||||
"5": "56", "6": "658", "7": "712", "8": "8630", "9": "904",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupRead:
|
||||
"""一个 4 位分组的识别情况。"""
|
||||
|
||||
rect: Tuple[int, int, int, int] # x1, y1, x2, y2
|
||||
offset: float # 相对基线的微调量(组宽倍数)
|
||||
reads: Dict[str, str] = field(default_factory=dict) # 通路 → 数字串
|
||||
digits: str = "" # 逐位投票结果
|
||||
votes: List[Dict[str, int]] = field(default_factory=list)
|
||||
|
||||
def options(self, i: int) -> List[Tuple[str, int, int]]:
|
||||
"""第 i 位的候选 (数字, 改动代价, 票数),按「代价低、票数高」排序。"""
|
||||
votes = self.votes[i] if i < len(self.votes) else {}
|
||||
if not votes:
|
||||
return [(d, 3, 0) for d in "0123456789"]
|
||||
top = max(votes.items(), key=lambda kv: (kv[1], kv[0]))[0]
|
||||
alts = _EMBOSS_CONFUSION.get(top, top)
|
||||
pool = set(votes) | set(alts) | {top}
|
||||
out: List[Tuple[str, int, int]] = []
|
||||
for d in pool:
|
||||
if d == top:
|
||||
cost = 0
|
||||
elif d in votes:
|
||||
cost = 1
|
||||
elif d in alts:
|
||||
cost = 2
|
||||
else:
|
||||
cost = 3
|
||||
out.append((d, cost, votes.get(d, 0)))
|
||||
out.sort(key=lambda o: (o[1], -o[2], o[0]))
|
||||
return out
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"rect": list(self.rect), "offset": round(self.offset, 3),
|
||||
"digits": self.digits, "reads": self.reads,
|
||||
"votes": [dict(v) for v in self.votes]}
|
||||
|
||||
|
||||
@dataclass
|
||||
class NumberReading:
|
||||
number: str = ""
|
||||
luhn_ok: bool = False
|
||||
length: int = 0
|
||||
bank: str = ""
|
||||
confidence: str = "low" # high / medium / low
|
||||
status: str = "failed" # ok / candidate / failed
|
||||
band: Tuple[int, int, int, int] = (0, 0, 0, 0)
|
||||
groups: List[GroupRead] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
elapsed_s: float = 0.0
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"number": self.number, "luhn_ok": self.luhn_ok,
|
||||
"length": self.length, "bank": self.bank,
|
||||
"confidence": self.confidence, "status": self.status,
|
||||
"band": list(self.band),
|
||||
"groups": [g.to_dict() for g in self.groups],
|
||||
"candidates": self.candidates,
|
||||
"elapsed_s": round(self.elapsed_s, 2)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 卡号带定位
|
||||
def _mser_boxes(gray: np.ndarray) -> List[Tuple[int, int, int, int]]:
|
||||
h, w = gray.shape[:2]
|
||||
mser = cv2.MSER_create()
|
||||
mser.setMinArea(max(800, int(h * w * 0.0004)))
|
||||
mser.setMaxArea(int(h * w * 0.08))
|
||||
mser.setDelta(5)
|
||||
try:
|
||||
_, bboxes = mser.detectRegions(gray)
|
||||
except cv2.error: # 个别 OpenCV 构建没编 MSER
|
||||
return []
|
||||
boxes: List[Tuple[int, int, int, int]] = []
|
||||
for (x, y, bw, bh) in bboxes:
|
||||
if bh < h * 0.030 or bh > h * 0.130:
|
||||
continue
|
||||
if bw < bh * 0.15 or bw > bh * 1.80:
|
||||
continue
|
||||
boxes.append((int(x), int(y), int(bw), int(bh)))
|
||||
# MSER 会对同一个字给出多个尺度,按中心点去重(保留面积最大的)
|
||||
boxes.sort(key=lambda b: -b[2] * b[3])
|
||||
keep: List[Tuple[int, int, int, int]] = []
|
||||
tol = max(12, int(min(h, w) * 0.02))
|
||||
for b in boxes:
|
||||
cx, cy = b[0] + b[2] / 2.0, b[1] + b[3] / 2.0
|
||||
if any(abs(cx - (k[0] + k[2] / 2.0)) < tol
|
||||
and abs(cy - (k[1] + k[3] / 2.0)) < tol for k in keep):
|
||||
continue
|
||||
keep.append(b)
|
||||
return keep
|
||||
|
||||
|
||||
def _cluster_rows(boxes: Sequence[Tuple[int, int, int, int]]):
|
||||
if not boxes:
|
||||
return []
|
||||
items = sorted(boxes, key=lambda b: b[1] + b[3] / 2.0)
|
||||
rows: List[List[Tuple[int, int, int, int]]] = []
|
||||
for b in items:
|
||||
yc = b[1] + b[3] / 2.0
|
||||
for row in rows:
|
||||
ref_c = float(np.median([x[1] + x[3] / 2.0 for x in row]))
|
||||
ref_h = float(np.median([x[3] for x in row]))
|
||||
if abs(yc - ref_c) < ref_h * 0.60 and 0.55 < b[3] / ref_h < 1.8:
|
||||
row.append(b)
|
||||
break
|
||||
else:
|
||||
rows.append([b])
|
||||
return rows
|
||||
|
||||
|
||||
def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
|
||||
) -> List[Tuple[int, int, int, int]]:
|
||||
"""定位卡号带的若干候选(按可能性排序),返回 [(x1, y1, x2, y2), ...]。
|
||||
|
||||
只做「纵向定位」:横向跨度交给 _SPAN_RATIOS 先验,避免被花纹干扰。
|
||||
"""
|
||||
if gray is None or gray.size == 0:
|
||||
return []
|
||||
h, w = gray.shape[:2]
|
||||
scale = 1400.0 / max(h, w)
|
||||
small = gray if scale >= 1.0 else cv2.resize(gray, None, fx=scale, fy=scale,
|
||||
interpolation=cv2.INTER_AREA)
|
||||
rows = _cluster_rows(_mser_boxes(small))
|
||||
scraped = []
|
||||
for row in rows:
|
||||
if len(row) < 3:
|
||||
continue
|
||||
x1 = min(b[0] for b in row)
|
||||
x2 = max(b[0] + b[2] for b in row)
|
||||
span = (x2 - x1) / float(small.shape[1])
|
||||
if span < 0.45:
|
||||
continue
|
||||
yc = float(np.median([b[1] + b[3] / 2.0 for b in row])) / small.shape[0]
|
||||
if not (_BAND_Y_RATIO[0] <= yc <= _BAND_Y_RATIO[1]):
|
||||
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.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:
|
||||
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
|
||||
# 卡号字高一般占卡高 6%~9%;MSER 常把上下花纹并进来,这里收到上限,避免竖条太高
|
||||
half = min(med_h * 0.70, h * 0.050)
|
||||
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))
|
||||
centers.append(yc)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 分组识别
|
||||
def _variant(name: str, crop: np.ndarray) -> Optional[np.ndarray]:
|
||||
if name == "gray":
|
||||
return crop
|
||||
if name == "eq":
|
||||
return cv2.equalizeHist(crop)
|
||||
if name == "clahe":
|
||||
try:
|
||||
return cv2.createCLAHE(3.0, (8, 8)).apply(crop)
|
||||
except Exception: # noqa: BLE001
|
||||
return cv2.equalizeHist(crop)
|
||||
if name == "grad":
|
||||
gx = np.abs(cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3))
|
||||
gy = np.abs(cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3))
|
||||
return cv2.normalize(cv2.magnitude(gx, gy), None, 0, 255,
|
||||
cv2.NORM_MINMAX).astype(np.uint8)
|
||||
if name == "morph":
|
||||
big = cv2.resize(crop, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
|
||||
return cv2.morphologyEx(big, cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8))
|
||||
return None
|
||||
|
||||
|
||||
def _read_crop(gray: np.ndarray, rect: Tuple[int, int, int, int],
|
||||
variants: Sequence[str]) -> Dict[str, str]:
|
||||
h, w = gray.shape[:2]
|
||||
x1, y1, x2, y2 = rect
|
||||
x1, y1 = max(0, x1), max(0, y1)
|
||||
x2, y2 = min(w, x2), min(h, y2)
|
||||
if x2 - x1 < 20 or y2 - y1 < 20:
|
||||
return {}
|
||||
crop = gray[y1:y2, x1:x2]
|
||||
reads: Dict[str, str] = {}
|
||||
for name in variants:
|
||||
img = _variant(name, crop)
|
||||
if img is not None:
|
||||
reads[name], _ = digitize(text_line(img))
|
||||
return reads
|
||||
|
||||
|
||||
def _vote(reads: Dict[str, str]) -> Tuple[str, List[Dict[str, int]]]:
|
||||
"""逐位投票:只采纳「正好 4 位」的识别结果。"""
|
||||
good = [v for v in reads.values() if len(v) == 4]
|
||||
votes: List[Dict[str, int]] = [{} for _ in range(4)]
|
||||
for s in good:
|
||||
for i, ch in enumerate(s):
|
||||
votes[i][ch] = votes[i].get(ch, 0) + 1
|
||||
digits = "".join(
|
||||
max(v.items(), key=lambda kv: (kv[1], kv[0]))[0] if v else "0" for v in votes)
|
||||
return digits, votes
|
||||
|
||||
|
||||
def _pick_group(gray: np.ndarray, xa: int, xb: int, y1: int, y2: int) -> GroupRead:
|
||||
"""在 [xa, xb] 附近微调窗口位置,选出「最像一组 4 位数字」的窗口。"""
|
||||
gw = max(60, xb - xa)
|
||||
best_score, best_ratio, best_rect = -1e9, 0.0, (xa, y1, xb, y2)
|
||||
# 先试基线窗口:形态学梯度能读出 4 位就直接用(多数分组都命中,省一轮扫描)
|
||||
if len(_read_crop(gray, best_rect, ("morph",)).get("morph", "")) == 4:
|
||||
g = GroupRead(rect=best_rect, offset=0.0)
|
||||
g.reads = _read_crop(gray, g.rect, _VARIANTS)
|
||||
g.digits, g.votes = _vote(g.reads)
|
||||
return g
|
||||
for k, ratio in enumerate(_OFFSETS):
|
||||
d = int(round(gw * ratio))
|
||||
rect = (xa + d, y1, xb + d, y2)
|
||||
probe = _read_crop(gray, rect, _PROBE)
|
||||
exact = sum(1 for v in probe.values() if len(v) == 4)
|
||||
score = 2.0 * exact - 0.3 * abs(k)
|
||||
if score > best_score:
|
||||
best_score, best_ratio, best_rect = score, ratio, rect
|
||||
if exact >= 2: # 两路都稳定读出同一组 4 位,不用再试别的偏移
|
||||
break
|
||||
g = GroupRead(rect=best_rect, offset=best_ratio)
|
||||
g.reads = _read_crop(gray, g.rect, _VARIANTS)
|
||||
g.digits, g.votes = _vote(g.reads)
|
||||
return g
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 规则裁决
|
||||
def _search(groups: Sequence[GroupRead], face_bank: str,
|
||||
budget: int) -> Dict[str, Tuple[int, int]]:
|
||||
"""在「改动代价 ≤ budget」的范围内搜出所有通过 Luhn 的号码。
|
||||
|
||||
代价递增搜索:投票串本身合法(代价 0)或只需改 1~2 位时,解空间很小;
|
||||
不用 itertools.product 全量展开(歧义位多时是 8^16,必然被截断漏解)。
|
||||
"""
|
||||
opts: List[List[Tuple[str, int, int]]] = []
|
||||
for g in groups:
|
||||
for i in range(4):
|
||||
opts.append(g.options(i))
|
||||
n = len(opts)
|
||||
found: Dict[str, Tuple[int, int]] = {}
|
||||
nodes = 0
|
||||
digits: List[str] = []
|
||||
|
||||
def dfs(pos: int, cost: int, votes: int) -> None:
|
||||
nonlocal nodes
|
||||
if nodes >= _MAX_NODES:
|
||||
return
|
||||
nodes += 1
|
||||
if pos == n:
|
||||
num = "".join(digits)
|
||||
if len(num) not in (16, 18, 19) or not prefix_ok(num) or not luhn_ok(num):
|
||||
return
|
||||
bank = bin_bank(num)
|
||||
if face_bank and bank and bank != face_bank:
|
||||
return
|
||||
prev = found.get(num)
|
||||
if prev is None or (cost, -votes) < (prev[0], -prev[1]):
|
||||
found[num] = (cost, votes)
|
||||
return
|
||||
for d, c, v in opts[pos]:
|
||||
if cost + c > budget:
|
||||
continue
|
||||
digits.append(d)
|
||||
dfs(pos + 1, cost + c, votes + v)
|
||||
digits.pop()
|
||||
|
||||
dfs(0, 0, 0)
|
||||
return found
|
||||
|
||||
|
||||
def _resolve(groups: Sequence[GroupRead], face_text: str = "") -> NumberReading:
|
||||
"""投票结果 → Luhn 裁决 → 排序候选。"""
|
||||
res = NumberReading()
|
||||
res.groups = list(groups)
|
||||
voted = "".join(g.digits for g in groups)
|
||||
res.number = voted
|
||||
res.length = len(voted)
|
||||
face_bank = _bank_from_text(face_text)
|
||||
|
||||
found: Dict[str, Tuple[int, int]] = {}
|
||||
for budget in range(1, _MAX_COST + 1):
|
||||
found = _search(groups, face_bank, budget)
|
||||
if found or budget >= 3:
|
||||
break
|
||||
|
||||
ranked = sorted(found.items(), key=lambda kv: (kv[1][0], -kv[1][1], kv[0]))
|
||||
res.candidates = [{"number": n, "luhn_ok": True, "length": len(n),
|
||||
"bank": bin_bank(n), "cost": c, "votes": v}
|
||||
for n, (c, v) in ranked[:_MAX_CANDIDATES]]
|
||||
if not res.candidates:
|
||||
res.number = "" # 没有通过校验的解:不返回可疑号码,交由人工
|
||||
res.status, res.confidence = "failed", "low"
|
||||
return res
|
||||
|
||||
top_num, (top_cost, _) = ranked[0]
|
||||
res.number = top_num
|
||||
res.length = len(top_num)
|
||||
res.luhn_ok = True
|
||||
res.bank = bin_bank(top_num) or face_bank
|
||||
# 投票串本身就合法 → 高置信;靠易混枚举纠回来 → 中/低置信(建议人工复核)
|
||||
if voted == top_num and top_cost == 0:
|
||||
res.status, res.confidence = "ok", "high"
|
||||
elif top_cost <= 1:
|
||||
res.status, res.confidence = "candidate", "medium"
|
||||
else:
|
||||
res.status, res.confidence = "candidate", "low"
|
||||
return res
|
||||
|
||||
|
||||
def _bank_from_text(text: str) -> str:
|
||||
from .bankcard import _bank_from_face # noqa: PLC0415 避免循环引用
|
||||
|
||||
return _bank_from_face(text) if text else ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 对外接口
|
||||
def _band_probe(gray: np.ndarray, band: Tuple[int, int, int, int]) -> int:
|
||||
"""便宜地试读一条带子:只跑 morph 一路,数「正好 4 位」的分组个数。"""
|
||||
_, y1, _, y2 = band
|
||||
h, w = gray.shape[:2]
|
||||
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):
|
||||
rect = (int(round(xa + gw * i)), y1, int(round(xa + gw * (i + 1))), y2)
|
||||
v = _read_crop(gray, rect, ("morph",)).get("morph", "")
|
||||
if len(v) == 4:
|
||||
good += 1
|
||||
return good
|
||||
|
||||
|
||||
def _quality(groups: Sequence[GroupRead]) -> int:
|
||||
"""分组读得干不干净:4 位命中次数 + 每位最高票数(用于在多个跨度假设间选优)。"""
|
||||
q = 0
|
||||
for g in groups:
|
||||
q += 2 * sum(1 for v in g.reads.values() if len(v) == 4)
|
||||
q += sum(max(v.values()) for v in g.votes if v)
|
||||
return q
|
||||
|
||||
|
||||
def read_bank_card_number(image, face_text: str = "") -> NumberReading:
|
||||
"""识别一张卡图上的卡号(浮雕/反光卡兜底用)。
|
||||
|
||||
Args:
|
||||
image: 图片路径,或已读入的 BGR/灰度 ndarray(建议传入已摆正/透视矫正的卡图)。
|
||||
face_text: 卡面 OCR 文本(含银行名时用于 BIN 交叉校验,如 "招商银行")。
|
||||
|
||||
Returns:
|
||||
NumberReading;`.number` 为最终号码,`.candidates` 为按可信度排序的候选,
|
||||
`.status` 为 ok / candidate / failed。读不准就返回候选并把 status 置为
|
||||
candidate/failed,不硬猜。
|
||||
"""
|
||||
t0 = time.time()
|
||||
gray = to_gray(image) if isinstance(image, np.ndarray) else to_gray(imread(str(image)))
|
||||
res = NumberReading()
|
||||
bands = find_number_bands(gray)
|
||||
if not bands:
|
||||
res.elapsed_s = time.time() - t0
|
||||
return res
|
||||
|
||||
# 用一次便宜试读挑带子:顶部花纹/有效期行通常读不出 4 位
|
||||
scored = [(_band_probe(gray, b), -i, b) for i, b in enumerate(bands)]
|
||||
scored.sort(reverse=True)
|
||||
ordered = [b for s, _, b in scored if s >= 2] or bands
|
||||
|
||||
h, w = gray.shape[:2]
|
||||
best: Optional[NumberReading] = None
|
||||
best_key = (-1, -1, -1, -1)
|
||||
for band in ordered[:2]:
|
||||
_, y1, _, 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:
|
||||
xa, xb = int(w * ra), int(w * rb)
|
||||
gw = (xb - xa) / 4.0
|
||||
groups = [_pick_group(gray, int(round(xa + gw * i)),
|
||||
int(round(xa + gw * (i + 1))), y1, y2)
|
||||
for i in range(4)]
|
||||
cand = _resolve(groups, face_text)
|
||||
cand.band = band
|
||||
cand.elapsed_s = time.time() - t0
|
||||
if cand.status == "ok": # 投票串本身就合法,直接返回
|
||||
return cand
|
||||
q = _quality(groups)
|
||||
key = (q, *_rank(cand))
|
||||
if best is None or key > best_key:
|
||||
best, best_key = cand, key
|
||||
if q >= 12: # 本带已读得很干净,不必再试更窄的跨度
|
||||
break
|
||||
assert best is not None
|
||||
best.elapsed_s = time.time() - t0
|
||||
return best
|
||||
|
||||
|
||||
def _rank(res: NumberReading) -> Tuple[int, int, int]:
|
||||
level = {"high": 3, "medium": 2, "low": 1}.get(res.confidence, 0)
|
||||
min_cost = min([c.get("cost", 9) for c in res.candidates] or [9])
|
||||
return (1 if res.luhn_ok else 0, level, -min_cost)
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份证字段抽取:号码 / 姓名 / 性别 / 民族 / 出生 / 住址。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from .engine import Line, join_text
|
||||
from .validators import (IdCandidate, id_birth, id_candidates, id_checksum_ok,
|
||||
id_gender, id_plausible, id_region, normalize_text)
|
||||
|
||||
ID_KEYWORDS = ("公民身份号码", "身份号码", "姓名", "性别", "民族", "出生", "住址",
|
||||
"签发机关", "有效期限", "中华人民共和国", "居民身份证")
|
||||
|
||||
# 这些词不能当姓名
|
||||
_NOT_NAME = set(ID_KEYWORDS) | {"男", "女", "汉", "回", "苗", "彝", "壮", "藏", "维吾尔",
|
||||
"身份证", "公民", "号码", "地址", "出生日期"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdCardResult:
|
||||
number: str = ""
|
||||
checksum_ok: bool = False
|
||||
birth: str = ""
|
||||
gender: str = ""
|
||||
name: str = ""
|
||||
ethnicity: str = ""
|
||||
address: str = ""
|
||||
issue: str = ""
|
||||
valid_to: str = ""
|
||||
confidence: str = "low" # high / medium / low
|
||||
evidence: List[str] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
found: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"found": self.found,
|
||||
"number": self.number,
|
||||
"checksum_ok": self.checksum_ok,
|
||||
"birth": self.birth,
|
||||
"gender": self.gender,
|
||||
"name": self.name,
|
||||
"ethnicity": self.ethnicity,
|
||||
"address": self.address,
|
||||
"issue": self.issue,
|
||||
"valid_to": self.valid_to,
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"candidates": self.candidates,
|
||||
}
|
||||
|
||||
|
||||
def looks_like_id(text: str) -> bool:
|
||||
hits = sum(1 for k in ID_KEYWORDS if k in text)
|
||||
return hits >= 2 or "公民身份号码" in text or "居民身份证" in text
|
||||
|
||||
|
||||
def _norm_name(s: str) -> str:
|
||||
s = normalize_text(s)
|
||||
s = re.sub(r"^姓名", "", s)
|
||||
s = re.sub(r"[·•.\s]", "", s)
|
||||
return s
|
||||
|
||||
|
||||
# 这些词长得像姓名,绝不能当姓名
|
||||
_BANK_WORDS = ("银行", "银联", "UNIONPAY", "信用卡", "借记卡", "储蓄卡", "一卡通",
|
||||
"有限公司", "保险", "支行", "分行")
|
||||
|
||||
|
||||
def _name_candidate(text: str) -> str:
|
||||
t = _norm_name(text)
|
||||
if not (2 <= len(t) <= 4 and re.fullmatch(r"[一-龥]+", t)):
|
||||
return ""
|
||||
if t in _NOT_NAME or any(w in t.upper() for w in _BANK_WORDS):
|
||||
return ""
|
||||
return t
|
||||
|
||||
|
||||
def _pick_name(lines: Sequence[Line], expected: str, full_text: str) -> str:
|
||||
"""姓名优先用外部给的姓名做交叉验证,其次取「姓名」标签旁边那一段 2~4 字中文。"""
|
||||
if expected:
|
||||
exp = _norm_name(expected)
|
||||
if exp and exp in normalize_text(full_text):
|
||||
return exp
|
||||
# 情况一:OCR 把标签和名字连成一段(「姓名李诗灿」)
|
||||
for ln in lines:
|
||||
m = re.match(r"姓名([一-龥]{2,4})$", normalize_text(ln.text))
|
||||
if m and _name_candidate(m.group(1)):
|
||||
return _name_candidate(m.group(1))
|
||||
# 情况二:标签和名字是两段,取离「姓名」标签最近的那段中文
|
||||
labels = [ln for ln in lines if "姓名" in normalize_text(ln.text)]
|
||||
cands = []
|
||||
for ln in lines:
|
||||
c = _name_candidate(ln.text)
|
||||
if not c:
|
||||
continue
|
||||
for lab in labels:
|
||||
d = abs(ln.y_mid - lab.y_mid) * 2.0 + abs(ln.left - lab.right)
|
||||
cands.append((d, c))
|
||||
if cands:
|
||||
cands.sort(key=lambda x: x[0])
|
||||
return cands[0][1]
|
||||
return ""
|
||||
|
||||
|
||||
def _pick_field(text: str, patterns: Sequence[str]) -> str:
|
||||
for pat in patterns:
|
||||
m = re.search(pat, text)
|
||||
if m:
|
||||
return m.group(1)
|
||||
return ""
|
||||
|
||||
|
||||
def parse(lines: Sequence[Line], expected_name: str = "",
|
||||
full_text: str = "", rows: Optional[Sequence[str]] = None) -> IdCardResult:
|
||||
"""从身份证那一面的 OCR 结果里抽字段。"""
|
||||
res = IdCardResult()
|
||||
text = normalize_text(full_text) if full_text else normalize_text(join_text(lines))
|
||||
if not text:
|
||||
return res
|
||||
|
||||
cands: List[IdCandidate] = id_candidates(rows if rows else text)
|
||||
if not cands:
|
||||
# 逐行再试(号码被拆成两段时)
|
||||
for ln in lines:
|
||||
cands.extend(id_candidates(ln.text))
|
||||
cands = sorted(cands, key=lambda c: -c.score)[:8]
|
||||
|
||||
if cands:
|
||||
top = cands[0]
|
||||
res.candidates = [{"number": c.number, "checksum_ok": c.checksum_ok,
|
||||
"origin": c.origin, "edits": c.edits,
|
||||
"score": round(c.score, 2)} for c in cands]
|
||||
res.number = top.number
|
||||
res.checksum_ok = top.checksum_ok
|
||||
res.birth = id_birth(top.number)
|
||||
res.gender = id_gender(top.number)
|
||||
res.found = True
|
||||
if top.origin == "repaired":
|
||||
res.evidence.append(f"号码经 {top.edits} 位纠错后通过校验码(原始识别有误)")
|
||||
|
||||
# 与 OCR 文字里的「出生 / 性别」交叉核对,不一致时优先相信 OCR 文字并打标注
|
||||
birth_txt = _pick_field(text, (r"出生(\d{4}年\d{1,2}月\d{1,2}日)",
|
||||
r"出生(\d{4}[.\-/]\d{1,2}[.\-/]\d{1,2})"))
|
||||
if birth_txt:
|
||||
res.evidence.append(f"卡面出生:{birth_txt}")
|
||||
|
||||
gender_txt = ""
|
||||
m = re.search(r"性别[男女]", text) or re.search(r"(男|女)", text)
|
||||
if m:
|
||||
gender_txt = "女" if "女" in m.group(0) else "男"
|
||||
if gender_txt:
|
||||
res.evidence.append(f"卡面性别:{gender_txt}")
|
||||
if res.gender and res.gender != gender_txt:
|
||||
res.evidence.append(f"⚠ 号码推导性别({res.gender})与卡面({gender_txt})不一致")
|
||||
|
||||
eth = _pick_field(text, (r"民族([\u4e00-\u9fa5]{1,4}?)(?=出生|性别|姓名|住址|公|$)",))
|
||||
res.ethnicity = eth
|
||||
|
||||
res.name = _pick_name(lines, expected_name, text)
|
||||
|
||||
# 住址:从「住址」开始到号码/签发机关之前
|
||||
m = re.search(r"住址(.+?)(公民身份号码|签发机关|有效期限|$)", text)
|
||||
addr = m.group(1) if m else ""
|
||||
res.address = re.sub(r"[。,,]", "", addr)[:60]
|
||||
|
||||
res.issue = _pick_field(text, (r"签发机关([^有效]+?)(?:有效|$)",))
|
||||
vt = re.search(r"有效期限?(\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?(?:[-—~至]\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?|长期))", text)
|
||||
res.valid_to = vt.group(1) if vt else ""
|
||||
|
||||
# 置信度
|
||||
high = res.checksum_ok and bool(res.name) and bool(res.birth)
|
||||
if (expected_name and res.name and _norm_name(res.name) != _norm_name(expected_name)):
|
||||
high = False
|
||||
res.evidence.append(f"⚠ 姓名({res.name})与表格姓名({expected_name})不一致")
|
||||
if not res.checksum_ok:
|
||||
res.confidence = "low" if not cands else "medium"
|
||||
elif high and (top.origin == "raw" if cands else False):
|
||||
res.confidence = "high"
|
||||
else:
|
||||
res.confidence = "medium"
|
||||
if res.birth and not id_plausible(res.number or ""):
|
||||
res.evidence.append("⚠ 号码生日不合法")
|
||||
return res
|
||||
@@ -0,0 +1,174 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""图像基础操作:中文路径读取、缩放、增强、旋转、透视矫正。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 身份证 / 银行卡物理尺寸 85.6 x 54 mm,长宽比 ≈ 1.585
|
||||
CARD_ASPECT = 85.6 / 54.0
|
||||
|
||||
|
||||
def imread(path: str) -> np.ndarray:
|
||||
"""读取图片(支持中文路径 / 空格,cv2.imread 在 Windows 下会失败)。"""
|
||||
p = str(path)
|
||||
if not os.path.isfile(p):
|
||||
raise FileNotFoundError(f"图片不存在:{p}")
|
||||
data = np.fromfile(p, dtype=np.uint8)
|
||||
if data.size == 0:
|
||||
raise ValueError(f"图片为空:{p}")
|
||||
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
||||
if img is None:
|
||||
# 部分手机的 JPEG(CMYK / 特殊 EXIF)cv2 解不出,退 Pillow
|
||||
from PIL import Image, ImageOps # noqa: PLC0415
|
||||
|
||||
with Image.open(p) as im:
|
||||
im = ImageOps.exif_transpose(im).convert("RGB")
|
||||
img = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
|
||||
return img
|
||||
|
||||
|
||||
def apply_exif(img: np.ndarray, path: str) -> np.ndarray:
|
||||
"""按 EXIF Orientation 摆正(手机竖拍常带 90/180/270 标记)。"""
|
||||
try:
|
||||
from PIL import Image, ImageOps # noqa: PLC0415
|
||||
|
||||
with Image.open(path) as im:
|
||||
exif = im.getexif()
|
||||
o = int(exif.get(274, 1) or 1)
|
||||
if o in (1, 0):
|
||||
return img
|
||||
im2 = ImageOps.exif_transpose(im).convert("RGB")
|
||||
return cv2.cvtColor(np.array(im2), cv2.COLOR_RGB2BGR)
|
||||
except Exception: # noqa: BLE001 EXIF 不可用不算错
|
||||
return img
|
||||
|
||||
|
||||
def resize_side(img: np.ndarray, max_side: int = 0, min_side: int = 0) -> np.ndarray:
|
||||
"""按长边上限缩小 / 短边下限放大(等比)。"""
|
||||
h, w = img.shape[:2]
|
||||
scale = 1.0
|
||||
if max_side and max(h, w) > max_side:
|
||||
scale = max_side / float(max(h, w))
|
||||
elif min_side and min(h, w) < min_side:
|
||||
scale = min_side / float(min(h, w))
|
||||
if abs(scale - 1.0) < 1e-3:
|
||||
return img
|
||||
interp = cv2.INTER_AREA if scale < 1 else cv2.INTER_CUBIC
|
||||
return cv2.resize(img, (max(1, int(round(w * scale))), max(1, int(round(h * scale)))),
|
||||
interpolation=interp)
|
||||
|
||||
|
||||
def to_gray(img: np.ndarray) -> np.ndarray:
|
||||
if img.ndim == 2:
|
||||
return img
|
||||
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
|
||||
def rotate90(img: np.ndarray, k: int) -> np.ndarray:
|
||||
"""逆时针旋转 k*90 度。"""
|
||||
return np.ascontiguousarray(np.rot90(img, k % 4))
|
||||
|
||||
|
||||
def gray_variants(gray: np.ndarray, upscale: float = 1.0) -> List[Tuple[str, np.ndarray]]:
|
||||
"""生成多路灰度增强图(浮雕卡号、反光、低对比度各有用),供多遍 OCR 投票。"""
|
||||
g = gray
|
||||
if upscale > 1.0:
|
||||
g = cv2.resize(g, None, fx=upscale, fy=upscale, interpolation=cv2.INTER_CUBIC)
|
||||
out: List[Tuple[str, np.ndarray]] = [("gray", g)]
|
||||
try:
|
||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(g)
|
||||
out.append(("clahe", clahe))
|
||||
except Exception: # noqa: BLE001
|
||||
clahe = g
|
||||
# 反光/低对比:白顶帽 + 黑底帽 强调字迹
|
||||
k = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 5))
|
||||
try:
|
||||
tophat = cv2.morphologyEx(g, cv2.MORPH_TOPHAT, k)
|
||||
blackhat = cv2.morphologyEx(g, cv2.MORPH_BLACKHAT, k)
|
||||
out.append(("tophat", cv2.normalize(tophat, None, 0, 255, cv2.NORM_MINMAX)))
|
||||
out.append(("blackhat", cv2.normalize(blackhat, None, 0, 255, cv2.NORM_MINMAX)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 二值化(Otsu / 自适应),深色卡面反相后号码变白底黑字
|
||||
try:
|
||||
_, otsu = cv2.threshold(g, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
||||
out.append(("otsu", otsu))
|
||||
out.append(("otsu_inv", cv2.bitwise_not(otsu)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
adap = cv2.adaptiveThreshold(g, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, 31, 9)
|
||||
out.append(("adaptive", adap))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 锐化(浮雕数字边缘)
|
||||
try:
|
||||
blur = cv2.GaussianBlur(g, (0, 0), 1.2)
|
||||
out.append(("sharp", cv2.addWeighted(g, 1.6, blur, -0.6, 0)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def order_points(pts: Sequence[Sequence[float]]) -> np.ndarray:
|
||||
"""四个点按 左上/右上/右下/左下 排序。"""
|
||||
pts = np.asarray(pts, dtype=np.float32).reshape(4, 2)
|
||||
s = pts.sum(axis=1)
|
||||
d = np.diff(pts, axis=1).reshape(-1)
|
||||
out = np.zeros((4, 2), dtype=np.float32)
|
||||
out[0] = pts[np.argmin(s)]
|
||||
out[2] = pts[np.argmax(s)]
|
||||
out[1] = pts[np.argmin(d)]
|
||||
out[3] = pts[np.argmax(d)]
|
||||
return out
|
||||
|
||||
|
||||
def four_point_warp(img: np.ndarray, pts: Sequence[Sequence[float]],
|
||||
width: int = 0, height: int = 0) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""把四边形透视矫正成矩形(宽度默认按目标长宽比 1.585 推算)。"""
|
||||
src = order_points(pts)
|
||||
tl, tr, br, bl = src
|
||||
w_top = float(np.linalg.norm(tr - tl))
|
||||
w_bot = float(np.linalg.norm(br - bl))
|
||||
h_lef = float(np.linalg.norm(bl - tl))
|
||||
h_rig = float(np.linalg.norm(br - tr))
|
||||
w = (w_top + w_bot) / 2.0
|
||||
h = (h_lef + h_rig) / 2.0
|
||||
if width and height:
|
||||
w, h = float(width), float(height)
|
||||
elif width:
|
||||
h = width / CARD_ASPECT
|
||||
elif height:
|
||||
w = height * CARD_ASPECT
|
||||
elif w > 0 and h > 0:
|
||||
# 拉正成标准卡比例,避免斜拍把字压扁
|
||||
if w / h > CARD_ASPECT * 1.12:
|
||||
h = w / CARD_ASPECT
|
||||
elif h / w > 1.0 / CARD_ASPECT * 1.12:
|
||||
w = h * CARD_ASPECT
|
||||
dst = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], dtype=np.float32)
|
||||
m = cv2.getPerspectiveTransform(src, dst)
|
||||
out = cv2.warpPerspective(img, m, (max(1, int(round(w))), max(1, int(round(h)))),
|
||||
flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
|
||||
return out, m
|
||||
|
||||
|
||||
def quad_area(pts: np.ndarray) -> float:
|
||||
return float(abs(cv2.contourArea(np.asarray(pts, dtype=np.float32).reshape(-1, 1, 2))))
|
||||
|
||||
|
||||
def iou_rect(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
|
||||
ax, ay, aw, ah = a
|
||||
bx, by, bw, bh = b
|
||||
x1, y1 = max(ax, bx), max(ay, by)
|
||||
x2, y2 = min(ax + aw, bx + bw), min(ay + ah, by + bh)
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return 0.0
|
||||
inter = (x2 - x1) * (y2 - y1)
|
||||
union = aw * ah + bw * bh - inter
|
||||
return inter / float(union) if union > 0 else 0.0
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命中分析:拿「已知正确号码」去比对识别结果,回答「这张照片能不能证明是这张卡」。
|
||||
|
||||
识别精确率是 100%(认出来的都对),但召回受照片质量限制(有的卡号只读到一半)。
|
||||
和业务上已有的工资卡数据比对时,不需要「完整读出」才有价值——读到前缀 + 后缀、
|
||||
或者除 1 位外全对,就已经能判定「照片与登记号码一致」。
|
||||
|
||||
状态定义:
|
||||
exact 完整命中(识别结果逐位一致)
|
||||
strong 高度一致(≥85% 位命中,通常只差 1 位且是 Luhn 歧义)
|
||||
partial 部分命中(30%~85% 位命中,能看到前缀/后缀)
|
||||
weak 基本读不出(<30%)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
from typing import Dict, Iterable, List, Sequence, Tuple
|
||||
|
||||
from .validators import PRIMARY, bin_bank, normalize_text
|
||||
|
||||
EXACT, STRONG, PARTIAL, WEAK = "exact", "strong", "partial", "weak"
|
||||
LABEL = {EXACT: "一致", STRONG: "高度疑似", PARTIAL: "部分命中", WEAK: "读不出"}
|
||||
|
||||
|
||||
def digits(text: str) -> str:
|
||||
s = normalize_text(text)
|
||||
return "".join(ch if ch.isdigit() else PRIMARY.get(ch, "") for ch in s)
|
||||
|
||||
|
||||
def _keep(run: str, exp: str, card_mode: bool, id_digits: str) -> bool:
|
||||
"""只有「像卡号片段」的游程才参与卡号比对,否则身份证号/日期会把命中率抬虚。"""
|
||||
if len(run) < 8:
|
||||
return False
|
||||
if not card_mode:
|
||||
return True
|
||||
if id_digits and (run == id_digits or id_digits in run or run in id_digits):
|
||||
return False
|
||||
return run.startswith("62") or bool(bin_bank(run)) or run in exp or exp.find(run) >= 0
|
||||
|
||||
|
||||
def coverage(expected: str, runs: Iterable[str], card_mode: bool = True,
|
||||
id_digits: str = "") -> Tuple[float, str, str]:
|
||||
"""返回 (命中率 0~1, 状态, 命中最多的片段)。"""
|
||||
exp = digits(expected)
|
||||
if not exp:
|
||||
return 0.0, WEAK, ""
|
||||
best_cov, best_run, best_status = 0.0, "", WEAK
|
||||
for raw in runs:
|
||||
run = digits(raw)
|
||||
if not _keep(run, exp, card_mode, id_digits):
|
||||
continue
|
||||
if run == exp:
|
||||
return 1.0, EXACT, run
|
||||
covered: set[int] = set()
|
||||
pos = 0
|
||||
while True:
|
||||
i = exp.find(run, pos)
|
||||
if i < 0:
|
||||
break
|
||||
covered.update(range(i, i + len(run)))
|
||||
pos = i + 1
|
||||
pos_cov = len(covered) / len(exp) if covered else 0.0
|
||||
# 只有够长的片段才用模糊相似度,避免 8~10 位噪声凑出虚高命中率
|
||||
ratio = difflib.SequenceMatcher(None, exp, run, autojunk=False).ratio() \
|
||||
if len(run) >= 14 else 0.0
|
||||
cov = max(pos_cov, ratio)
|
||||
if cov > best_cov:
|
||||
best_cov, best_run = cov, run
|
||||
best_status = STRONG if cov >= 0.85 else (PARTIAL if cov >= 0.30 else WEAK)
|
||||
return best_cov, best_status, best_run
|
||||
|
||||
|
||||
def _runs_of(person: dict) -> List[str]:
|
||||
out: List[str] = []
|
||||
for r in (person.get("raw") or []):
|
||||
out.extend(r.get("digit_runs") or [])
|
||||
return out
|
||||
|
||||
|
||||
def check_person(person: dict, truth: Dict[str, str]) -> dict:
|
||||
"""比对一个人的识别结果和人工填写的正确值。"""
|
||||
idc = person.get("id_card") or {}
|
||||
bk = person.get("bank_card") or {}
|
||||
runs = _runs_of(person)
|
||||
|
||||
t_id = digits(truth.get("id") or "")
|
||||
t_card = digits(truth.get("card") or "")
|
||||
t_name = (truth.get("name") or "").strip()
|
||||
|
||||
got_id = digits(idc.get("number") or "")
|
||||
if t_id:
|
||||
if got_id == t_id:
|
||||
id_status, id_cov = EXACT, 1.0
|
||||
else:
|
||||
id_cov, id_status, _ = coverage(t_id, runs, card_mode=False)
|
||||
else:
|
||||
id_status, id_cov = WEAK, 0.0
|
||||
|
||||
if t_card:
|
||||
if digits(bk.get("number") or "") == t_card:
|
||||
card_status, card_cov = EXACT, 1.0
|
||||
else:
|
||||
card_cov, card_status, _ = coverage(t_card, runs, card_mode=True,
|
||||
id_digits=got_id or t_id)
|
||||
else:
|
||||
card_cov, card_status = 0.0, WEAK
|
||||
|
||||
got_name = (idc.get("name") or "").strip()
|
||||
if t_name:
|
||||
name_status = EXACT if got_name == t_name else (PARTIAL if not got_name else WEAK)
|
||||
else:
|
||||
name_status = WEAK
|
||||
|
||||
return {
|
||||
"folder": person.get("folder", ""),
|
||||
"truth_name": t_name,
|
||||
"id_recognized": got_id or "",
|
||||
"id_status": id_status,
|
||||
"id_coverage": round(id_cov, 3),
|
||||
"card_recognized": digits(bk.get("number") or ""),
|
||||
"card_status": card_status,
|
||||
"card_coverage": round(card_cov, 3),
|
||||
"name_recognized": got_name,
|
||||
"name_status": name_status,
|
||||
"runs": runs[:12],
|
||||
}
|
||||
|
||||
|
||||
def check_persons(persons: Sequence[dict], truth_map: Dict[str, Dict[str, str]]) -> List[dict]:
|
||||
rows = []
|
||||
for p in persons:
|
||||
t = truth_map.get(p.get("folder", "")) or {}
|
||||
if not t:
|
||||
continue
|
||||
rows.append(check_person(p, t))
|
||||
return rows
|
||||
|
||||
|
||||
def print_report(rows: Sequence[dict]) -> str:
|
||||
lines = [f"{'姓名':<9}{'身份证识别':<20}{'状态':<9}{'卡号识别':<20}{'卡号状态':<9}"
|
||||
f"{'命中率':<8}姓名"]
|
||||
lines.append("-" * 100)
|
||||
for r in rows:
|
||||
lines.append(
|
||||
f"{r['folder']:<9}"
|
||||
f"{(r['id_recognized'] or '-'):<20}"
|
||||
f"{LABEL.get(r['id_status'], r['id_status']):<9}"
|
||||
f"{(r['card_recognized'] or '-'):<20}"
|
||||
f"{LABEL.get(r['card_status'], r['card_status']):<9}"
|
||||
f"{r['card_coverage']:<8.2f}"
|
||||
f"{'一致' if r['name_status'] == EXACT else ('未识别' if not r['name_recognized'] else '不一致')}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,640 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""识别流水线:粗识别 → 方向补测 → 文字块精修 → 字段抽取 → 交叉校验。
|
||||
|
||||
为什么不直接「一步 OCR 全图」:手机拍的照片边长动辄 4000~5700 像素,
|
||||
PP-OCR 的检测网络会先把整图缩到 ~1600,卡面上的小字(尤其浮雕卡号)就直接糊了。
|
||||
所以这里做两级:先小图定位文字块(快),再把原图上对应的块按原分辨率切出来精识别
|
||||
(准),卡号读不出来时再对数字带做多路增强 + 多遍投票,最后用校验位把错字纠回来。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from . import bankcard, idcard
|
||||
from .cards import find_cards
|
||||
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,
|
||||
normalize_text)
|
||||
|
||||
logger = logging.getLogger("cardocr")
|
||||
|
||||
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"}
|
||||
|
||||
# 粗识别缩图边长:太小丢小字,太大慢且和精修重复
|
||||
_COARSE_SIDE = 1440
|
||||
# 精修块最长边
|
||||
_FINE_SIDE = 2200
|
||||
# 数字带目标字高
|
||||
_STRIP_H = 120
|
||||
# 数字带做增强的通道(越多越准;跳过检测网络后单路只要 0.1~0.3s)
|
||||
_STRIP_VARIANT_NAMES = ("gray", "blackhat", "otsu_inv", "sharp", "tophat")
|
||||
|
||||
|
||||
|
||||
@dataclass
|
||||
class View:
|
||||
"""一次 OCR 的输入区域(整图粗识别 / 精修块 / 卡片矫正图)。"""
|
||||
|
||||
name: str
|
||||
image: np.ndarray
|
||||
source: str # coarse / fine / strip / quad
|
||||
rect: Tuple[int, int, int, int]
|
||||
lines: List[Line] = field(default_factory=list)
|
||||
text: str = ""
|
||||
kind: str = "unknown" # id / bank / both / unknown
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"name": self.name, "source": self.source, "rect": list(self.rect),
|
||||
"size": [int(self.image.shape[1]), int(self.image.shape[0])],
|
||||
"kind": self.kind, "lines": len(self.lines), "text": self.text[:180]}
|
||||
|
||||
|
||||
def classify(text: str) -> str:
|
||||
if not text.strip():
|
||||
return "unknown"
|
||||
is_id = idcard.looks_like_id(text)
|
||||
is_bank = bankcard.looks_like_bank_card(text)
|
||||
if is_id and is_bank:
|
||||
return "both"
|
||||
if is_id:
|
||||
return "id"
|
||||
if is_bank:
|
||||
return "bank"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _digitish(text: str) -> int:
|
||||
return sum(1 for ch in text if ch.isdigit() or ch in _CONFUSABLE)
|
||||
|
||||
|
||||
def number_runs(text: str, min_len: int = 6) -> List[str]:
|
||||
"""从一段文本里抽数字串(易混字母按首选映射还原),用于人工核对时的「命中分析」。"""
|
||||
s = normalize_text(text)
|
||||
norm = "".join(ch if ch.isdigit() else PRIMARY.get(ch, " ") for ch in s)
|
||||
runs: List[str] = []
|
||||
cur = []
|
||||
for ch in norm:
|
||||
if ch.isdigit():
|
||||
cur.append(ch)
|
||||
else:
|
||||
if len(cur) >= min_len:
|
||||
runs.append("".join(cur))
|
||||
cur = []
|
||||
if len(cur) >= min_len:
|
||||
runs.append("".join(cur))
|
||||
return runs
|
||||
|
||||
|
||||
def _looks_rotated(lines: Sequence[Line]) -> bool:
|
||||
"""文字框普遍「高 > 宽」→ 照片被拍成横的,值得转 90/270 度补测。"""
|
||||
if not lines:
|
||||
return True
|
||||
tall = sum(1 for x in lines if x.height > 1.6 * x.width)
|
||||
return tall >= max(2, len(lines) * 0.3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 文字块
|
||||
def group_blocks(lines: Sequence[Line], max_blocks: int = 12) -> List[List[Line]]:
|
||||
"""把同一张卡上的文字行聚成块(按竖直间距 + 水平重叠)。"""
|
||||
if not lines:
|
||||
return []
|
||||
items = sorted(lines, key=lambda x: (x.top, x.left))
|
||||
med_h = float(np.median([x.height for x in items])) if items else 0.0
|
||||
blocks: List[List[Line]] = []
|
||||
cur = [items[0]]
|
||||
for ln in items[1:]:
|
||||
prev = cur[-1]
|
||||
vgap = ln.top - prev.bottom
|
||||
overlap = min(ln.right, prev.right) - max(ln.left, prev.left)
|
||||
same_row = overlap > 0.15 * min(ln.width, prev.width) and \
|
||||
abs(ln.y_mid - prev.y_mid) < 0.6 * max(ln.height, prev.height)
|
||||
if vgap <= max(10.0, med_h * 1.2) or same_row or vgap < 0:
|
||||
cur.append(ln)
|
||||
else:
|
||||
blocks.append(cur)
|
||||
cur = [ln]
|
||||
blocks.append(cur)
|
||||
blocks.sort(key=lambda b: -len(b))
|
||||
return blocks[:max_blocks]
|
||||
|
||||
|
||||
def _bbox(lines: Sequence[Line], pad_x: float, pad_y: float,
|
||||
bounds: Tuple[int, int]) -> Tuple[int, int, int, int]:
|
||||
x1 = min(x.left for x in lines)
|
||||
y1 = min(x.top for x in lines)
|
||||
x2 = max(x.right for x in lines)
|
||||
y2 = max(x.bottom for x in lines)
|
||||
px = int((x2 - x1) * pad_x) + 8
|
||||
py = int((y2 - y1) * pad_y) + 8
|
||||
w, h = bounds
|
||||
return max(0, x1 - px), max(0, y1 - py), min(w, x2 + px), min(h, y2 + py)
|
||||
|
||||
|
||||
def _fit(img: np.ndarray, max_side: int = _FINE_SIDE, min_h: int = 0) -> np.ndarray:
|
||||
out = img
|
||||
if max(out.shape[:2]) > max_side:
|
||||
out = resize_side(out, max_side=max_side)
|
||||
if min_h and min(out.shape[:2]) < min_h:
|
||||
out = resize_side(out, min_side=min_h)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 精修
|
||||
def _fine_views(img: np.ndarray, coarse: View,
|
||||
budget: int = 3) -> List[View]:
|
||||
"""从粗识别文字块里挑出信息最密的若干块,回原图按原生分辨率切开精识别。"""
|
||||
blocks = group_blocks(coarse.lines)
|
||||
picked: List[Tuple[float, List[Line]]] = []
|
||||
for b in blocks:
|
||||
t = join_text(b)
|
||||
s = 0.0
|
||||
if idcard.looks_like_id(t):
|
||||
s += 3.0
|
||||
if bankcard.looks_like_bank_card(t):
|
||||
s += 2.5
|
||||
d = _digitish(t)
|
||||
if d >= 8:
|
||||
s += 2.0
|
||||
elif d >= 6:
|
||||
s += 1.0
|
||||
if len(b) >= 2:
|
||||
s += 0.5
|
||||
if s > 0:
|
||||
picked.append((s, b))
|
||||
picked.sort(key=lambda x: -x[0])
|
||||
h, w = img.shape[:2]
|
||||
# 粗识别是在缩图(≤1440)上做的,坐标要按比例放大回原图
|
||||
scale = w / float(coarse.image.shape[1])
|
||||
out: List[View] = []
|
||||
for s, b in picked[:budget]:
|
||||
x1, y1, x2, y2 = _bbox(b, 0.18, 0.55, (w, h))
|
||||
x1, y1 = int(x1 * scale), int(y1 * scale)
|
||||
x2, y2 = min(w, int(x2 * scale)), min(h, int(y2 * scale))
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
continue
|
||||
crop = img[y1:y2, x1:x2]
|
||||
if crop.size == 0:
|
||||
continue
|
||||
# 与已有精修块大面积重叠则跳过(同一张卡被拆成多块时会重复)
|
||||
if any(_iou_rect((x1, y1, x2 - x1, y2 - y1), v.rect) > 0.55 for v in out):
|
||||
continue
|
||||
crop = _fit(crop)
|
||||
out.append(View(name=f"fine{len(out) + 1}", image=crop, source="fine",
|
||||
rect=(x1, y1, x2 - x1, y2 - y1)))
|
||||
return out
|
||||
|
||||
|
||||
def _iou_rect(a, b) -> float:
|
||||
ax, ay, aw, ah = a
|
||||
bx, by, bw, bh = b
|
||||
x1, y1 = max(ax, bx), max(ay, by)
|
||||
x2, y2 = min(ax + aw, bx + bw), min(ay + ah, by + bh)
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return 0.0
|
||||
inter = (x2 - x1) * (y2 - y1)
|
||||
return inter / float(aw * ah + bw * bh - inter)
|
||||
|
||||
|
||||
def _strip_variants(view: View, lines: Sequence[Line], want: int = 2):
|
||||
"""对数字行做多路增强识别,逐路 yield 行文本(调用方可以随时提前收工)。
|
||||
|
||||
窄条图直接用识别网络(跳过检测网络),单路约 0.1~0.3s,可放心多跑几路。
|
||||
"""
|
||||
jobs = [ln for ln in lines if _digitish(ln.text) >= 6 and ln.width >= 100]
|
||||
jobs.sort(key=lambda x: -_digitish(x.text))
|
||||
for ln in jobs[:want]:
|
||||
h, w = view.image.shape[:2]
|
||||
px = max(6, int(ln.height * 0.2))
|
||||
x1, y1 = max(0, ln.left - px), max(0, ln.top - px)
|
||||
x2, y2 = min(w, ln.right + px), min(h, ln.bottom + px)
|
||||
crop = _fit(view.image[y1:y2, x1:x2], max_side=1600, min_h=96)
|
||||
if crop.size == 0:
|
||||
continue
|
||||
gray = to_gray(crop)
|
||||
for name, var in gray_variants(gray, upscale=1.0):
|
||||
if name in _STRIP_VARIANT_NAMES:
|
||||
text = text_line(var)
|
||||
if text:
|
||||
yield [text]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 主流程
|
||||
def analyze_image(path: str, expected_name: str = "",
|
||||
mark_dir: Optional[str] = None,
|
||||
extra_passes: bool = True,
|
||||
fast: bool = False) -> dict:
|
||||
"""识别单张照片,返回结构化结果。
|
||||
|
||||
Args:
|
||||
path: 图片路径(支持中文 / 空格)。
|
||||
expected_name: 表格或文件夹里的姓名,用来校验身份证上的姓名。
|
||||
mark_dir: 若给目录,把命中区域的标注图存下去方便人工复核。
|
||||
extra_passes: 卡号/身份证号没读准时,是否追加多遍增强识别。
|
||||
fast: 只跑粗识别(快,但精度下降)。
|
||||
"""
|
||||
t0 = time.time()
|
||||
p = Path(path)
|
||||
img = imread(str(p))
|
||||
img = apply_exif(img, str(p))
|
||||
H, W = img.shape[:2]
|
||||
views: List[View] = []
|
||||
|
||||
def add_view(v: View) -> None:
|
||||
v.lines = ocr_lines(v.image)
|
||||
v.text = join_text(v.lines)
|
||||
v.kind = classify(v.text)
|
||||
views.append(v)
|
||||
|
||||
# ---- 1) 粗识别(原方向;缩略图先放大,否则小字根本没有像素)
|
||||
coarse_src = img if max(H, W) >= 1000 else resize_side(img, min_side=1000)
|
||||
coarse_img = resize_side(coarse_src, max_side=_COARSE_SIDE)
|
||||
coarse = View(name="coarse", image=coarse_img, source="coarse", rect=(0, 0, W, H))
|
||||
add_view(coarse)
|
||||
chosen_rot = 0
|
||||
img_work = img
|
||||
|
||||
# ---- 2) 方向补测:只在「身份证号 / 卡号」都没读准时才做(每多一次约 2~4s)
|
||||
if not fast:
|
||||
def quick_q(views: Sequence[View]) -> int:
|
||||
idok = any(c.checksum_ok for c in id_candidates(rows_of(views, "id"), limit=3))
|
||||
cok = any(c.luhn_ok for c in card_candidates(rows_of(views, "bank"), limit=3))
|
||||
return int(idok) + int(cok)
|
||||
|
||||
q = quick_q(views)
|
||||
# 文字是竖排的(整张照片拍横了)或几乎没识别到字,才值得换方向重认
|
||||
rotated_text = _looks_rotated(coarse.lines)
|
||||
few_text = len(coarse.lines) <= 2
|
||||
if q < 2 and (rotated_text or few_text):
|
||||
best_q, best_k = q, 0
|
||||
for k in (1, 3):
|
||||
small = resize_side(rotate90(img, k), max_side=_COARSE_SIDE)
|
||||
probe = View(name="probe", image=small, source="coarse", rect=(0, 0, W, H))
|
||||
probe.lines = ocr_lines(small)
|
||||
probe.text = join_text(probe.lines)
|
||||
probe.kind = classify(probe.text)
|
||||
qk = quick_q([probe])
|
||||
if qk > best_q:
|
||||
best_q, best_k = qk, k
|
||||
if qk == 2:
|
||||
break
|
||||
if best_k:
|
||||
chosen_rot = best_k
|
||||
img_work = rotate90(img, chosen_rot)
|
||||
views.clear()
|
||||
coarse = View(name="coarse",
|
||||
image=resize_side(img_work, max_side=_COARSE_SIDE),
|
||||
source="coarse",
|
||||
rect=(0, 0, img_work.shape[1], img_work.shape[0]))
|
||||
add_view(coarse)
|
||||
|
||||
# ---- 3) 首版字段抽取
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
extra_used = 0
|
||||
extra_rows: List[str] = []
|
||||
|
||||
# ---- 4) 精修:只在字段缺失 / 不可信时,回原图按原生分辨率切块重识别
|
||||
need_id = not id_res.checksum_ok
|
||||
need_card = not (bank_res.found and bank_res.luhn_ok
|
||||
and bank_res.length in (16, 18, 19))
|
||||
if (need_id or need_card) and not fast:
|
||||
budget = 2
|
||||
for v in _fine_views(img_work, coarse, budget=budget):
|
||||
add_view(v)
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
|
||||
# ---- 5) 多路增强:数字带换灰度/黑帽/Otsu 反相再识别一遍(浮雕字、反光靠这层)
|
||||
if extra_passes and not fast and (not id_res.checksum_ok
|
||||
or not (bank_res.found and bank_res.luhn_ok)):
|
||||
# 5.1 整图灰度/CLAHE 通道:彩色图上漏掉的卡号,灰度图经常能出来(实测很有效)
|
||||
if not (bank_res.found and bank_res.luhn_ok):
|
||||
base = resize_side(img_work, max_side=_COARSE_SIDE)
|
||||
for vname, var in gray_variants(to_gray(base), upscale=1.0):
|
||||
if vname not in ("gray", "clahe"):
|
||||
continue
|
||||
add_view(View(name=f"gray_{vname}", image=var, source="fine",
|
||||
rect=(0, 0, base.shape[1], base.shape[0])))
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
|
||||
# 5.2 小图放大补识别:短边 <800px 的缩略图,卡号笔画往往只有几个像素
|
||||
if (not (bank_res.found and bank_res.luhn_ok)) and min(W, H) < 800:
|
||||
big = resize_side(img_work, min_side=2400)
|
||||
for vname, var in gray_variants(to_gray(big), upscale=1.0):
|
||||
if vname not in ("gray", "adaptive"):
|
||||
continue
|
||||
add_view(View(name=f"zoom_{vname}", image=var, source="fine",
|
||||
rect=(0, 0, big.shape[1], big.shape[0])))
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
|
||||
# 5.3 数字带窄条:跳过检测网络,多路增强 + 出现合法卡号就收工
|
||||
if not (bank_res.found and bank_res.luhn_ok):
|
||||
digit_views = [v for v in views if v.source in ("fine", "quad", "coarse")]
|
||||
digit_views.sort(key=lambda v: -_digitish(v.text))
|
||||
for v in digit_views[:2]:
|
||||
for rows in _strip_variants(v, v.lines, want=2):
|
||||
extra_rows.extend(rows)
|
||||
extra_used += len(rows)
|
||||
id_res, bank_res = _extract(views, expected_name, extra_rows=extra_rows)
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
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)):
|
||||
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))))
|
||||
if len(views) > 1:
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
|
||||
# ---- 5) 汇总标记
|
||||
flags: List[str] = []
|
||||
if id_res.found and not id_res.checksum_ok:
|
||||
flags.append("id_checksum_fail")
|
||||
if not id_res.found:
|
||||
flags.append("id_not_found")
|
||||
if not bank_res.found:
|
||||
flags.append("card_not_found")
|
||||
elif not bank_res.luhn_ok:
|
||||
flags.append("card_luhn_fail")
|
||||
if bank_res.found and bank_res.length not in (16, 18, 19):
|
||||
flags.append("card_length_odd")
|
||||
if id_res.number and bank_res.number and id_res.number == bank_res.number:
|
||||
flags.append("same_number_id_and_card")
|
||||
if expected_name and id_res.name and id_res.name != expected_name:
|
||||
flags.append("id_name_mismatch")
|
||||
if min(H, W) < 400:
|
||||
flags.append("low_resolution")
|
||||
if chosen_rot:
|
||||
flags.append(f"rotated_{chosen_rot * 90}")
|
||||
|
||||
# 所有识别到过的数字片段(含被淘汰的候选),供「和已知号码比对」时找证据
|
||||
runs: List[str] = []
|
||||
for row in rows_of(views) + extra_rows:
|
||||
runs.extend(number_runs(row, 6))
|
||||
unique_runs = list(dict.fromkeys(runs))[:40]
|
||||
|
||||
res = {
|
||||
"file": str(p), "filename": p.name,
|
||||
"bytes": p.stat().st_size if p.exists() else 0,
|
||||
"width": W, "height": H,
|
||||
"sha256": sha256_file(p),
|
||||
"elapsed_s": round(time.time() - t0, 2),
|
||||
"rotation_applied": chosen_rot * 90,
|
||||
"views": [v.to_dict() for v in views],
|
||||
"layout": _layout(views),
|
||||
"id_card": id_res.to_dict(),
|
||||
"bank_card": bank_res.to_dict(),
|
||||
"digit_runs": unique_runs,
|
||||
"flags": flags,
|
||||
"ocr_passes": len(views) + extra_used,
|
||||
}
|
||||
if mark_dir:
|
||||
res["marks"] = _save_marks(views, str(mark_dir), p.stem)
|
||||
return res
|
||||
|
||||
|
||||
def idline(views: Sequence[View], kind: str) -> List[Line]:
|
||||
focus = [v for v in views if v.kind in (kind, "both")]
|
||||
return [ln for v in (focus or views) for ln in v.lines]
|
||||
|
||||
|
||||
def bline(views: Sequence[View], kind: str) -> List[Line]:
|
||||
focus = [v for v in views if v.kind in (kind, "both")]
|
||||
return [ln for v in (focus or views) for ln in v.lines]
|
||||
|
||||
|
||||
def rows_of(views: Sequence[View], kind: str = "") -> List[str]:
|
||||
"""按视图取「行文本」;kind 传 id/bank 时只取对应卡片视图(没有则退回全部)。"""
|
||||
focus = [v for v in views if v.kind in (kind, "both")] if kind else list(views)
|
||||
out: List[str] = []
|
||||
for v in (focus or views):
|
||||
out.extend(row_texts(v.lines))
|
||||
return out
|
||||
|
||||
|
||||
def _extract(views: Sequence[View], expected_name: str,
|
||||
extra_rows: Optional[Sequence[str]] = None):
|
||||
"""按视图集合跑一遍字段抽取(extra_rows 是补充识别出来的行文本)。"""
|
||||
all_text = " ".join(v.text for v in views)
|
||||
extra = list(extra_rows or ())
|
||||
id_res = idcard.parse(idline(views, "id"), expected_name=expected_name,
|
||||
full_text=all_text, rows=rows_of(views, "id") + extra)
|
||||
bank_res = bankcard.parse(bline(views, "bank"), all_text,
|
||||
exclude=[id_res.number] if id_res.number else (),
|
||||
rows=rows_of(views, "bank") + extra)
|
||||
return id_res, bank_res
|
||||
|
||||
|
||||
def _layout(views: Sequence[View]) -> str:
|
||||
kinds = {v.kind for v in views}
|
||||
if "both" in kinds or ("id" in kinds and "bank" in kinds):
|
||||
return "both"
|
||||
if kinds == {"id"}:
|
||||
return "id_only"
|
||||
if kinds == {"bank"}:
|
||||
return "bank_only"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def sha256_file(p: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(p, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 标注图
|
||||
_FONT_CACHE: Dict[int, object] = {}
|
||||
|
||||
|
||||
def _font(size: int = 16):
|
||||
if size in _FONT_CACHE:
|
||||
return _FONT_CACHE[size]
|
||||
try:
|
||||
from PIL import ImageFont # noqa: PLC0415
|
||||
|
||||
for cand in (r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\simhei.ttf",
|
||||
r"C:\Windows\Fonts\simsun.ttc"):
|
||||
if os.path.isfile(cand):
|
||||
try:
|
||||
_FONT_CACHE[size] = ImageFont.truetype(cand, size)
|
||||
return _FONT_CACHE[size]
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_FONT_CACHE[size] = None
|
||||
return None
|
||||
|
||||
|
||||
def _save_marks(views: Sequence[View], out_dir: str, stem: str) -> List[str]:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
font = _font(16)
|
||||
paths: List[str] = []
|
||||
for v in views:
|
||||
base = v.image.copy()
|
||||
for ln in v.lines:
|
||||
cv2.rectangle(base, (ln.left, ln.top), (ln.right, ln.bottom), (0, 200, 0), 1)
|
||||
if font is not None:
|
||||
from PIL import Image, ImageDraw # noqa: PLC0415
|
||||
|
||||
pil = Image.fromarray(cv2.cvtColor(base, cv2.COLOR_BGR2RGB))
|
||||
draw = ImageDraw.Draw(pil)
|
||||
for ln in v.lines:
|
||||
ty = ln.top - 18 if ln.top >= 18 else ln.bottom + 2
|
||||
draw.text((ln.left, ty), ln.text[:24], fill=(255, 0, 0), font=font)
|
||||
canvas = np.array(pil)[:, :, ::-1]
|
||||
else:
|
||||
canvas = base
|
||||
out = os.path.join(out_dir, f"{stem}.{v.name}.{v.kind}.png")
|
||||
ok, buf = cv2.imencode(".png", canvas)
|
||||
if ok:
|
||||
buf.tofile(out)
|
||||
paths.append(out)
|
||||
return paths
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 批量
|
||||
def analyze_folder(root: str, expected_names: Optional[Dict[str, str]] = None,
|
||||
mark_dir: Optional[str] = None, extra_passes: bool = True,
|
||||
fast: bool = False, limit: int = 0) -> List[dict]:
|
||||
"""按「姓名/图片」目录结构批量识别,同人多图合并成一条记录。"""
|
||||
root_p = Path(root)
|
||||
if not root_p.is_dir():
|
||||
raise FileNotFoundError(f"目录不存在:{root}")
|
||||
persons: List[dict] = []
|
||||
cache: Dict[str, dict] = {} # sha256 → 识别结果(同一张图被传到两列时只跑一遍)
|
||||
for d in sorted(root_p.iterdir()):
|
||||
if not d.is_dir():
|
||||
continue
|
||||
imgs = sorted(p for p in d.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_EXT)
|
||||
if not imgs:
|
||||
continue
|
||||
name = (expected_names or {}).get(d.name, d.name)
|
||||
rows = []
|
||||
for p in (imgs[:limit] if limit else imgs):
|
||||
digest = ""
|
||||
try:
|
||||
digest = sha256_file(p)
|
||||
if digest in cache:
|
||||
cached = cache[digest]
|
||||
rows.append({**cached, "file": str(p), "filename": p.name,
|
||||
"reused_from": cached.get("filename")})
|
||||
continue
|
||||
res = analyze_image(str(p), expected_name=name, mark_dir=mark_dir,
|
||||
extra_passes=extra_passes, fast=fast)
|
||||
cache[digest] = res
|
||||
rows.append(res)
|
||||
logger.info("%s/%s 完成:%.1fs id=%s card=%s", d.name, p.name,
|
||||
res.get("elapsed_s", 0),
|
||||
res.get("id_card", {}).get("number") or "-",
|
||||
res.get("bank_card", {}).get("number") or "-")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("识别失败:%s", p)
|
||||
rows.append({"file": str(p), "filename": p.name, "ok": False,
|
||||
"sha256": digest, "error": f"{type(e).__name__}: {e}"})
|
||||
persons.append(_merge_person(d.name, name, rows))
|
||||
return persons
|
||||
|
||||
|
||||
def _merge_person(folder_name: str, expected_name: str, rows: List[dict]) -> dict:
|
||||
ok_rows = [r for r in rows if r.get("ok", True) and "id_card" in r]
|
||||
hashes = {r.get("sha256") for r in ok_rows if r.get("sha256")}
|
||||
|
||||
def best(key: str, prefer: str) -> dict:
|
||||
# 号码没识别出来,但卡面银行名 / 身份证姓名读到了,也要保留(交叉核对时有用)
|
||||
items = [r[key] for r in ok_rows
|
||||
if r.get(key, {}).get("found") or r.get(key, {}).get("bank")
|
||||
or r.get(key, {}).get("name")]
|
||||
if not items:
|
||||
return {}
|
||||
rank = {"high": 3, "medium": 2, "low": 1}
|
||||
|
||||
def score(d: dict) -> tuple:
|
||||
return (1 if d.get(prefer) else 0, rank.get(d.get("confidence"), 0),
|
||||
max([c.get("score", 0) for c in d.get("candidates", [])] or [0]))
|
||||
|
||||
return max(items, key=score)
|
||||
|
||||
id_best = best("id_card", "checksum_ok")
|
||||
bank_best = best("bank_card", "luhn_ok")
|
||||
flags: List[str] = []
|
||||
if len(ok_rows) < 2:
|
||||
flags.append("missing_one_photo")
|
||||
if len(hashes) == 1 and len(ok_rows) >= 2:
|
||||
flags.append("duplicate_photo")
|
||||
# 只按「人」的最终结果判定字段问题,不把「这张图没拍到身份证」当成整人的问题
|
||||
if not id_best.get("number"):
|
||||
flags.append("id_not_found")
|
||||
elif not id_best.get("checksum_ok"):
|
||||
flags.append("id_checksum_fail")
|
||||
elif expected_name and id_best.get("name") and id_best["name"] != expected_name:
|
||||
flags.append("id_name_mismatch")
|
||||
if not bank_best.get("number"):
|
||||
flags.append("card_not_found")
|
||||
elif not bank_best.get("luhn_ok"):
|
||||
flags.append("card_luhn_fail")
|
||||
elif bank_best.get("length") not in (16, 18, 19):
|
||||
flags.append("card_length_odd")
|
||||
# 图像质量类问题才从单图冒泡上来
|
||||
for r in ok_rows:
|
||||
for f in r.get("flags", []):
|
||||
if f in ("low_resolution", "rotated_90", "rotated_180", "rotated_270",
|
||||
"card_not_located", "multiple_cards_in_photo") and f not in flags:
|
||||
flags.append(f)
|
||||
|
||||
return {
|
||||
"folder": folder_name, "expected_name": expected_name,
|
||||
"files": [{"filename": r.get("filename"), "sha256": (r.get("sha256") or "")[:16],
|
||||
"layout": r.get("layout"), "flags": r.get("flags", [])} for r in rows],
|
||||
"id_card": id_best, "bank_card": bank_best,
|
||||
"duplicate_photo": len(hashes) == 1 and len(ok_rows) >= 2,
|
||||
"flags": flags,
|
||||
"raw": ok_rows,
|
||||
}
|
||||
|
||||
|
||||
def _disp_width(s: str) -> int:
|
||||
import unicodedata # noqa: PLC0415
|
||||
|
||||
return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in str(s))
|
||||
|
||||
|
||||
def _pad(s: str, width: int) -> str:
|
||||
s = str(s)
|
||||
return s + " " * max(1, width - _disp_width(s))
|
||||
|
||||
|
||||
def summary_table(persons: Sequence[dict]) -> str:
|
||||
head = (_pad("姓名", 9) + _pad("身份证号", 22) + _pad("校验", 5) + _pad("银行卡号", 24)
|
||||
+ _pad("Luhn", 6) + _pad("发卡行", 20) + "标记")
|
||||
lines = [head, "-" * 104]
|
||||
for p in persons:
|
||||
idc, bk = p.get("id_card", {}), p.get("bank_card", {})
|
||||
lines.append(
|
||||
_pad(p.get("folder", ""), 9)
|
||||
+ _pad(idc.get("number") or "-", 22)
|
||||
+ _pad("✓" if idc.get("checksum_ok") else "✗", 5)
|
||||
+ _pad(bk.get("number") or "-", 24)
|
||||
+ _pad("✓" if bk.get("luhn_ok") else "✗", 6)
|
||||
+ _pad(bk.get("bank") or "-", 20)
|
||||
+ ",".join(p.get("flags", [])))
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""核对工作簿:把识别结果导出成 Excel,留出「正确答案」列给人工填写,并可回读算准确率。
|
||||
|
||||
用法(代码):
|
||||
from cardocr.review import write_review_workbook, verify_workbook
|
||||
write_review_workbook(persons, "识别核对表.xlsx")
|
||||
print(verify_workbook("识别核对表.xlsx"))
|
||||
|
||||
命令行:
|
||||
python -m cardocr review --json result.json --out 识别核对表.xlsx
|
||||
python -m cardocr verify 识别核对表.xlsx
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
|
||||
INPUT_FILL = PatternFill("solid", fgColor="FFF2CC")
|
||||
THIN = Side(style="thin", color="BFBFBF")
|
||||
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||
|
||||
# 逐人核对表列定义:(key, 列名, 宽度)
|
||||
PERSON_COLS = [
|
||||
("pid", "ID", 8),
|
||||
("folder", "姓名(文件夹)", 12),
|
||||
("id_number", "身份证号(识别)", 22),
|
||||
("id_ok", "身份证校验", 10),
|
||||
("id_name", "身份证姓名(识别)", 14),
|
||||
("card_number", "银行卡号(识别)", 22),
|
||||
("card_ok", "Luhn", 7),
|
||||
("bank", "发卡行", 16),
|
||||
("id_conf", "身份证置信度", 12),
|
||||
("card_conf", "卡号置信度", 11),
|
||||
("photos", "图片数", 8),
|
||||
("files", "照片文件", 40),
|
||||
("dup", "重复图片", 9),
|
||||
("flags", "标记", 34),
|
||||
("evidence", "识别说明", 34),
|
||||
("truth_id", "【待填】正确身份证号", 22),
|
||||
("truth_name", "【待填】正确姓名", 14),
|
||||
("truth_card", "【待填】正确银行卡号", 22),
|
||||
("verdict", "【待填】判定", 10),
|
||||
("note", "【待填】说明", 26),
|
||||
]
|
||||
|
||||
IMAGE_COLS = [
|
||||
("iid", "图片ID", 10),
|
||||
("folder", "姓名(文件夹)", 12),
|
||||
("filename", "文件名", 34),
|
||||
("size", "分辨率", 14),
|
||||
("kb", "大小KB", 9),
|
||||
("layout", "布局", 10),
|
||||
("id_number", "身份证号(识别)", 22),
|
||||
("id_ok", "身份证校验", 10),
|
||||
("id_name", "姓名(识别)", 12),
|
||||
("card_number", "卡号(识别)", 22),
|
||||
("card_ok", "Luhn", 7),
|
||||
("bank", "发卡行", 16),
|
||||
("conf", "置信度", 10),
|
||||
("elapsed", "用时s", 8),
|
||||
("sha", "SHA256前12", 15),
|
||||
("flags", "标记", 30),
|
||||
("cands", "卡号候选", 30),
|
||||
("path", "路径", 55),
|
||||
]
|
||||
|
||||
|
||||
def _style_sheet(ws, cols: Sequence[tuple], truth_from: int = 0) -> None:
|
||||
for i, (_key, title, width) in enumerate(cols, 1):
|
||||
c = ws.cell(row=1, column=i, value=title)
|
||||
c.font = Font(bold=True, color="FFFFFF", size=10)
|
||||
c.fill = HEADER_FILL
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = BORDER
|
||||
ws.column_dimensions[get_column_letter(i)].width = width
|
||||
ws.row_dimensions[1].height = 30
|
||||
ws.freeze_panes = "A2"
|
||||
if truth_from:
|
||||
for i in range(truth_from, len(cols) + 1):
|
||||
ws.cell(row=1, column=i).fill = PatternFill("solid", fgColor="C00000")
|
||||
|
||||
|
||||
def _fmt_id(p: dict) -> Dict[str, object]:
|
||||
idc = p.get("id_card") or {}
|
||||
bk = p.get("bank_card") or {}
|
||||
flags = p.get("flags", [])
|
||||
notes = list(idc.get("evidence") or [])
|
||||
if "low_resolution" in flags and bk.get("number"):
|
||||
notes.append("⚠ 原图是缩略图,卡号建议人工复核")
|
||||
if bk.get("number") and not bk.get("luhn_ok"):
|
||||
notes.append("⚠ 卡号未过 Luhn")
|
||||
return {
|
||||
"pid": "",
|
||||
"folder": p.get("folder", ""),
|
||||
"id_number": idc.get("number") or "未识别",
|
||||
"id_ok": "✓" if idc.get("checksum_ok") else ("✗" if idc.get("number") else ""),
|
||||
"id_name": idc.get("name") or "未识别",
|
||||
"card_number": bk.get("number") or "未识别",
|
||||
"card_ok": "✓" if bk.get("luhn_ok") else ("✗" if bk.get("number") else ""),
|
||||
"bank": bk.get("bank") or "-",
|
||||
"id_conf": idc.get("confidence", "") or "-",
|
||||
"card_conf": bk.get("confidence", "") or "-",
|
||||
"photos": len(p.get("files") or []),
|
||||
"files": ";".join(f.get("filename") or "" for f in (p.get("files") or [])),
|
||||
"dup": "是" if p.get("duplicate_photo") else "否",
|
||||
"flags": ",".join(p.get("flags", [])),
|
||||
"evidence": ";".join(notes) or "",
|
||||
}
|
||||
|
||||
|
||||
def _fmt_image(p: dict, r: dict, iid: str) -> Dict[str, object]:
|
||||
idc = r.get("id_card") or {}
|
||||
bk = r.get("bank_card") or {}
|
||||
cands = bk.get("candidates") or []
|
||||
top = [c.get("number", "") for c in cands[:2]]
|
||||
return {
|
||||
"iid": iid,
|
||||
"folder": p.get("folder", ""),
|
||||
"filename": r.get("filename", ""),
|
||||
"size": f"{r.get('width', '')}x{r.get('height', '')}",
|
||||
"kb": round((r.get("bytes") or 0) / 1024),
|
||||
"layout": r.get("layout", ""),
|
||||
"id_number": idc.get("number") or "未识别",
|
||||
"id_ok": "✓" if idc.get("checksum_ok") else ("✗" if idc.get("number") else ""),
|
||||
"id_name": idc.get("name") or "未识别",
|
||||
"card_number": bk.get("number") or "未识别",
|
||||
"card_ok": "✓" if bk.get("luhn_ok") else ("✗" if bk.get("number") else ""),
|
||||
"bank": bk.get("bank") or "-",
|
||||
"conf": f"身份证:{idc.get('confidence', '') or '-'} 卡:{bk.get('confidence', '') or '-'}",
|
||||
"elapsed": r.get("elapsed_s", ""),
|
||||
"sha": (r.get("sha256") or "")[:12],
|
||||
"flags": ",".join(r.get("flags", [])),
|
||||
"cands": " / ".join(top),
|
||||
"path": r.get("file", ""),
|
||||
}
|
||||
|
||||
|
||||
def write_review_workbook(persons: Sequence[dict], path: str,
|
||||
source_root: str = "") -> str:
|
||||
"""导出核对工作簿(3 个 sheet:逐人核对 / 逐图明细 / 填写说明)。"""
|
||||
wb = Workbook()
|
||||
ws1 = wb.active
|
||||
ws1.title = "逐人核对"
|
||||
ws2 = wb.create_sheet("逐图明细")
|
||||
ws3 = wb.create_sheet("填写说明")
|
||||
|
||||
truth_from = next((i for i, (_k, _t, _w) in enumerate(PERSON_COLS, 1)
|
||||
if _k.startswith("truth")), 0)
|
||||
_style_sheet(ws1, PERSON_COLS, truth_from=truth_from)
|
||||
_style_sheet(ws2, IMAGE_COLS)
|
||||
|
||||
stats = {"persons": len(persons), "photos": 0}
|
||||
id_ok = id_bad = 0
|
||||
card_ok = card_bad = 0
|
||||
r1 = 2
|
||||
r2 = 2
|
||||
for idx, p in enumerate(persons, 1):
|
||||
pid = f"P{idx:03d}"
|
||||
row = _fmt_id(p)
|
||||
row["pid"] = pid
|
||||
for col, (_key, _title, _w) in enumerate(PERSON_COLS, 1):
|
||||
c = ws1.cell(row=r1, column=col, value=row.get(_key, ""))
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
if col >= 15:
|
||||
c.fill = INPUT_FILL
|
||||
ws1.row_dimensions[r1].height = 22
|
||||
if row["id_ok"] == "✓":
|
||||
id_ok += 1
|
||||
elif row["id_ok"] == "✗":
|
||||
id_bad += 1
|
||||
if row["card_ok"] == "✓":
|
||||
card_ok += 1
|
||||
elif row["card_ok"] == "✗":
|
||||
card_bad += 1
|
||||
|
||||
imgs = [r for r in (p.get("raw") or []) if r.get("id_card") or r.get("bank_card")]
|
||||
for j, r in enumerate(imgs, 1):
|
||||
row2 = _fmt_image(p, r, f"{pid}-{'AB'[min(j - 1, 1)]}")
|
||||
for col, (_key, _title, _w) in enumerate(IMAGE_COLS, 1):
|
||||
c = ws2.cell(row=r2, column=col, value=row2.get(_key, ""))
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
ws2.row_dimensions[r2].height = 22
|
||||
r2 += 1
|
||||
stats["photos"] += 1
|
||||
r1 += 1
|
||||
|
||||
ws1.auto_filter.ref = f"A1:{get_column_letter(len(PERSON_COLS))}{r1 - 1}"
|
||||
ws2.auto_filter.ref = f"A1:{get_column_letter(len(IMAGE_COLS))}{r2 - 1}"
|
||||
ws3.column_dimensions["A"].width = 90
|
||||
lines = [
|
||||
"填写说明",
|
||||
"",
|
||||
"1. 只需要填「逐人核对」里黄色底的 5 列:正确身份证号 / 正确姓名 / 正确银行卡号 / 判定 / 说明。",
|
||||
"2. 判定填 对 / 错 / 部分:整行都识别对了填 对;哪里错了填 错,并在说明里写清楚(例如「卡号错 2 位」)。",
|
||||
"3. 识别为空但实际有值的,正确列请照实填写(这是最有价值的样本)。",
|
||||
"4. 身份证校验 / Luhn 是识别结果自带的数学校验,不代表业务上一定对;以你填的为准。",
|
||||
"5. 填好后运行:python -m cardocr verify 本文件.xlsx,会自动算准确率。",
|
||||
"",
|
||||
"标记含义",
|
||||
" duplicate_photo 同一个人两列上传了同一张图(数据录入问题)",
|
||||
" missing_one_photo 只找到一张照片",
|
||||
" id_not_found 没有识别到身份证号",
|
||||
" id_checksum_fail 识别到 18 位号码但校验码不通过",
|
||||
" id_name_mismatch 身份证姓名与文件夹姓名不一致",
|
||||
" card_not_found 没有识别到银行卡号",
|
||||
" card_luhn_fail 识别到候选卡号但 Luhn 不通过",
|
||||
" card_length_odd 卡号位数不是 16/18/19",
|
||||
" low_resolution 原图短边 < 400px(多为缩略图)",
|
||||
" rotated_90 / rotated_270 照片是横拍的,已自动转正后识别",
|
||||
" multiple_cards_in_photo 一张照片里有不止一张卡",
|
||||
" card_not_located 没定位到卡片轮廓,按整图识别",
|
||||
"",
|
||||
f"本次统计:{stats['persons']} 人 / {stats['photos']} 张图;"
|
||||
f"身份证号有号码且校验通过 {id_ok} 人、有号码但校验失败 {id_bad} 人;"
|
||||
f"卡号 Luhn 通过 {card_ok} 人、有候选但未通过 {card_bad} 人。",
|
||||
f"图片根目录:{source_root}" if source_root else "",
|
||||
]
|
||||
for i, text in enumerate(lines, 1):
|
||||
c = ws3.cell(row=i, column=1, value=text)
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
if i == 1:
|
||||
c.font = Font(bold=True, size=14)
|
||||
else:
|
||||
c.font = Font(size=10.5)
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 回读核对
|
||||
def verify_workbook(path: str) -> dict:
|
||||
"""读回填好的核对表,统计身份证号 / 卡号 / 姓名三项准确率。"""
|
||||
wb = load_workbook(path, data_only=True)
|
||||
ws = wb["逐人核对"]
|
||||
idx = {c.value: i for i, c in enumerate(ws[1], 1) if c.value}
|
||||
|
||||
def cell(row, name: str) -> str:
|
||||
i = idx.get(name)
|
||||
if not i:
|
||||
return ""
|
||||
v = row[i - 1].value
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
res = {"rows": 0, "id": [0, 0, 0], "name": [0, 0, 0], "card": [0, 0, 0],
|
||||
"skipped": []}
|
||||
errors: List[dict] = []
|
||||
|
||||
def is_truth(v: str) -> bool:
|
||||
"""「人工也无法识别 / 无 / -」这类填写不算真值,跳过统计。"""
|
||||
return bool(v) and v not in ("无", "-", "/") and "无法识别" not in v
|
||||
|
||||
for row in ws.iter_rows(min_row=2):
|
||||
pid = cell(row, "ID")
|
||||
if not pid:
|
||||
continue
|
||||
t_id = cell(row, "【待填】正确身份证号")
|
||||
t_name = cell(row, "【待填】正确姓名")
|
||||
t_card = cell(row, "【待填】正确银行卡号")
|
||||
if not (t_id or t_name or t_card):
|
||||
continue
|
||||
res["rows"] += 1
|
||||
for label, v in (("身份证号", t_id), ("姓名", t_name), ("银行卡号", t_card)):
|
||||
if v and not is_truth(v):
|
||||
res["skipped"].append({"ID": pid, "字段": label, "填写": v})
|
||||
|
||||
def cmp(truth: str, got_key: str, bucket: List[int], label: str) -> None:
|
||||
if not is_truth(truth):
|
||||
return
|
||||
got = cell(row, got_key)
|
||||
if got == "未识别":
|
||||
got = ""
|
||||
ok = got.upper() == truth.upper()
|
||||
bucket[0] += 1
|
||||
bucket[1 if ok else 2] += 1
|
||||
if not ok:
|
||||
errors.append({"ID": pid, "姓名": cell(row, "姓名(文件夹)"), "字段": label,
|
||||
"识别": got, "正确": truth})
|
||||
|
||||
cmp(t_id, "身份证号(识别)", res["id"], "身份证号")
|
||||
cmp(t_name, "身份证姓名(识别)", res["name"], "姓名")
|
||||
cmp(t_card, "银行卡号(识别)", res["card"], "银行卡号")
|
||||
|
||||
out = {"核对行数": res["rows"], "明细": {}, "错误": errors,
|
||||
"跳过": res["skipped"]}
|
||||
for key, label in (("id", "身份证号"), ("name", "姓名"), ("card", "银行卡号")):
|
||||
total, right, wrong = res[key]
|
||||
out["明细"][label] = {
|
||||
"有真值": total, "正确": right, "错误": wrong,
|
||||
"准确率": f"{(right / total * 100 if total else 0):.1f}%",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def print_verify(result: dict) -> None:
|
||||
print(f"核对行数:{result['核对行数']}")
|
||||
for label, d in result["明细"].items():
|
||||
print(f" {label}: 有真值 {d['有真值']},正确 {d['正确']},错误 {d['错误']},准确率 {d['准确率']}")
|
||||
if result["错误"]:
|
||||
print("\n错误明细:")
|
||||
for e in result["错误"]:
|
||||
print(f" {e['ID']} {e['姓名']} {e['字段']}:识别「{e['识别']}」 → 正确「{e['正确']}」")
|
||||
|
||||
|
||||
def load_persons(json_path: str) -> List[dict]:
|
||||
with open(json_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("persons") or data.get("images") or []
|
||||
|
||||
|
||||
def load_truth_workbook(path: str) -> Dict[str, Dict[str, str]]:
|
||||
"""读回人工填好的核对表:文件夹姓名 → {id, name, card}。"""
|
||||
wb = load_workbook(path, data_only=True)
|
||||
ws = wb["逐人核对"]
|
||||
idx = {c.value: i for i, c in enumerate(ws[1], 1) if c.value}
|
||||
out: Dict[str, Dict[str, str]] = {}
|
||||
for row in ws.iter_rows(min_row=2, values_only=True):
|
||||
def cell(name: str) -> str:
|
||||
i = idx.get(name)
|
||||
if not i:
|
||||
return ""
|
||||
v = row[i - 1]
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
folder = cell("姓名(文件夹)")
|
||||
if not folder:
|
||||
continue
|
||||
out[folder] = {"id": cell("【待填】正确身份证号"),
|
||||
"name": cell("【待填】正确姓名"),
|
||||
"card": cell("【待填】正确银行卡号"),
|
||||
"note": cell("【待填】说明")}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""号码校验与纠错:身份证 18 位校验码、银行卡 Luhn、OCR 易混字符还原。
|
||||
|
||||
两种号码都自带数学校验位,这让我们能把 OCR 出来的「b214 8338 3071 20bb」
|
||||
这类文本,在有限候选里反推出唯一合法号码——这是本模块敢离线跑的关键。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
# ---------------------------------------------------------------- 字符归一
|
||||
# OCR 把数字认成字母(或反过来)的常见映射;值是「可能对应的数字」
|
||||
_CONFUSABLE: Dict[str, Tuple[str, ...]] = {
|
||||
"O": ("0",), "o": ("0",), "D": ("0",),
|
||||
"I": ("1",), "l": ("1",), "|": ("1",), "!": ("1",),
|
||||
"L": ("1",), "Z": ("2",), "z": ("2",),
|
||||
"S": ("5",), "s": ("5",), "$": ("5",),
|
||||
"B": ("6", "8"), "b": ("6", "8"),
|
||||
"G": ("9", "6"), "g": ("9", "6"), "q": ("9", "6"),
|
||||
"A": ("4",), "a": ("4",), "E": ("8",), "e": ("8",),
|
||||
"T": ("7",), "t": ("7",), "C": ("0", "6"),
|
||||
"X": ("X",), "x": ("X",),
|
||||
}
|
||||
|
||||
PRIMARY: Dict[str, str] = {k: v[0] for k, v in _CONFUSABLE.items()}
|
||||
|
||||
|
||||
def normalize_text(text: str) -> str:
|
||||
"""全角转半角、去空白(OCR 常在数字间插空格)。"""
|
||||
out = []
|
||||
for ch in str(text or ""):
|
||||
o = ord(ch)
|
||||
if 0xFF01 <= o <= 0xFF5E: # 全角 ASCII
|
||||
ch = chr(o - 0xFEE0)
|
||||
elif o == 0x3000: # 全角空格
|
||||
ch = " "
|
||||
out.append(ch)
|
||||
return re.sub(r"\s+", "", "".join(out))
|
||||
|
||||
|
||||
def digitize(text: str) -> Tuple[str, List[int]]:
|
||||
"""把文本压成数字串(字母按首选映射),并返回「有歧义」的位置下标。"""
|
||||
s = normalize_text(text)
|
||||
digits, ambiguous = [], []
|
||||
for ch in s:
|
||||
if ch.isdigit():
|
||||
digits.append(ch)
|
||||
elif ch in _CONFUSABLE:
|
||||
digits.append(PRIMARY[ch])
|
||||
if len(_CONFUSABLE[ch]) > 1:
|
||||
ambiguous.append(len(digits) - 1)
|
||||
return "".join(digits), ambiguous
|
||||
|
||||
|
||||
def digit_runs(text: str, min_len: int = 13) -> List[str]:
|
||||
"""从一段文本里抽出连续数字串(允许中间夹易混字母)。"""
|
||||
s = normalize_text(text)
|
||||
# 把易混字母当数字,再做游程切分
|
||||
norm = "".join(PRIMARY.get(c, c) if not c.isdigit() else c for c in s)
|
||||
runs = re.findall(r"[0-9]{%d,}" % min_len, norm)
|
||||
return runs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 身份证
|
||||
# 18 位:6 位地址 + 8 位生日 + 3 位顺序 + 1 位校验
|
||||
_ID_WEIGHTS = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
|
||||
_ID_CHECK = "10X98765432"
|
||||
|
||||
|
||||
def id_checksum_ok(no: str) -> bool:
|
||||
if len(no) != 18:
|
||||
return False
|
||||
if not re.fullmatch(r"\d{17}[\dXx]", no):
|
||||
return False
|
||||
total = sum(int(no[i]) * _ID_WEIGHTS[i] for i in range(17))
|
||||
return _ID_CHECK[total % 11] == no[17].upper()
|
||||
|
||||
|
||||
def id_birth(no: str) -> str:
|
||||
"""从身份证号取生日 YYYY-MM-DD(含合法性检查,不合法返回空)。"""
|
||||
if len(no) != 18:
|
||||
return ""
|
||||
y, m, d = int(no[6:10]), int(no[10:12]), int(no[12:14])
|
||||
if not (1900 <= y <= 2020) or not (1 <= m <= 12) or not (1 <= d <= 31):
|
||||
return ""
|
||||
return f"{y:04d}-{m:02d}-{d:02d}"
|
||||
|
||||
|
||||
def id_gender(no: str) -> str:
|
||||
if len(no) != 18:
|
||||
return ""
|
||||
return "男" if int(no[16]) % 2 == 1 else "女"
|
||||
|
||||
|
||||
def id_region(no: str) -> str:
|
||||
return no[:2] if len(no) == 18 else ""
|
||||
|
||||
|
||||
_VALID_PROVINCE = {f"{i:02d}" for i in range(11, 66)}
|
||||
|
||||
|
||||
def id_plausible(no: str) -> bool:
|
||||
return (len(no) == 18
|
||||
and id_region(no) in _VALID_PROVINCE
|
||||
and bool(id_birth(no)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdCandidate:
|
||||
number: str
|
||||
checksum_ok: bool
|
||||
origin: str = "raw" # raw / repaired
|
||||
edits: int = 0
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
def id_candidates(text: Union[str, Sequence[str]], limit: int = 8) -> List[IdCandidate]:
|
||||
"""从 OCR 文本里找身份证号候选,并做 1~2 位纠错。
|
||||
|
||||
text 可以是单段文本,也可以是「行文本列表」(推荐:按行抓,避免跨行串号)。
|
||||
"""
|
||||
rows = [text] if isinstance(text, str) else list(text)
|
||||
seen: Dict[str, IdCandidate] = {}
|
||||
|
||||
def add(no: str, origin: str, edits: int) -> None:
|
||||
no = no.upper()
|
||||
if len(no) != 18:
|
||||
return
|
||||
c = seen.get(no)
|
||||
ok = id_checksum_ok(no)
|
||||
if c is None or (ok and not c.checksum_ok):
|
||||
seen[no] = IdCandidate(no, ok, origin, edits, score=0.0)
|
||||
|
||||
for row in rows:
|
||||
s = normalize_text(row)
|
||||
# 原始文本里的 18 位窗口(允许 X 结尾、允许混入易混字母)
|
||||
for raw in re.findall(r"[0-9OoIlLZzSBbGgqAaEeTtCc|!]{17}[0-9XxOoIl]", s):
|
||||
d, amb = digitize(raw)
|
||||
if len(d) == 18:
|
||||
add(d, "raw", 0)
|
||||
if len(amb) <= 4 and not id_checksum_ok(d):
|
||||
for combo in _enumerate_ambiguous(d, amb, limit=200):
|
||||
add(combo, "repaired", sum(1 for x, y in zip(d, combo) if x != y))
|
||||
# 纯数字窗口(含标签粘连)
|
||||
for m in re.finditer(r"\d{17}[\dXx]", s):
|
||||
add(m.group(0), "raw", 0)
|
||||
if not id_checksum_ok(m.group(0)):
|
||||
for combo in _one_digit_sub(m.group(0), limit=200):
|
||||
add(combo, "repaired", 1)
|
||||
|
||||
for c in seen.values():
|
||||
c.score = (3.0 if c.checksum_ok else 0.0) + (2.0 if id_plausible(c.number) else 0.0) \
|
||||
- 0.5 * c.edits
|
||||
return sorted(seen.values(), key=lambda x: -x.score)[:limit]
|
||||
|
||||
|
||||
def _enumerate_ambiguous(digits: str, positions: Sequence[int],
|
||||
limit: int = 200) -> List[str]:
|
||||
"""在歧义位置枚举替代数字。"""
|
||||
out = [digits]
|
||||
for pos in positions:
|
||||
ch = digits[pos]
|
||||
alts = [x for x in _CONFUSABLE.get(ch, ()) if x.isdigit()]
|
||||
if len(alts) <= 1:
|
||||
continue
|
||||
new = []
|
||||
for base in out:
|
||||
for a in alts:
|
||||
new.append(base[:pos] + a + base[pos + 1:])
|
||||
out = new[:limit]
|
||||
return out
|
||||
|
||||
|
||||
def _one_digit_sub(no: str, limit: int = 200) -> List[str]:
|
||||
out = []
|
||||
for i in range(len(no)):
|
||||
cur = no[i]
|
||||
for d in "0123456789":
|
||||
if d == cur:
|
||||
continue
|
||||
cand = no[:i] + d + no[i + 1:]
|
||||
if id_checksum_ok(cand) and id_plausible(cand):
|
||||
out.append(cand)
|
||||
if len(out) >= limit:
|
||||
return out
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 银行卡
|
||||
def luhn_ok(no: str) -> bool:
|
||||
if not no or not no.isdigit() or not (13 <= len(no) <= 19):
|
||||
return False
|
||||
total, alt = 0, False
|
||||
for ch in reversed(no):
|
||||
d = int(ch)
|
||||
if alt:
|
||||
d *= 2
|
||||
if d > 9:
|
||||
d -= 9
|
||||
total += d
|
||||
alt = not alt
|
||||
return total % 10 == 0
|
||||
|
||||
|
||||
def luhn_check_digit(prefix: str) -> str:
|
||||
"""给前 n-1 位算 Luhn 校验位。"""
|
||||
total, alt = 0, True
|
||||
for ch in reversed(prefix):
|
||||
d = int(ch)
|
||||
if alt:
|
||||
d *= 2
|
||||
if d > 9:
|
||||
d -= 9
|
||||
total += d
|
||||
alt = not alt
|
||||
return str((10 - total % 10) % 10)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CardCandidate:
|
||||
number: str
|
||||
digits: int
|
||||
luhn_ok: bool
|
||||
prefix: str = ""
|
||||
bank: str = ""
|
||||
origin: str = "raw" # raw / consensus / repaired
|
||||
edits: int = 0
|
||||
votes: int = 1
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断
|
||||
BIN_BANK: Dict[str, str] = {
|
||||
# 工商银行
|
||||
"622202": "中国工商银行", "622203": "中国工商银行", "622200": "中国工商银行",
|
||||
"622208": "中国工商银行", "621226": "中国工商银行", "955880": "中国工商银行",
|
||||
"955882": "中国工商银行", "621225": "中国工商银行",
|
||||
# 农业银行
|
||||
"622848": "中国农业银行", "622845": "中国农业银行", "622846": "中国农业银行",
|
||||
"622849": "中国农业银行", "621336": "中国农业银行", "622841": "中国农业银行",
|
||||
# 建设银行
|
||||
"621700": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
|
||||
"622280": "中国建设银行", "621081": "中国建设银行",
|
||||
# 中国银行
|
||||
"621661": "中国银行", "621660": "中国银行", "621662": "中国银行",
|
||||
"621663": "中国银行", "621665": "中国银行", "601382": "中国银行",
|
||||
"456351": "中国银行", "621785": "中国银行", "621786": "中国银行",
|
||||
"621787": "中国银行", "621788": "中国银行", "621789": "中国银行",
|
||||
# 招商银行
|
||||
"621483": "招商银行", "622588": "招商银行", "621286": "招商银行",
|
||||
"622575": "招商银行", "622576": "招商银行", "622577": "招商银行",
|
||||
"622578": "招商银行", "622579": "招商银行",
|
||||
# 民生银行
|
||||
"622622": "中国民生银行", "622600": "中国民生银行", "622601": "中国民生银行",
|
||||
"622602": "中国民生银行", "622603": "中国民生银行", "622615": "中国民生银行",
|
||||
"622617": "中国民生银行", "622619": "中国民生银行", "622621": "中国民生银行",
|
||||
"622623": "中国民生银行", "421393": "中国民生银行",
|
||||
# 兴业银行
|
||||
"622908": "兴业银行", "622909": "兴业银行", "621084": "兴业银行",
|
||||
# 浦发银行
|
||||
"622521": "浦发银行", "622522": "浦发银行", "622523": "浦发银行",
|
||||
"622516": "浦发银行", "622517": "浦发银行", "622518": "浦发银行",
|
||||
"622525": "浦发银行", "622526": "浦发银行",
|
||||
# 交通银行
|
||||
"622260": "交通银行", "622262": "交通银行", "622250": "交通银行",
|
||||
"622251": "交通银行", "622252": "交通银行", "622253": "交通银行",
|
||||
"622254": "交通银行", "622255": "交通银行",
|
||||
# 邮储银行
|
||||
"622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行",
|
||||
"621095": "中国邮政储蓄银行", "620062": "中国邮政储蓄银行", "955100": "中国邮政储蓄银行",
|
||||
# 中信 / 光大 / 华夏 / 广发 / 平安
|
||||
"622690": "中信银行", "622691": "中信银行", "622692": "中信银行",
|
||||
"622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行",
|
||||
"622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行",
|
||||
"622568": "广发银行", "622576": "广发银行",
|
||||
"622155": "平安银行", "622156": "平安银行", "622157": "平安银行",
|
||||
}
|
||||
|
||||
|
||||
def bin_bank(no: str) -> str:
|
||||
return BIN_BANK.get(no[:6], "") if len(no) >= 6 else ""
|
||||
|
||||
|
||||
def prefix_ok(no: str) -> bool:
|
||||
"""前缀是否像一张国内借记卡:62 开头,或命中已知 BIN(含 4/6/9 开头的老卡)。"""
|
||||
return bool(bin_bank(no)) or no.startswith("62")
|
||||
|
||||
|
||||
def _id_like(no: str) -> bool:
|
||||
"""18 位且通过身份证校验码、又不是 62 开头 → 基本可判定是身份证号,不是卡号。"""
|
||||
return len(no) == 18 and id_checksum_ok(no) and not no.startswith("62")
|
||||
|
||||
|
||||
def card_candidates(text: Union[str, Sequence[str]], want_lengths: Sequence[int] = (16, 19, 18),
|
||||
limit: int = 8, exclude: Sequence[str] = ()) -> List[CardCandidate]:
|
||||
"""从 OCR 文本里找卡号候选:游程 + 歧义枚举 + Luhn 校验。
|
||||
|
||||
Args:
|
||||
text: 单段文本或「行文本列表」(推荐按行传,避免跨行把两行数字连起来)。
|
||||
exclude: 已知的身份证号等「长得像卡号」的号码,直接排除。
|
||||
"""
|
||||
excludes = {normalize_text(x).upper() for x in exclude if x}
|
||||
rows = [text] if isinstance(text, str) else list(text)
|
||||
runs: List[str] = []
|
||||
for row in rows:
|
||||
norm = normalize_text(row)
|
||||
cur: List[str] = []
|
||||
for ch in norm:
|
||||
if ch.isdigit():
|
||||
cur.append(ch)
|
||||
elif ch in _CONFUSABLE:
|
||||
cur.append(PRIMARY[ch])
|
||||
else:
|
||||
if len(cur) >= 13:
|
||||
runs.append("".join(cur))
|
||||
cur = []
|
||||
if len(cur) >= 13:
|
||||
runs.append("".join(cur))
|
||||
|
||||
seen: Dict[str, CardCandidate] = {}
|
||||
|
||||
def add(no: str, origin: str, edits: int, votes: int = 1) -> None:
|
||||
if no in excludes or _id_like(no) or not prefix_ok(no):
|
||||
return
|
||||
ok = luhn_ok(no)
|
||||
if not ok and origin == "raw":
|
||||
return
|
||||
c = seen.get(no)
|
||||
if c is None:
|
||||
seen[no] = CardCandidate(number=no, digits=len(no), luhn_ok=ok,
|
||||
prefix=no[:6], bank=bin_bank(no),
|
||||
origin=origin, edits=edits, votes=votes)
|
||||
else:
|
||||
c.votes += votes
|
||||
c.luhn_ok = c.luhn_ok or ok
|
||||
|
||||
for run in runs:
|
||||
if run in excludes or _id_like(run) or not prefix_ok(run):
|
||||
continue
|
||||
add(run, "raw", 0)
|
||||
if luhn_ok(run):
|
||||
continue
|
||||
# 歧义位置枚举;只有唯一解才敢认定(多个解 = 不知道错在哪,宁可标人工)
|
||||
if 13 <= len(run) <= 19:
|
||||
solutions = _luhn_repair(run, max_edits=1)
|
||||
for s in solutions:
|
||||
add(s, "repaired", 1)
|
||||
# 多遍 OCR 的「共识」由上层合并;这里只保证数量
|
||||
cands = [c for c in seen.values() if c.luhn_ok]
|
||||
for c in cands:
|
||||
c.score = (4.0 if c.luhn_ok else 0.0) \
|
||||
+ (2.0 if c.digits in want_lengths else 0.0) \
|
||||
+ (1.0 if c.bank else 0.0) \
|
||||
+ 0.5 * min(c.votes, 4) - 0.5 * c.edits
|
||||
return sorted(cands, key=lambda x: -x.score)[:limit]
|
||||
|
||||
|
||||
def _luhn_repair(no: str, max_edits: int = 1) -> List[str]:
|
||||
"""返回「能通过 Luhn 的最少改动解」;多于一个解视为歧义,返回空。
|
||||
|
||||
卡号错一位时,Luhn 往往还能匹配出 5~9 种改法。若无其它证据(例如另一处
|
||||
小字印的同一卡号、卡面 BIN),宁可不认,避免把身份证号「纠」成合法卡号。
|
||||
"""
|
||||
if luhn_ok(no):
|
||||
return [no]
|
||||
found: List[str] = []
|
||||
if max_edits >= 1:
|
||||
for i in range(len(no)):
|
||||
for d in "0123456789":
|
||||
if d == no[i]:
|
||||
continue
|
||||
cand = no[:i] + d + no[i + 1:]
|
||||
if luhn_ok(cand):
|
||||
found.append(cand)
|
||||
if len(found) > 1:
|
||||
return []
|
||||
if max_edits >= 2 and not found:
|
||||
for i in range(len(no)):
|
||||
for j in range(i + 1, len(no)):
|
||||
for d1 in "0123456789":
|
||||
for d2 in "0123456789":
|
||||
cand = no[:i] + d1 + no[i + 1:j] + d2 + no[j + 1:]
|
||||
if luhn_ok(cand):
|
||||
found.append(cand)
|
||||
if len(found) > 1:
|
||||
return []
|
||||
return found
|
||||
|
||||
|
||||
def consensus(numbers: Iterable[str]) -> List[str]:
|
||||
"""多数投票:同长度、逐位取众数(用于多遍 OCR 结果合并)。"""
|
||||
groups: Dict[int, List[str]] = {}
|
||||
for n in numbers:
|
||||
if n.isdigit():
|
||||
groups.setdefault(len(n), []).append(n)
|
||||
out = []
|
||||
for length, items in groups.items():
|
||||
if not items:
|
||||
continue
|
||||
votes = []
|
||||
for i in range(length):
|
||||
counts: Dict[str, int] = {}
|
||||
for it in items:
|
||||
counts[it[i]] = counts.get(it[i], 0) + 1
|
||||
votes.append(max(counts.items(), key=lambda kv: kv[1])[0])
|
||||
cand = "".join(votes)
|
||||
score = sum(1 for it in items if it == cand)
|
||||
if score >= max(2, len(items) // 2 + 1):
|
||||
out.append(cand)
|
||||
return out
|
||||
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "desktopauto"
|
||||
version = "0.4.0"
|
||||
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)"
|
||||
version = "0.5.0"
|
||||
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别、键鼠输入、窗口与进程管理"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
@@ -20,9 +20,18 @@ ocr = [
|
||||
"rapidocr>=3.0",
|
||||
"onnxruntime>=1.16",
|
||||
]
|
||||
# 证件照识别:依赖 OCR + openpyxl(导出核对工作簿)
|
||||
card = [
|
||||
"rapidocr>=3.0",
|
||||
"onnxruntime>=1.16",
|
||||
"openpyxl>=3.1",
|
||||
]
|
||||
report = [
|
||||
"openpyxl>=3.1",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/37du/37duAutomation"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["desktopauto"]
|
||||
packages = ["desktopauto", "desktopauto.cardocr"]
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "desktopauto",
|
||||
"name": "桌面自动化 SDK",
|
||||
"version": "0.4.0",
|
||||
"description": "屏幕识图点击、图像存在判断、OCR 文字坐标、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)",
|
||||
"version": "0.5.0",
|
||||
"description": "屏幕识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别(号码纠错/命中分析)、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)",
|
||||
"provides": [
|
||||
"desktopauto"
|
||||
],
|
||||
|
||||
+22
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "hr_sdk",
|
||||
"version": "0.2.3",
|
||||
"version": "0.2.4",
|
||||
"modules": {
|
||||
"hr_sdk": {
|
||||
"exports": [
|
||||
@@ -41,6 +41,7 @@
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow",
|
||||
"__version__"
|
||||
],
|
||||
@@ -81,6 +82,7 @@
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow",
|
||||
"__version__"
|
||||
],
|
||||
@@ -141,8 +143,10 @@
|
||||
"test_shift",
|
||||
"test_wage",
|
||||
"test_wage_base",
|
||||
"test_wage_import",
|
||||
"test_workflow",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow"
|
||||
],
|
||||
"all": [],
|
||||
@@ -166,6 +170,7 @@
|
||||
"test_shift": "() -> 'None'",
|
||||
"test_wage": "() -> 'None'",
|
||||
"test_wage_base": "() -> 'None'",
|
||||
"test_wage_import": "() -> 'None'",
|
||||
"test_workflow": "() -> 'None'"
|
||||
}
|
||||
},
|
||||
@@ -800,6 +805,22 @@
|
||||
"wage_cards": "(client, staff_id: 'str') -> 'List[dict]'"
|
||||
}
|
||||
},
|
||||
"hr_sdk.wage_import": {
|
||||
"exports": [
|
||||
"HEADERS",
|
||||
"build_xlsx",
|
||||
"import_cards"
|
||||
],
|
||||
"all": [
|
||||
"HEADERS",
|
||||
"build_xlsx",
|
||||
"import_cards"
|
||||
],
|
||||
"signatures": {
|
||||
"build_xlsx": "(rows: 'Iterable[Sequence[Any]]', headers: 'Optional[Sequence[str]]' = None) -> 'bytes'",
|
||||
"import_cards": "(rows: 'Optional[Iterable[Sequence[Any]]]' = None, *, xlsx: 'Optional[bytes]' = None, session: 'Any' = None, cookie_path: 'str' = '', fit_type: 'int' = 1, headless: 'bool' = True, timeout: 'float' = 300, log=<built-in function print>, keep_open: 'bool' = False) -> 'Dict[str, Any]'"
|
||||
}
|
||||
},
|
||||
"hr_sdk.workflow": {
|
||||
"exports": [
|
||||
"DEFAULT_PAGE_SIZE",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
分工:**SDK 出接口,插件出业务**。这里封装登录态访问、查询条件加密、异步导出、
|
||||
分页拉全、模板解析等接口事实;异常判定、店长分组、文案、列名映射、落盘策略留在插件。
|
||||
|
||||
当前版本(0.2.3)覆盖:
|
||||
当前版本(0.2.4)覆盖:
|
||||
|
||||
========================== ==========================================================
|
||||
接口 入口
|
||||
@@ -18,6 +18,7 @@
|
||||
组织机构 :mod:`org`(``rows``)
|
||||
工资待办 / 账套 / 起调薪 :mod:`wage`(``rows`` / ``accounts`` / ``account_items`` /
|
||||
``started`` / ``standards`` / ``submit_start`` / ``submit_change``)
|
||||
工资卡导入(浏览器上下文) :mod:`wage_import`(``build_xlsx`` / ``import_cards``)
|
||||
========================== ==========================================================
|
||||
|
||||
典型用法::
|
||||
@@ -34,10 +35,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.2.3"
|
||||
__version__ = "0.2.4"
|
||||
|
||||
from . import (attach, attendance, auth, client, config, contract, errors, export, imports,
|
||||
ledger, org, query, roster, seal, session, shift, wage, workflow)
|
||||
ledger, org, query, roster, seal, session, shift, wage, wage_import, workflow)
|
||||
from .client import HrClient
|
||||
from .config import HR_BASE_URL, WS_EXPORT_THEME, base_params, cookies_file
|
||||
from .errors import (ApiError, AuthError, CancelledError, ConfigError, ExportTimeoutError,
|
||||
@@ -82,6 +83,7 @@ __all__ = [
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
@@ -13,7 +13,7 @@ import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
from . import attach, attendance, auth, contract, imports, seal, shift, wage, workflow
|
||||
from . import attach, attendance, auth, contract, imports, seal, shift, wage, wage_import, workflow
|
||||
from . import client as client_mod
|
||||
from . import config, errors, export, ledger, org, query, roster, session
|
||||
|
||||
@@ -566,6 +566,33 @@ def test_imports() -> None:
|
||||
"文件缺失抛 ConfigError")
|
||||
|
||||
|
||||
def test_wage_import() -> None:
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
row = ["胡检妹", "51052219830211222X", "胡检妹", "主卡", "51052219830211222X",
|
||||
"工资卡", "招商银行", "", "6214832790329259", "备注"]
|
||||
blob = wage_import.build_xlsx([row])
|
||||
sheet = load_workbook(BytesIO(blob)).active
|
||||
_eq([c.value for c in sheet[1]], list(wage_import.HEADERS), "模板表头固定 10 列")
|
||||
_eq(sheet.title, wage_import.SHEET_NAME, "工作表名")
|
||||
_eq(sheet.cell(row=2, column=9).value, 6214832790329259, "第 9 列卡号写数值")
|
||||
_eq(sheet.cell(row=2, column=9).data_type, "n", "卡号单元格类型为数值(否则报「卡号必须是数字」)")
|
||||
_raises(errors.ConfigError,
|
||||
lambda: wage_import.build_xlsx([row[:8] + ["6214 8327"] + row[9:]]),
|
||||
"卡号非纯数字抛 ConfigError")
|
||||
_raises(errors.ConfigError, lambda: wage_import.build_xlsx([row[:9]]),
|
||||
"列数不是 10 列抛 ConfigError")
|
||||
|
||||
class _Sess:
|
||||
cookies = {"a": "1"}
|
||||
|
||||
cookies = wage_import._cookie_list(_Sess())
|
||||
_eq(cookies[0]["name"], "a", "会话 cookies 转浏览器注入列表")
|
||||
_eq(cookies[0]["domain"], "hr.37du.co", "缺省域名 hr.37du.co")
|
||||
|
||||
|
||||
def test_auth() -> None:
|
||||
import base64 as _b64
|
||||
|
||||
@@ -621,6 +648,7 @@ def main() -> int:
|
||||
("contract", test_contract),
|
||||
("export_pipeline", test_export_pipeline),
|
||||
("imports", test_imports),
|
||||
("wage_import", test_wage_import),
|
||||
("auth", test_auth),
|
||||
]
|
||||
failed = 0
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""工资卡导入(浏览器上下文)。
|
||||
|
||||
为什么不用纯 HTTP
|
||||
----------------
|
||||
``POST {REDSEA}/uploadExtenalData/HrStaffWageCard.mc`` 只负责「接收文件 + 起异步任务」,
|
||||
永远返回 ``{"state":"1","meg":"处理成功"}``;真正的解析/落库由服务端异步任务执行,
|
||||
结果只通过 WS 主题 ``WAGE_BASE_CARD_IMPORT`` 推送。实测:同一个文件,浏览器发起
|
||||
→ 正常导入;requests/curl 发起 → 任务在「开始读取数据」阶段直接抛
|
||||
``over:{"result":"-1","msg":null}``(Cookie/请求头/报文与浏览器逐字节一致仍复现)。
|
||||
该异步任务与浏览器会话(同会话 WS 连接)强绑定,因此这里用 DrissionPage 打开
|
||||
HR 门户,在**页面内**用 ``fetch`` 上传并订阅 WS 读结果。
|
||||
|
||||
接口事实
|
||||
--------
|
||||
- 模板 10 列(固定顺序,第 1 行为表头)::
|
||||
|
||||
*姓名 / *身份证号 / *开户人姓名 / *是否主卡 / *开户人身份证号 /
|
||||
*银行卡类型 / *开卡银行 / 开户支行 / *银行卡号 / 备注
|
||||
|
||||
- **银行卡号必须是数值单元格**,写成文本会报「卡号必须是数字」。
|
||||
- ``fitType``:1=按身份证匹配,2=按工号匹配。
|
||||
- WS 末条消息以 ``over:`` 开头,正文是 JSON::
|
||||
|
||||
{"result":1,"total":1,"successNum":0,"errorNum":1,"state":"1","fileId":"...",
|
||||
"errorList":[{"line":2,"staffName":"..","idCard":"..","meg":"没有与身份证号匹配的人员"}]}
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import wage_import
|
||||
|
||||
rows = [["胡检妹", "51052219830211222X", "胡检妹", "主卡", "51052219830211222X",
|
||||
"工资卡", "招商银行", "", "6214832790329259", "影像核对一致"]]
|
||||
res = wage_import.import_cards(rows, session=client.session, log=print)
|
||||
if res["result"] == 1 and res["errorNum"] == 0:
|
||||
...
|
||||
|
||||
注意:导入要独占一份浏览器 profile(同一时刻只能有一个导入进程)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from io import BytesIO
|
||||
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
||||
|
||||
from .config import HR_BASE_URL
|
||||
from .errors import ConfigError, ExportTimeoutError, HrError
|
||||
|
||||
#: 模板表头(固定顺序,勿改)
|
||||
HEADERS = ["*姓名", "*身份证号", "*开户人姓名", "*是否主卡", "*开户人身份证号",
|
||||
"银行卡类型", "*开卡银行", "开户支行", "*银行卡号", "备注"]
|
||||
|
||||
SHEET_NAME = "工资卡导入模板"
|
||||
UPLOAD_PATH = "/RedseaPlatform/uploadExtenalData/HrStaffWageCard.mc"
|
||||
PORTAL_URL = f"{HR_BASE_URL}/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
WS_THEME = "WAGE_BASE_CARD_IMPORT"
|
||||
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
#: 页面内上传 + 订阅 WS 的脚本(结果写进 window.__result / window.__msgs)
|
||||
_JS_START = """
|
||||
var b64 = arguments[0], fitType = arguments[1], mime = arguments[2], theme = arguments[3], url = arguments[4];
|
||||
window.__msgs = [];
|
||||
window.__result = null;
|
||||
window.__uploadResp = null;
|
||||
(function () {
|
||||
var bin = atob(b64), arr = new Uint8Array(bin.length);
|
||||
for (var i = 0; i < bin.length; i++) { arr[i] = bin.charCodeAt(i); }
|
||||
var ws = new WebSocket('wss://' + location.host + '/RedseaPlatform/ws/service?theme=' + theme);
|
||||
ws.onopen = function () {
|
||||
ws.send(JSON.stringify({theme: theme, code: 'SUBCRIBE_THEME'}));
|
||||
var fd = new FormData();
|
||||
fd.append('importFile', new File([arr], 'wage_cards.xlsx', {type: mime}));
|
||||
fd.append('fitType', String(fitType));
|
||||
fetch(url, {
|
||||
method: 'POST', body: fd,
|
||||
headers: {'Csrf-Token': 'RP', 'X-Requested-With': 'XMLHttpRequest'}
|
||||
}).then(function (r) { return r.text(); }).then(function (t) { window.__uploadResp = t; });
|
||||
};
|
||||
ws.onmessage = function (e) {
|
||||
var txt = e.data;
|
||||
try { txt = JSON.parse(e.data).txt; } catch (err) { }
|
||||
window.__msgs.push(String(txt));
|
||||
if (String(txt).indexOf('over:') === 0) {
|
||||
window.__result = String(txt).slice(5);
|
||||
try { ws.close(); } catch (err) { }
|
||||
}
|
||||
};
|
||||
ws.onerror = function () { window.__msgs.push('[ws-error]'); };
|
||||
window.__ws = ws;
|
||||
})();
|
||||
return 'started';
|
||||
"""
|
||||
|
||||
|
||||
def build_xlsx(rows: Iterable[Sequence[Any]], headers: Optional[Sequence[str]] = None) -> bytes:
|
||||
"""按模板列顺序生成工资卡导入 xlsx(银行卡号强制数值)。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
sh = wb.active
|
||||
sh.title = SHEET_NAME
|
||||
sh.append(list(headers or HEADERS))
|
||||
for row in rows:
|
||||
values = list(row)
|
||||
if len(values) != len(HEADERS):
|
||||
raise ConfigError(f"工资卡导入行需 {len(HEADERS)} 列,实际 {len(values)} 列:{values!r}")
|
||||
# 第 9 列(下标 8)卡号必须是数字,否则服务端报「卡号必须是数字」
|
||||
card = str(values[8]).strip()
|
||||
if card:
|
||||
if not card.isdigit():
|
||||
raise ConfigError(f"银行卡号必须是纯数字:{card!r}")
|
||||
values[8] = int(card)
|
||||
sh.append(values)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _cookie_list(source: Any, cookie_path: str = "") -> List[dict]:
|
||||
"""从 requests 会话 / cookies JSON / 文件路径取 cookie 列表(给浏览器注入)。"""
|
||||
if source is None or isinstance(source, str):
|
||||
path = source if isinstance(source, str) and source else cookie_path
|
||||
if not path:
|
||||
from .config import cookies_file
|
||||
path = cookies_file()
|
||||
if not path or not os.path.exists(path):
|
||||
raise ConfigError(f"未找到 HR 登录态 cookies:{path}")
|
||||
with open(path, encoding="utf-8") as fp:
|
||||
raw = json.load(fp)
|
||||
items = raw.get("cookies") if isinstance(raw, dict) else raw
|
||||
return [c for c in (items or []) if isinstance(c, dict) and c.get("name")]
|
||||
|
||||
cookies = getattr(source, "cookies", source)
|
||||
if isinstance(cookies, dict):
|
||||
return [{"name": k, "value": v, "domain": "hr.37du.co", "path": "/"}
|
||||
for k, v in cookies.items()]
|
||||
out = []
|
||||
for ck in cookies:
|
||||
name = getattr(ck, "name", None) or (ck.get("name") if isinstance(ck, dict) else None)
|
||||
if not name:
|
||||
continue
|
||||
value = getattr(ck, "value", None) if not isinstance(ck, dict) else ck.get("value", "")
|
||||
domain = (getattr(ck, "domain", "") if not isinstance(ck, dict) else ck.get("domain", "")) or "hr.37du.co"
|
||||
path = (getattr(ck, "path", "/") if not isinstance(ck, dict) else ck.get("path", "")) or "/"
|
||||
out.append({"name": name, "value": value or "", "domain": domain, "path": path})
|
||||
return out
|
||||
|
||||
|
||||
def _profile_dir() -> str:
|
||||
base = os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()
|
||||
path = os.path.join(base, "37duAutomation", "_hr_browser")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def import_cards(rows: Optional[Iterable[Sequence[Any]]] = None, *,
|
||||
xlsx: Optional[bytes] = None,
|
||||
session: Any = None, cookie_path: str = "",
|
||||
fit_type: int = 1, headless: bool = True,
|
||||
timeout: float = 300, log=print, keep_open: bool = False) -> Dict[str, Any]:
|
||||
"""导入工资卡并返回服务端结果。
|
||||
|
||||
Args:
|
||||
rows: 数据行(模板 10 列顺序),与 ``xlsx`` 二选一。
|
||||
xlsx: 直接给 xlsx 字节(需自备表头与数值卡号)。
|
||||
session: 借来的 requests 会话(取其中的 cookies 注入浏览器);也可传 cookies JSON 路径。
|
||||
fit_type: 1=按身份证,2=按工号。
|
||||
headless: 是否无头浏览器(无头实测可用)。
|
||||
timeout: 等待导入结果秒数。
|
||||
log: 日志回调。
|
||||
|
||||
Returns:
|
||||
``{"result": 1, "total": n, "successNum": n, "errorNum": n,
|
||||
"errorList": [...], "fileId": "...", "msgs": [...]}``
|
||||
"""
|
||||
log = log or (lambda *_a, **_k: None)
|
||||
if xlsx is None:
|
||||
if rows is None:
|
||||
raise ConfigError("rows 与 xlsx 至少给一个")
|
||||
xlsx = build_xlsx(rows)
|
||||
cookies = _cookie_list(session, cookie_path)
|
||||
b64 = base64.b64encode(xlsx).decode()
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumOptions, ChromiumPage
|
||||
except ImportError: # pragma: no cover
|
||||
raise ConfigError("工资卡导入依赖 DrissionPage(pip install DrissionPage)") from None
|
||||
|
||||
options = ChromiumOptions(read_file=False)
|
||||
options.set_user_data_path(_profile_dir())
|
||||
options.set_argument("--remote-allow-origins=*")
|
||||
if headless:
|
||||
options.headless(True)
|
||||
page = ChromiumPage(options)
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
page.get(PORTAL_URL, timeout=60)
|
||||
if "login" in (page.url or "").lower():
|
||||
raise ConfigError("HR 登录态已失效,请先登录")
|
||||
log(f"[wage_import] 页面就绪:{page.title}")
|
||||
page.run_js(_JS_START, b64, int(fit_type), XLSX_MIME, WS_THEME, UPLOAD_PATH)
|
||||
|
||||
deadline = time.time() + timeout
|
||||
raw = None
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
raw = page.run_js("return window.__result")
|
||||
if raw:
|
||||
break
|
||||
msgs = page.run_js("return window.__msgs") or []
|
||||
upload_resp = page.run_js("return window.__uploadResp") or ""
|
||||
if not raw:
|
||||
raise ExportTimeoutError(
|
||||
f"等待工资卡导入结果超时({timeout}s);上传响应={str(upload_resp)[:120]},消息={msgs[-3:]}")
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except ValueError:
|
||||
raise HrError(f"导入结果无法解析:{raw!r}") from None
|
||||
data["msgs"] = msgs
|
||||
data["upload_resp"] = upload_resp
|
||||
log(f"[wage_import] 结果 result={data.get('result')} 成功 {data.get('successNum')} "
|
||||
f"失败 {data.get('errorNum')}")
|
||||
return data
|
||||
finally:
|
||||
if not keep_open:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
__all__ = ["HEADERS", "build_xlsx", "import_cards"]
|
||||
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "hr_sdk"
|
||||
version = "0.2.3"
|
||||
description = "HR(RedseaPlatform)接口 SDK:通用请求/分页/下载、commonQuery 加密、台账异步导出、花名册/预入职/调动/组织机构、工资账套与起调薪接口"
|
||||
version = "0.2.4"
|
||||
description = "HR(RedseaPlatform)接口 SDK:通用请求/分页/下载、commonQuery 加密、台账异步导出、花名册/预入职/调动/组织机构、工资账套与起调薪接口、工资卡导入(浏览器上下文)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
@@ -13,6 +13,7 @@ dependencies = [
|
||||
"pandas>=1.5",
|
||||
"openpyxl>=3.1",
|
||||
"websocket-client>=1.5",
|
||||
"DrissionPage>=4.1",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
@@ -2,3 +2,4 @@ requests>=2.28
|
||||
pandas>=1.5
|
||||
openpyxl>=3.1
|
||||
websocket-client>=1.5
|
||||
DrissionPage>=4.1
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "hr_sdk",
|
||||
"name": "HR 系统 SDK",
|
||||
"version": "0.2.3",
|
||||
"description": "HR(RedseaPlatform)接口封装:通用请求/分页/下载、commonQuery 条件加密、台账异步导出(bridge+WS)、花名册/预入职/调动/合同台账/组织机构、审批流程(含「全部流程详细数据」导出)、考勤与排班、封存数据、附件下载、工资待办/账套/工资项/起调薪核对与提交、增减员导入(默认 dry-run)、登录原语",
|
||||
"version": "0.2.4",
|
||||
"description": "HR(RedseaPlatform)接口封装:通用请求/分页/下载、commonQuery 条件加密、台账异步导出(bridge+WS)、花名册/预入职/调动/合同台账/组织机构、审批流程(含「全部流程详细数据」导出)、考勤与排班、封存数据、附件下载、工资待办/账套/工资项/起调薪核对与提交、增减员导入(默认 dry-run)、工资卡导入(浏览器上下文 + WS 结果)、登录原语",
|
||||
"provides": [
|
||||
"hr_sdk"
|
||||
],
|
||||
@@ -11,7 +11,8 @@
|
||||
"requests",
|
||||
"pandas",
|
||||
"openpyxl",
|
||||
"websocket"
|
||||
"websocket",
|
||||
"DrissionPage"
|
||||
],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 银行卡更新EHR系统 插件入口(第一阶段)。
|
||||
|
||||
流程编排:
|
||||
1) 读取 AI 表格「银行卡-变更收集表」,筛选「是否更新HR系统 / 收到纸质资料 / 登记日期」
|
||||
任一为空的待处理行;
|
||||
2) 下载银行卡卡号面照片、持卡人身份证照片;
|
||||
3) desktopauto.cardocr 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
4) 输出核对工作簿(核对结果 + 异常名单),识别不出或不一致的推送钉钉群提醒人事手动处理。
|
||||
|
||||
HR 系统「薪资管理-工资数据-工资卡管理」的写入(现金发放/新增/修改主卡、回写
|
||||
「是否更新HR系统=是」)留到后续阶段,本阶段不写 HR、不改 AI 表格。
|
||||
"""
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .logic.runner import run_verify
|
||||
|
||||
|
||||
class BankCardEhrUpdatePlugin(ScenePlugin):
|
||||
"""银行卡变更影像核对 + 后续 EHR 工资卡更新(需求 XQ0084)。"""
|
||||
|
||||
id = "xq0084"
|
||||
name = "银行卡更新EHR系统"
|
||||
version = "0.1.0"
|
||||
description = ("读取人资 AI 表格「银行卡变更收集表」待处理行(是否更新HR系统/收到纸质资料/"
|
||||
"登记日期任一为空),下载银行卡与身份证照片识别卡号、身份证号、姓名、开户银行,"
|
||||
"与表格登记值比对;一致放行,不一致或识别不出进异常名单并提醒人事手动处理。"
|
||||
"当前阶段只核对不写 HR 系统。")
|
||||
platform = ""
|
||||
uses_month = False
|
||||
capabilities = ["xq0084"]
|
||||
permissions = {}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "核对结果工作簿与下载影像的保存目录;每次运行独立留档,按留档份数自动清理旧文件",
|
||||
},
|
||||
"keep_files": {
|
||||
"type": "integer", "title": "结果留档份数",
|
||||
"default": config.DEFAULT_KEEP_FILES,
|
||||
"description": "输出目录最多保留最近 N 份结果工作簿与 N 批影像(含本次);0 = 不清理",
|
||||
},
|
||||
"limit_rows": {
|
||||
"type": "integer", "title": "最多处理条数",
|
||||
"default": 0,
|
||||
"description": "0 = 处理全部待处理记录;调试时可填小数字只跑前几条",
|
||||
},
|
||||
"push_webhook": {
|
||||
"type": "string", "title": "钉钉群机器人 Webhook",
|
||||
"default": "",
|
||||
"description": "留空=只导出不推送;存在异常时推送异常名单摘要(文本,文件需到输出目录自取)",
|
||||
},
|
||||
"push_secret": {
|
||||
"type": "string", "title": "钉钉机器人加签密钥", "format": "password",
|
||||
"default": "",
|
||||
"description": "机器人安全设置为「加签」时填写,未配置加签留空",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
config.set_log(ctx.log)
|
||||
ctx.progress(1)
|
||||
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
keep_files = config.normalize_keep(fields.get("keep_files"))
|
||||
push_webhook = (fields.get("push_webhook") or "").strip()
|
||||
push_secret = fields.get("push_secret") or ""
|
||||
try:
|
||||
limit_rows = max(int(str(fields.get("limit_rows") or 0).strip()), 0)
|
||||
except (TypeError, ValueError):
|
||||
limit_rows = 0
|
||||
|
||||
ctx.log(f"===== 银行卡变更影像核对启动:输出目录 {save_dir}(留档 {keep_files} 份)=====",
|
||||
"INFO")
|
||||
result = run_verify(
|
||||
save_dir=save_dir,
|
||||
keep_files=keep_files,
|
||||
push_webhook=push_webhook,
|
||||
push_secret=push_secret,
|
||||
limit_rows=limit_rows,
|
||||
progress=ctx.progress,
|
||||
)
|
||||
|
||||
stats = result["stats"]
|
||||
if not stats["total"]:
|
||||
return {"summary": "无待处理记录:AI 表格三项缺失字段均无命中",
|
||||
"detail": {"待处理": 0}, "path": ""}
|
||||
|
||||
summary = ("银行卡变更核对完成:共 {total} 条,通过 {passed} / 需人工 {manual} / "
|
||||
"现金发放 {cash}。文件:{path}").format(path=result["path"], **stats)
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
"待处理": stats["total"],
|
||||
"通过": stats["passed"],
|
||||
"需人工": stats["manual"],
|
||||
"现金发放": stats["cash"],
|
||||
"未更新HR系统": stats["trigger"][config.F_DONE],
|
||||
"未收纸质资料": stats["trigger"][config.F_PAPER],
|
||||
"缺登记日期": stats["trigger"][config.F_REG_DATE],
|
||||
"清理历史留档": len(result["cleaned"]),
|
||||
"推送": "成功" if result["push"].get("success") else result["push"].get("message", ""),
|
||||
},
|
||||
"path": result["path"],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(BankCardEhrUpdatePlugin())
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)。
|
||||
|
||||
把插件压成 dist-plugin/xq0084_v<版本>.zip(zip 根含 plugin.json)。
|
||||
排除:__pycache__、_selftest*、本脚本、*.pyc。
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"__pycache__", "debug", ".sessions", "out", "images"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_PREFIXES = ("_selftest",)
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES:
|
||||
continue
|
||||
if p.name.startswith(_EXCLUDE_PREFIXES) or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 判定规则自测(不联网、不依赖底座,仅验证纯逻辑)。
|
||||
|
||||
运行:python -m xq0084._selftest(开发态把插件目录放到 PYTHONPATH 或将本目录
|
||||
临时复制为 plugins/xq0084/)。打包时 `_` 前缀文件会被 _pack.py 排除。
|
||||
"""
|
||||
from .logic.verify import verify
|
||||
|
||||
CARD = "6214832377534396"
|
||||
ID = "500228199001011235"
|
||||
|
||||
|
||||
def _item(card=CARD, id_no=ID, holder="张三", reason="个人原因换新卡", images=("a.jpg",)):
|
||||
row = {
|
||||
"员工姓名.工号": "37000001",
|
||||
"持卡人姓名": holder,
|
||||
"变更原因": reason,
|
||||
"开户银行": "招商银行",
|
||||
"银行卡号": card,
|
||||
"持卡人身份证号": id_no,
|
||||
"是否更新HR系统": "",
|
||||
}
|
||||
return {"row": row, "triggers": ["收到纸质资料"], "images": list(images), "errors": []}
|
||||
|
||||
|
||||
def _ocr(id_no=ID, name="张三", card=CARD, bank="招商银行"):
|
||||
return {"id": {"number": id_no, "name": name},
|
||||
"bank": {"number": card, "bank": bank},
|
||||
"runs": [id_no, card], "errors": []}
|
||||
|
||||
|
||||
def main():
|
||||
cases = [
|
||||
("全部一致", _item(), _ocr(), "通过"),
|
||||
("身份证不一致", _item(), _ocr(id_no="500228199002021235"), "需人工核实"),
|
||||
("卡号读不出", _item(), _ocr(card=""), "需人工核实"),
|
||||
("姓名不一致", _item(), _ocr(name="李四"), "需人工核实"),
|
||||
("开户银行不一致", _item(), _ocr(bank="建设银行"), "需人工核实"),
|
||||
("缺影像", _item(images=()), _ocr(), "需人工核实"),
|
||||
("表格缺卡号", _item(card=""), _ocr(), "需人工核实"),
|
||||
("现金发放跳过核对", _item(card="", reason="银行卡收款异常改“现金发放”"),
|
||||
{}, "现金发放(无需影像核对)"),
|
||||
("多人一行", _item(holder="张三、李四"), _ocr(), "需人工核实"),
|
||||
]
|
||||
failed = 0
|
||||
for name, item, ocr, expect in cases:
|
||||
got = verify(item, ocr)["conclusion"]
|
||||
ok = got == expect
|
||||
failed += 0 if ok else 1
|
||||
print(f"{'OK ' if ok else 'FAIL'} {name}: {got}(期望 {expect})")
|
||||
print(f"完成:{len(cases) - failed}/{len(cases)} 通过")
|
||||
return failed
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,221 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 银行卡更新EHR系统 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖 Python 标准库 / 第三方库 / 执行机挂载的 SDK
|
||||
(desktopauto、dingtalk_sdk),不 import 任何插件包之外的业务代码。
|
||||
|
||||
当前实现范围(第一阶段):
|
||||
1) 从 AI 表格「37°人资领域相关工作台账-银行卡变更收集表」拉取待处理行;
|
||||
2) 下载员工上传的银行卡卡号面照片、持卡人身份证照片;
|
||||
3) 用 desktopauto.cardocr 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
4) 输出核对工作簿;识别不出或不一致的进异常名单,推送钉钉群提醒人事手动处理。
|
||||
HR 系统「薪资管理-工资数据-工资卡管理」的写入留到后续阶段。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
|
||||
# ==================== 钉钉 AI 表格 ====================
|
||||
# 人资 base(XQ0034/XQ0035/XQ0037 同一套);sheet 为「银行卡-变更收集表」
|
||||
AI_BASE = "hr"
|
||||
AI_SHEET = "uavChPe"
|
||||
|
||||
# 企业内部应用凭证(与 XQ0012/XQ0034 同一应用;插件自包含,不读根 .env)
|
||||
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
|
||||
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
|
||||
AITABLE_OPERATOR_UNIONID = "o3mB4s7fjPUtELmYbl5Q3AiEiE" # 人资专用号(固定操作人)
|
||||
|
||||
# 待处理判定:以下任一字段为空即需要处理(用户 2026-11-17 明确口径)
|
||||
PENDING_FIELDS = ("是否更新HR系统", "收到纸质资料", "登记日期")
|
||||
|
||||
# ==================== AI 表格字段名 ====================
|
||||
F_EMP_NAME = "员工姓名" # 人员字段
|
||||
F_EMP_NO = "员工姓名.工号" # 人员字段带出的工号(文本列)
|
||||
F_HOLDER = "持卡人姓名"
|
||||
F_BANK = "开户银行"
|
||||
F_CARD = "银行卡号"
|
||||
F_ID = "持卡人身份证号"
|
||||
F_REASON = "变更原因"
|
||||
F_DONE = "是否更新HR系统"
|
||||
F_PAPER = "收到纸质资料"
|
||||
F_REG_DATE = "登记日期"
|
||||
F_CARD_IMG = "银行卡卡号面照片"
|
||||
F_ID_IMG = "持卡人身份证照片"
|
||||
F_REMARK = "具体说明"
|
||||
F_UNIT = "单位"
|
||||
F_TRUST = "是否委托发放"
|
||||
|
||||
REASON_CASH_KEYWORD = "现金" # 变更原因含「现金」=> 改现金发放,不做影像核对
|
||||
|
||||
# ==================== 输出 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\银行卡更新"
|
||||
RESULT_STEM = "银行卡变更核对结果"
|
||||
IMAGE_DIR_NAME = "images"
|
||||
DEFAULT_KEEP_FILES = 30 # 结果工作簿 + 每批影像目录的留档份数
|
||||
|
||||
_RESULT_FILE_RE = re.compile(rf"^{re.escape(RESULT_STEM)}_(\d{{8}}_\d{{6}})(?:_(\d+))?\.xlsx$")
|
||||
|
||||
SHEET_FULL = "核对结果"
|
||||
SHEET_ABNORMAL = "异常名单"
|
||||
|
||||
|
||||
def blank(value):
|
||||
"""AI 表格字段是否为空(None / 空串 / 空列表 / 空字典)。"""
|
||||
if value is None:
|
||||
return True
|
||||
if isinstance(value, str):
|
||||
return not value.strip()
|
||||
if isinstance(value, (list, dict, tuple, set)):
|
||||
return len(value) == 0
|
||||
return False
|
||||
|
||||
|
||||
def text(value):
|
||||
"""字段值 → 去首尾空白的字符串(列表取首项,dict 取 name/text/value)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, str):
|
||||
return value.strip()
|
||||
if isinstance(value, (int, float)):
|
||||
return str(value).strip()
|
||||
if isinstance(value, dict):
|
||||
for key in ("name", "text", "value", "title"):
|
||||
if value.get(key):
|
||||
return str(value[key]).strip()
|
||||
return ""
|
||||
if isinstance(value, (list, tuple)):
|
||||
parts = [text(v) for v in value]
|
||||
return "、".join(p for p in parts if p)
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def safe_name(value, fallback="未命名"):
|
||||
"""目录/文件名安全化:去掉 Windows 非法字符与换行。"""
|
||||
s = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", text(value) or "")
|
||||
s = s.strip(" ._")
|
||||
return s[:60] or fallback
|
||||
|
||||
|
||||
def build_result_path(save_dir):
|
||||
"""带时间戳的结果工作簿路径,同一秒重复运行追加序号。"""
|
||||
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
path = os.path.join(save_dir, f"{RESULT_STEM}_{stamp}.xlsx")
|
||||
seq = 2
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{RESULT_STEM}_{stamp}_{seq}.xlsx")
|
||||
seq += 1
|
||||
return path
|
||||
|
||||
|
||||
def normalize_keep(value):
|
||||
try:
|
||||
n = int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_KEEP_FILES
|
||||
return max(n, 0)
|
||||
|
||||
|
||||
def cleanup_old_results(save_dir, keep=DEFAULT_KEEP_FILES, protect=None):
|
||||
"""只清理本插件命名规则的历史工作簿,其它文件一律不动。"""
|
||||
if keep <= 0 or not os.path.isdir(save_dir):
|
||||
return []
|
||||
try:
|
||||
names = os.listdir(save_dir)
|
||||
except OSError as e:
|
||||
logger.warning("清理历史结果失败:无法读取目录 %s(%s)", save_dir, e)
|
||||
return []
|
||||
|
||||
files = []
|
||||
for name in names:
|
||||
m = _RESULT_FILE_RE.match(name)
|
||||
if m:
|
||||
files.append(((m.group(1), int(m.group(2) or 1)),
|
||||
os.path.abspath(os.path.join(save_dir, name))))
|
||||
files.sort(key=lambda item: item[0], reverse=True)
|
||||
|
||||
keep_abs = {os.path.abspath(protect)} if protect else set()
|
||||
removed = []
|
||||
for _, full in files:
|
||||
if full in keep_abs:
|
||||
continue
|
||||
if len(keep_abs) < keep:
|
||||
keep_abs.add(full)
|
||||
continue
|
||||
try:
|
||||
os.remove(full)
|
||||
removed.append(os.path.basename(full))
|
||||
except OSError as e:
|
||||
logger.warning("清理历史结果失败:%s(%s)", os.path.basename(full), e)
|
||||
if removed:
|
||||
logger.info("已清理历史结果 %d 份(保留最近 %d 份)", len(removed), keep)
|
||||
return removed
|
||||
|
||||
|
||||
def cleanup_old_images(image_root, keep=DEFAULT_KEEP_FILES, protect=None):
|
||||
"""按批次目录清理历史影像(目录名以 20 开头的时间戳),保留最近 keep 批。"""
|
||||
if keep <= 0 or not os.path.isdir(image_root):
|
||||
return []
|
||||
try:
|
||||
names = [n for n in os.listdir(image_root)
|
||||
if re.match(r"^\d{8}_\d{6}", n) and os.path.isdir(os.path.join(image_root, n))]
|
||||
except OSError as e:
|
||||
logger.warning("清理历史影像失败:无法读取目录 %s(%s)", image_root, e)
|
||||
return []
|
||||
names.sort(reverse=True)
|
||||
keep_abs = {os.path.abspath(protect)} if protect else set()
|
||||
removed = []
|
||||
for name in names:
|
||||
full = os.path.abspath(os.path.join(image_root, name))
|
||||
if full in keep_abs:
|
||||
continue
|
||||
if len(keep_abs) < keep:
|
||||
keep_abs.add(full)
|
||||
continue
|
||||
try:
|
||||
shutil.rmtree(full)
|
||||
removed.append(name)
|
||||
except OSError as e:
|
||||
logger.warning("清理历史影像失败:%s(%s)", name, e)
|
||||
if removed:
|
||||
logger.info("已清理历史影像 %d 批(保留最近 %d 批)", len(removed), keep)
|
||||
return removed
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到底座 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 data 子包。"""
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 数据层:AI 表格读取与影像下载。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from dingtalk_sdk.aitable import AiTable, attachment_items, flatten
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_client():
|
||||
"""创建 AI 表格客户端(凭证内置,不依赖执行机 .env)。"""
|
||||
return AiTable(
|
||||
app_key=config.DINGTALK_APP_KEY,
|
||||
app_secret=config.DINGTALK_APP_SECRET,
|
||||
operator=config.AITABLE_OPERATOR_UNIONID,
|
||||
log=lambda m: config.logger.debug(m),
|
||||
)
|
||||
|
||||
|
||||
def list_pending(cli):
|
||||
"""拉全表并按「是否更新HR系统 / 收到纸质资料 / 登记日期 任一为空」筛选。"""
|
||||
records = cli.records(config.AI_BASE, config.AI_SHEET)
|
||||
items = []
|
||||
for rec in records:
|
||||
fields = rec.get("fields") or {}
|
||||
triggers = [name for name in config.PENDING_FIELDS if config.blank(fields.get(name))]
|
||||
if not triggers:
|
||||
continue
|
||||
row = flatten(rec)
|
||||
holder = config.text(row.get(config.F_HOLDER)) or config.text(row.get(config.F_EMP_NAME))
|
||||
items.append({
|
||||
"record_id": rec.get("id") or rec.get("recordId") or "",
|
||||
"fields": fields,
|
||||
"row": row,
|
||||
"triggers": triggers,
|
||||
"reason": config.text(row.get(config.F_REASON)),
|
||||
"holder": holder,
|
||||
"emp_no": config.text(row.get(config.F_EMP_NO)),
|
||||
"errors": [],
|
||||
"images": [],
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def download_images(cli, item, batch_dir):
|
||||
"""下载一条记录的银行卡/身份证照片到批次目录,返回本地路径列表。"""
|
||||
fields = item["fields"]
|
||||
folder = os.path.join(
|
||||
batch_dir,
|
||||
config.safe_name(f"{item.get('emp_no') or '无工号'}_{item.get('holder') or '无姓名'}"),
|
||||
)
|
||||
saved = []
|
||||
expected = 0
|
||||
for field, prefix in ((config.F_CARD_IMG, "银行卡"), (config.F_ID_IMG, "身份证")):
|
||||
attachments = attachment_items(fields.get(field))
|
||||
expected += len(attachments)
|
||||
if not attachments:
|
||||
continue
|
||||
try:
|
||||
got = cli.download_attachments(fields.get(field), folder,
|
||||
prefix=f"{prefix}_", col=field)
|
||||
except Exception as e: # 预签名过期/网络异常 → 转人工
|
||||
item["errors"].append(f"{field}下载失败:{e}")
|
||||
config.logger.warning("%s %s 下载失败:%s", item.get("emp_no"), field, e)
|
||||
continue
|
||||
for g in got:
|
||||
if g.get("path"):
|
||||
saved.append(g["path"])
|
||||
item["images"] = saved
|
||||
item["expected_images"] = expected
|
||||
item["image_dir"] = folder if saved else ""
|
||||
return saved
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 logic 子包。"""
|
||||
@@ -0,0 +1,92 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 识别层:调用 desktopauto 的银行卡/身份证识别能力。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
|
||||
def _digit_runs(results):
|
||||
runs = []
|
||||
for res in results:
|
||||
for raw in (res.get("raw") or []):
|
||||
runs.extend(raw.get("digit_runs") or [])
|
||||
return runs
|
||||
|
||||
|
||||
def _best(results, kind, prefer):
|
||||
"""在同一条记录的多张照片里取最优识别结果(优先校验通过,其次位数更长)。"""
|
||||
cands = [r.get(kind) or {} for r in results if (r.get(kind) or {})]
|
||||
if not cands:
|
||||
return {}
|
||||
return max(cands, key=lambda c: (1 if c.get(prefer) else 0,
|
||||
len(str(c.get("number") or ""))))
|
||||
|
||||
|
||||
def _enhance(paths, bank_hint):
|
||||
"""常规识别读不出卡号时,用浮雕增强接口兜底(只采信 Luhn 自身合法的高置信结果)。"""
|
||||
try:
|
||||
from desktopauto import read_bank_card_number
|
||||
except Exception: # noqa: BLE001 老版本 SDK 没有该接口
|
||||
return None
|
||||
best = None
|
||||
for path in paths:
|
||||
try:
|
||||
r = read_bank_card_number(path, face_text=bank_hint)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if r.status == "ok":
|
||||
return r
|
||||
if best is None or _erank(r) > _erank(best):
|
||||
best = r
|
||||
return best
|
||||
|
||||
|
||||
def _erank(r):
|
||||
level = {"high": 3, "medium": 2, "low": 1}.get(r.confidence, 0)
|
||||
return (1 if r.luhn_ok else 0, level, len(r.candidates))
|
||||
|
||||
|
||||
def recognize(paths, expected_name=""):
|
||||
"""识别一批照片,合并出身份证/银行卡最佳结果。
|
||||
|
||||
Returns:
|
||||
{"id": {...}, "bank": {...}, "runs": [...], "errors": [...], "files": [...]}
|
||||
"""
|
||||
from desktopauto.cardocr.pipeline import analyze_image
|
||||
|
||||
results, errors = [], []
|
||||
for path in paths:
|
||||
try:
|
||||
results.append(analyze_image(path, expected_name=expected_name))
|
||||
except Exception as e:
|
||||
errors.append(f"{os.path.basename(path)}:{e}")
|
||||
|
||||
idc = _best(results, "id_card", "checksum_ok")
|
||||
bk = _best(results, "bank_card", "luhn_ok")
|
||||
bank = {
|
||||
"number": str(bk.get("number") or ""),
|
||||
"bank": str(bk.get("bank") or ""),
|
||||
"luhn_ok": bool(bk.get("luhn_ok")),
|
||||
}
|
||||
# 常规通道没读到可信卡号:浮雕/反光增强兜底;仍不合法则只留候选,交人工
|
||||
if not bank["luhn_ok"]:
|
||||
enh = _enhance(paths, bank["bank"])
|
||||
if enh is not None and enh.status == "ok":
|
||||
bank.update(number=enh.number, bank=enh.bank or bank["bank"],
|
||||
luhn_ok=True, confidence=enh.confidence, source="enhance")
|
||||
elif enh is not None:
|
||||
bank["confidence"] = enh.confidence
|
||||
# 只有「差 1~2 位就能通过校验」的候选才值得给人看;差太多的是噪声
|
||||
if enh.candidates and enh.candidates[0].get("cost", 9) <= 2:
|
||||
bank["candidates"] = [c["number"] for c in enh.candidates]
|
||||
return {
|
||||
"id": {
|
||||
"number": str(idc.get("number") or ""),
|
||||
"name": str(idc.get("name") or ""),
|
||||
"checksum_ok": bool(idc.get("checksum_ok")),
|
||||
},
|
||||
"bank": bank,
|
||||
"runs": _digit_runs(results),
|
||||
"errors": errors,
|
||||
"files": list(paths),
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 流程编排:拉取待处理行 → 下载影像 → 识别 → 判定 → 输出/提醒。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
from ..data.ai_table import download_images, list_pending, open_client
|
||||
from ..report.notify import send_markdown
|
||||
from ..report.workbook import write_workbook
|
||||
from .recognize import recognize
|
||||
from .verify import verify
|
||||
|
||||
|
||||
def _push_text(rows, stats, path):
|
||||
lines = [
|
||||
"### 银行卡变更影像核对(XQ0084)",
|
||||
f"- 待处理:**{stats['total']}** 条;通过 **{stats['passed']}**、"
|
||||
f"需人工 **{stats['manual']}**、现金发放 **{stats['cash']}**",
|
||||
"- 触发原因:未更新HR系统 {0} / 未收纸质资料 {1} / 缺登记日期 {2}".format(
|
||||
stats["trigger"][config.F_DONE],
|
||||
stats["trigger"][config.F_PAPER],
|
||||
stats["trigger"][config.F_REG_DATE],
|
||||
),
|
||||
]
|
||||
manual = [r for r in rows if r["conclusion"] == "需人工核实"]
|
||||
if manual:
|
||||
lines.append(f"#### 需人工核实({len(manual)})")
|
||||
for r in manual[:20]:
|
||||
lines.append(f"- {r['holder']}({r['emp_no']}):{r['notes'][:120]}")
|
||||
if len(manual) > 20:
|
||||
lines.append(f"- …… 其余 {len(manual) - 20} 条见结果文件")
|
||||
lines.append(f"- 结果文件:{path}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def run_verify(save_dir, keep_files=config.DEFAULT_KEEP_FILES, push_webhook="",
|
||||
push_secret="", limit_rows=0, progress=None):
|
||||
p = progress or (lambda _pct: None)
|
||||
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
image_batch = os.path.join(save_dir, config.IMAGE_DIR_NAME, stamp)
|
||||
os.makedirs(image_batch, exist_ok=True)
|
||||
p(3)
|
||||
|
||||
with open_client() as cli:
|
||||
items = list_pending(cli)
|
||||
config.logger.info("AI 表格待处理记录:%d 条(筛选:%s 任一为空)",
|
||||
len(items), "、".join(config.PENDING_FIELDS))
|
||||
if limit_rows and limit_rows > 0:
|
||||
items = items[:limit_rows]
|
||||
config.logger.info("按配置仅处理前 %d 条", len(items))
|
||||
if not items:
|
||||
return {"path": "", "rows": [], "stats": _stats([], []),
|
||||
"push": {"success": False, "message": "无待处理记录"},
|
||||
"cleaned": [], "batch_dir": image_batch}
|
||||
|
||||
# 1) 先集中下载影像(预签名有效期短,避免识别耗时导致后续地址过期)
|
||||
for i, item in enumerate(items):
|
||||
if config.REASON_CASH_KEYWORD in (item.get("reason") or ""):
|
||||
continue
|
||||
download_images(cli, item, image_batch)
|
||||
p(5 + int(20 * (i + 1) / len(items)))
|
||||
|
||||
# 2) 逐条识别 + 判定
|
||||
rows = []
|
||||
for i, item in enumerate(items):
|
||||
if config.REASON_CASH_KEYWORD in (item.get("reason") or ""):
|
||||
ocr = {}
|
||||
else:
|
||||
ocr = recognize(item.get("images") or [], expected_name=item.get("holder") or "")
|
||||
result = verify(item, ocr)
|
||||
rows.append(result)
|
||||
config.logger.info("%s %s(%s)→ %s%s",
|
||||
result["emp_no"], result["holder"], result["reason"],
|
||||
result["conclusion"],
|
||||
f":{result['notes']}" if result["notes"] else "")
|
||||
p(25 + int(65 * (i + 1) / len(items)))
|
||||
|
||||
stats = _stats(rows, items)
|
||||
path = write_workbook(rows, config.build_result_path(save_dir))
|
||||
p(94)
|
||||
|
||||
cleaned = config.cleanup_old_results(save_dir, keep_files, protect=path)
|
||||
config.cleanup_old_images(os.path.join(save_dir, config.IMAGE_DIR_NAME), keep_files,
|
||||
protect=image_batch)
|
||||
|
||||
push = {"success": False, "message": "无需推送(无异常)"}
|
||||
if stats["manual"] and push_webhook:
|
||||
push = send_markdown(push_webhook, push_secret, "银行卡变更影像核对异常",
|
||||
_push_text(rows, stats, path))
|
||||
p(100)
|
||||
return {"path": path, "rows": rows, "stats": stats, "push": push,
|
||||
"cleaned": cleaned, "batch_dir": image_batch}
|
||||
|
||||
|
||||
def _stats(rows, items):
|
||||
trigger = {name: 0 for name in config.PENDING_FIELDS}
|
||||
for item in items:
|
||||
for name in item.get("triggers") or []:
|
||||
trigger[name] = trigger.get(name, 0) + 1
|
||||
return {
|
||||
"total": len(rows),
|
||||
"passed": sum(1 for r in rows if r.get("conclusion") == "通过"),
|
||||
"manual": sum(1 for r in rows if r.get("conclusion") == "需人工核实"),
|
||||
"cash": sum(1 for r in rows if str(r.get("conclusion", "")).startswith("现金发放")),
|
||||
"trigger": trigger,
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 判定层:表格登记值与影像识别值的一致性核对。
|
||||
|
||||
判定口径(第一阶段,只核对不写 HR):
|
||||
- 一致 => 通过;
|
||||
- 不一致 / 无法识别 / 表格缺关键字段 / 多人一行 => 需人工核实;
|
||||
- 变更原因含「现金」=> 改现金发放,不做影像核对。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from desktopauto.cardocr.match import EXACT, PARTIAL, STRONG, WEAK, coverage, digits
|
||||
from desktopauto.cardocr.validators import bin_bank, id_checksum_ok, luhn_ok
|
||||
|
||||
from .. import config
|
||||
|
||||
LABEL = {EXACT: "一致", STRONG: "高度疑似", PARTIAL: "部分命中", WEAK: "无法识别"}
|
||||
|
||||
# 银行名称归一:去掉公司后缀后按关键字映射到统一简称
|
||||
_BANK_CANON = {
|
||||
"中国工商": "工商", "工商": "工商", "工行": "工商",
|
||||
"中国建设": "建设", "建设": "建设", "建行": "建设",
|
||||
"中国农业": "农业", "农业": "农业", "农行": "农业",
|
||||
"中国银行": "中行", "中行": "中行",
|
||||
"邮政储蓄": "邮储", "邮储": "邮储",
|
||||
"重庆农村商业": "重庆农商", "重庆农商": "重庆农商",
|
||||
"农村商业": "农商", "农村信用": "农商", "农商": "农商",
|
||||
"招商": "招商", "招行": "招商",
|
||||
"浦东发展": "浦发", "浦发": "浦发",
|
||||
"民生": "民生", "兴业": "兴业", "华夏": "华夏", "中信": "中信",
|
||||
"光大": "光大", "平安": "平安", "三峡": "三峡", "交通": "交通",
|
||||
}
|
||||
_BANK_KEYS = sorted(_BANK_CANON, key=len, reverse=True)
|
||||
|
||||
|
||||
def bank_core(name):
|
||||
s = re.sub(r"[\s()()·-]", "", config.text(name))
|
||||
for noise in ("股份有限公司", "有限责任公司", "有限公司", "分行", "支行", "银行"):
|
||||
s = s.replace(noise, "")
|
||||
for key in _BANK_KEYS:
|
||||
if key in s:
|
||||
return _BANK_CANON[key]
|
||||
return s
|
||||
|
||||
|
||||
def compare_bank(table_bank, ocr_bank):
|
||||
a, b = bank_core(table_bank), bank_core(ocr_bank)
|
||||
if not config.text(table_bank):
|
||||
return "表格缺失"
|
||||
if not b:
|
||||
return "无法识别"
|
||||
return "一致" if a == b else "不一致"
|
||||
|
||||
|
||||
def _status(value, truth, runs, card_mode, id_digits=""):
|
||||
"""用 match.coverage 判定识别值与登记值的命中程度。"""
|
||||
if not truth:
|
||||
return "表格缺失"
|
||||
if not value and not runs:
|
||||
return "无法识别"
|
||||
_cov, status, _run = coverage(truth, list(runs) + ([value] if value else []),
|
||||
card_mode=card_mode, id_digits=id_digits)
|
||||
return LABEL.get(status, "无法识别")
|
||||
|
||||
|
||||
def _is_multi(holder, table_id):
|
||||
return bool(re.search(r"[、,,;;/]", holder or "")) or bool(re.search(r"[\r\n、,,;;/]", table_id or ""))
|
||||
|
||||
|
||||
def verify(item, ocr):
|
||||
"""比对一条记录,返回核对结果 dict(字段见 report 输出列)。"""
|
||||
row = item.get("row") or {}
|
||||
holder = config.text(row.get(config.F_HOLDER))
|
||||
reason = config.text(row.get(config.F_REASON))
|
||||
table_card = digits(config.text(row.get(config.F_CARD)))
|
||||
table_id = digits(config.text(row.get(config.F_ID)))
|
||||
table_bank = config.text(row.get(config.F_BANK))
|
||||
done = config.text(row.get(config.F_DONE))
|
||||
|
||||
base = {
|
||||
"emp_no": config.text(row.get(config.F_EMP_NO)),
|
||||
"holder": holder or config.text(row.get(config.F_EMP_NAME)),
|
||||
"reason": reason,
|
||||
"triggers": "、".join(item.get("triggers") or []),
|
||||
"table_bank": table_bank,
|
||||
"table_card": table_card,
|
||||
"table_id": table_id,
|
||||
"ocr_id": "",
|
||||
"ocr_name": "",
|
||||
"ocr_card": "",
|
||||
"ocr_bank": "",
|
||||
"id_status": "-",
|
||||
"name_status": "-",
|
||||
"card_status": "-",
|
||||
"bank_status": "-",
|
||||
"self_check": "",
|
||||
"conclusion": "",
|
||||
"notes": "",
|
||||
"image_dir": item.get("image_dir") or "",
|
||||
"image_count": len(item.get("images") or []),
|
||||
}
|
||||
|
||||
# 改现金发放:HR 侧只改发放方式,不需要核对新卡影像
|
||||
if config.REASON_CASH_KEYWORD in reason:
|
||||
base["conclusion"] = "现金发放(无需影像核对)"
|
||||
base["notes"] = "变更原因为现金发放,HR 侧改为现金/卡号 0,无需核对银行卡与身份证影像"
|
||||
return base
|
||||
|
||||
runs = list((ocr or {}).get("runs") or [])
|
||||
ocr_id = digits((ocr or {}).get("id", {}).get("number") or "")
|
||||
ocr_name = config.text((ocr or {}).get("id", {}).get("name") or "")
|
||||
ocr_card = digits((ocr or {}).get("bank", {}).get("number") or "")
|
||||
ocr_bank = config.text((ocr or {}).get("bank", {}).get("bank") or "")
|
||||
base.update(ocr_id=ocr_id, ocr_name=ocr_name, ocr_card=ocr_card, ocr_bank=ocr_bank)
|
||||
|
||||
base["id_status"] = _status(ocr_id, table_id, runs, card_mode=False)
|
||||
base["card_status"] = _status(ocr_card, table_card, runs, card_mode=True, id_digits=ocr_id or table_id)
|
||||
if not table_id:
|
||||
base["id_status"] = "表格缺失"
|
||||
if not table_card:
|
||||
base["card_status"] = "表格缺失"
|
||||
|
||||
if not holder:
|
||||
base["name_status"] = "表格缺失"
|
||||
elif not ocr_name:
|
||||
base["name_status"] = "无法识别"
|
||||
elif _is_multi(holder, config.text(row.get(config.F_ID))):
|
||||
base["name_status"] = "多人未拆分"
|
||||
else:
|
||||
base["name_status"] = "一致" if ocr_name.replace(" ", "") == holder.replace(" ", "") else "不一致"
|
||||
base["bank_status"] = compare_bank(table_bank, ocr_bank)
|
||||
|
||||
blockers, notes = [], []
|
||||
if _is_multi(holder, config.text(row.get(config.F_ID))):
|
||||
blockers.append("持卡人为多人/多卡,需人工拆分核对")
|
||||
if not table_card:
|
||||
blockers.append("表格缺银行卡号")
|
||||
if not table_id:
|
||||
blockers.append("表格缺身份证号")
|
||||
if not holder:
|
||||
blockers.append("表格缺持卡人姓名")
|
||||
if not item.get("images"):
|
||||
blockers.append("未上传或未下载到银行卡/身份证影像")
|
||||
if base["id_status"] != "一致":
|
||||
blockers.append(f"身份证号{base['id_status']}")
|
||||
if base["card_status"] != "一致":
|
||||
blockers.append(f"银行卡号{base['card_status']}")
|
||||
if base["name_status"] == "不一致":
|
||||
blockers.append("持卡人姓名不一致")
|
||||
elif base["name_status"] == "无法识别":
|
||||
notes.append("身份证姓名未读出")
|
||||
if base["bank_status"] == "不一致":
|
||||
blockers.append("开户银行不一致")
|
||||
elif base["bank_status"] == "无法识别":
|
||||
notes.append("开户银行未读出")
|
||||
|
||||
# 浮雕/反光卡:增强识别给出若干通过 Luhn 的候选,供人工对照影像确认
|
||||
bank_info = (ocr or {}).get("bank", {})
|
||||
card_cands = bank_info.get("candidates") or []
|
||||
if card_cands and base["card_status"] != "一致":
|
||||
notes.append("卡号未读准,候选:" + "、".join(card_cands[:3]) + "(请对照影像人工确认)")
|
||||
elif bank_info.get("confidence") == "low" and base["card_status"] != "一致":
|
||||
notes.append("卡号反光/浮雕未读准,请对照影像人工录入")
|
||||
|
||||
# 表格自身校验:卡号位数/Luhn/BIN、身份证校验位
|
||||
issues = []
|
||||
if table_card:
|
||||
if len(table_card) not in (16, 18, 19):
|
||||
issues.append(f"卡号位数 {len(table_card)} 异常")
|
||||
else:
|
||||
if not luhn_ok(table_card):
|
||||
issues.append("卡号校验位不通过")
|
||||
guessed = bin_bank(table_card)
|
||||
if guessed and table_bank and bank_core(guessed) != bank_core(table_bank):
|
||||
issues.append(f"卡号 BIN({guessed}) 与开户银行({table_bank}) 不一致")
|
||||
if len(table_id) == 18 and not id_checksum_ok(table_id):
|
||||
issues.append("身份证校验位不通过")
|
||||
blockers.extend(issues)
|
||||
base["self_check"] = ";".join(issues)
|
||||
|
||||
for err in item.get("errors") or []:
|
||||
blockers.append(err)
|
||||
if (ocr or {}).get("errors"):
|
||||
blockers.append("影像识别异常:" + ";".join(ocr["errors"]))
|
||||
|
||||
if done == "是":
|
||||
notes.insert(0, "HR 系统已标记已更新,本次仅核对影像")
|
||||
|
||||
base["conclusion"] = "需人工核实" if blockers else "通过"
|
||||
base["notes"] = ";".join(blockers + notes)
|
||||
return base
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0084",
|
||||
"name": "银行卡更新EHR系统",
|
||||
"version": "0.1.0",
|
||||
"description": "读取人资 AI 表格「银行卡变更收集表」待处理行(是否更新HR系统/收到纸质资料/登记日期任一为空),下载银行卡与身份证照片识别卡号、身份证号、姓名、开户银行并比对;不一致或识别不出进异常名单提醒人事手动处理。当前阶段只核对不写 HR 系统。",
|
||||
"category": "人事薪酬",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": false,
|
||||
"capabilities": ["xq0084"],
|
||||
"permissions": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"desktopauto": {
|
||||
"compat": "^0.5"
|
||||
},
|
||||
"dingtalk_sdk": {
|
||||
"compat": "^0.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\银行卡更新",
|
||||
"description": "核对结果工作簿与下载影像的保存目录;每次运行独立留档,按留档份数自动清理旧文件"
|
||||
},
|
||||
"keep_files": {
|
||||
"type": "integer",
|
||||
"title": "结果留档份数",
|
||||
"default": 30,
|
||||
"description": "输出目录最多保留最近 N 份结果工作簿与 N 批影像(含本次);0 = 不清理"
|
||||
},
|
||||
"limit_rows": {
|
||||
"type": "integer",
|
||||
"title": "最多处理条数",
|
||||
"default": 0,
|
||||
"description": "0 = 处理全部待处理记录;调试时可填小数字只跑前几条"
|
||||
},
|
||||
"push_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉群机器人 Webhook",
|
||||
"default": "",
|
||||
"description": "留空=只导出不推送;存在异常时推送异常名单摘要(文本,文件需到输出目录自取)"
|
||||
},
|
||||
"push_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉机器人加签密钥",
|
||||
"format": "password",
|
||||
"default": "",
|
||||
"description": "机器人安全设置为「加签」时填写,未配置加签留空"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 report 子包。"""
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 提醒层:钉钉群机器人 Markdown 推送(仅标准库 + 项目级重试)。"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from ..config import logger
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"),
|
||||
digestmod=hashlib.sha256).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=""):
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = "&" if "?" in webhook else "?"
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
def send_markdown(webhook, secret, title, text):
|
||||
"""向群机器人推送 Markdown;webhook 为空时跳过。"""
|
||||
webhook = (webhook or "").strip()
|
||||
if not webhook:
|
||||
return {"success": False, "message": "未配置 Webhook,跳过推送"}
|
||||
payload = {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": title or "通知", "text": text or ""},
|
||||
}
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
url = _build_url(webhook, (secret or "").strip())
|
||||
last_err = ""
|
||||
for attempt in range(1, DEFAULT_RETRY_TIMES + 1):
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, data=body, method="POST",
|
||||
headers={"Content-Type": "application/json; charset=utf-8"})
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT) as resp:
|
||||
raw = resp.read().decode("utf-8", errors="replace")
|
||||
data = json.loads(raw) if raw else {}
|
||||
if data.get("errcode") == 0:
|
||||
logger.info("钉钉群消息推送成功")
|
||||
return {"success": True, "message": "ok"}
|
||||
last_err = f"errcode={data.get('errcode')} errmsg={data.get('errmsg')}"
|
||||
except Exception as e:
|
||||
last_err = str(e)
|
||||
logger.warning("钉钉推送第 %d/%d 次失败:%s", attempt, DEFAULT_RETRY_TIMES, last_err)
|
||||
if attempt < DEFAULT_RETRY_TIMES:
|
||||
time.sleep(1.0 * attempt)
|
||||
return {"success": False, "message": last_err}
|
||||
@@ -0,0 +1,79 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 输出层:核对结果工作簿。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from .. import config
|
||||
|
||||
COLUMNS = [
|
||||
("emp_no", "工号", 11),
|
||||
("holder", "持卡人姓名", 14),
|
||||
("reason", "变更原因", 24),
|
||||
("table_bank", "开户银行(表格)", 18),
|
||||
("table_card", "银行卡号(表格)", 23),
|
||||
("table_id", "身份证号(表格)", 23),
|
||||
("ocr_id", "身份证号(识别)", 23),
|
||||
("ocr_name", "姓名(识别)", 11),
|
||||
("ocr_card", "银行卡号(识别)", 23),
|
||||
("ocr_bank", "开户银行(识别)", 18),
|
||||
("id_status", "身份证核对", 11),
|
||||
("name_status", "姓名核对", 11),
|
||||
("card_status", "卡号核对", 11),
|
||||
("bank_status", "开户银行核对", 13),
|
||||
("self_check", "表格自检", 26),
|
||||
("triggers", "触发原因", 22),
|
||||
("conclusion", "核对结论", 22),
|
||||
("notes", "说明", 60),
|
||||
("image_count", "影像数", 8),
|
||||
("image_dir", "影像目录", 50),
|
||||
]
|
||||
|
||||
_HEAD_FILL = PatternFill("solid", fgColor="1F4E78")
|
||||
_HEAD_FONT = Font(color="FFFFFF", bold=True)
|
||||
_MANUAL_FILL = PatternFill("solid", fgColor="FFF2CC")
|
||||
_PASS_FILL = PatternFill("solid", fgColor="E2EFDA")
|
||||
_CASH_FILL = PatternFill("solid", fgColor="DDEBF7")
|
||||
|
||||
|
||||
def _write_sheet(ws, rows):
|
||||
ws.append([title for _, title, _ in COLUMNS])
|
||||
for col, (_, title, width) in enumerate(COLUMNS, start=1):
|
||||
cell = ws.cell(row=1, column=col)
|
||||
cell.fill = _HEAD_FILL
|
||||
cell.font = _HEAD_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws.column_dimensions[get_column_letter(col)].width = width
|
||||
ws.row_dimensions[1].height = 24
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
for record in rows:
|
||||
ws.append([record.get(key, "") for key, _, _ in COLUMNS])
|
||||
r = ws.max_row
|
||||
for col in range(1, len(COLUMNS) + 1):
|
||||
ws.cell(row=r, column=col).alignment = Alignment(vertical="center", wrap_text=True)
|
||||
conclusion = record.get("conclusion", "")
|
||||
fill = (_MANUAL_FILL if conclusion == "需人工核实"
|
||||
else _CASH_FILL if conclusion.startswith("现金发放") else _PASS_FILL)
|
||||
ws.cell(row=r, column=[k for k, _, _ in COLUMNS].index("conclusion") + 1).fill = fill
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(COLUMNS))}{max(ws.max_row, 1)}"
|
||||
|
||||
|
||||
def write_workbook(rows, path):
|
||||
"""写出「核对结果 / 异常名单」两个 sheet。"""
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.SHEET_FULL
|
||||
_write_sheet(ws, rows)
|
||||
|
||||
abnormal = [r for r in rows if r.get("conclusion") == "需人工核实"]
|
||||
ws2 = wb.create_sheet(config.SHEET_ABNORMAL)
|
||||
_write_sheet(ws2, abnormal)
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
Reference in New Issue
Block a user