diff --git a/tests/_compat_da.json b/tests/_compat_da.json new file mode 100644 index 0000000..c4f5840 --- /dev/null +++ b/tests/_compat_da.json @@ -0,0 +1,332 @@ +{ + "schema_version": 1, + "tool_version": "1.0.0", + "sdk": { + "id": "desktopauto", + "version": "0.5.0", + "path": "D:\\work\\code\\37duAutomation\\libs\\desktopauto", + "baseline": "0.4.1" + }, + "python": "3.11.9", + "runtime_version": "", + "classification": "ACCIDENTAL_BREAK", + "exit_code": 1, + "summary": { + "plugins_total": 33, + "checked": 9, + "skipped": 24, + "pass": 1, + "warn": 7, + "fail": 1, + "errors": 2, + "warnings": 7 + }, + "sdk_findings": [], + "api_diff": { + "added": [ + "desktopauto.cardocr.enhance" + ], + "removed": [], + "changed": [] + }, + "plugins": [ + { + "id": "xq0001", + "version": "1.0.1", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0001 排班异常识别", + "declared": { + "hr_sdk": { + "compat": ">=0.1 <0.3" + }, + "dingtalk_sdk": { + "compat": "^0.1" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0002", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0003", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0004", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0005", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0008", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0009", + "version": "1.0.15", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0009 门店上月请休假异常人员名单梳理", + "declared": { + "dingtalk_sdk": { + "compat": "^0.1" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0010", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0011", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0012", + "version": "0.3.5", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0012 EHR预支及支付报酬自动发起ERP付款申请", + "declared": { + "hr_sdk": { + "compat": "^0.2" + }, + "erpsdk": { + "compat": "^0.1" + }, + "printkit": { + "compat": "^0.1" + }, + "dingtalk_sdk": { + "compat": "^0.1" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0013", + "version": "0.1.2", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0013 社保费用申报导出并汇总", + "declared": { + "desktopauto": { + "compat": "^0.5" + } + }, + "status": "PASS", + "findings": [] + }, + { + "id": "xq0020", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0031_xq0032", + "version": "1.1.8", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0031_XQ0032 物料收发与采购订单导出", + "declared": { + "erpsdk": { + "compat": "^0.1" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0033", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0034", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0035", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0036", + "version": "0.1.1", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0036 门店员工起调薪处理", + "declared": { + "hr_sdk": { + "compat": "^0.2" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0037", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0038", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0041", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0042", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0045_xq0046", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0047", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0048", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0052", + "version": "0.7.0", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0052 湖畔储值卡每日导出统计", + "declared": { + "hotel_report": { + "compat": "^0.3" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0065", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0076", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0077", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0078", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0079", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0080", + "status": "SKIP", + "findings": [] + }, + { + "id": "xq0081", + "version": "0.3.4", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0081 金贵系统数据导出", + "declared": { + "hotel_report": { + "compat": "^0.3" + } + }, + "status": "WARN", + "findings": [ + { + "code": "UNUSED_DECLARATION", + "severity": "warning", + "message": "声明了 SDK 但源码里没找到 import(可能动态使用)" + } + ] + }, + { + "id": "xq0084", + "version": "0.1.0", + "dir": "D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0084 银行卡更新EHR系统", + "declared": { + "desktopauto": { + "compat": "^0.5" + }, + "dingtalk_sdk": { + "compat": "^0.1" + } + }, + "status": "FAIL", + "findings": [ + { + "code": "NO_UI", + "severity": "error", + "message": "plugin.json 未声明 ui:true:壳子里没有「插件界面」tab,无法提交参数或触发执行", + "file": "plugin.json", + "suggestion": "补 ui-src(Vue3 + Element Plus,见 docs/插件/插件UI开发规范.md §1)并构建 ui/" + }, + { + "code": "SELFTEST_FAIL", + "severity": "error", + "message": "_selftest 失败: File \"D:\\work\\code\\37duAutomation\\plugins\\XQ0001-0100\\XQ0084 银行卡更新EHR系统\\_selftest.py\", line 7, in | from .logic.verify import verify | ImportError: attempted relative import with no known parent package" + } + ] + } + ] +} \ No newline at end of file diff --git a/tests/aitable_probe/audit_bankcards.py b/tests/aitable_probe/audit_bankcards.py new file mode 100644 index 0000000..772499c --- /dev/null +++ b/tests/aitable_probe/audit_bankcards.py @@ -0,0 +1,360 @@ +# -*- coding: utf-8 -*- +"""交叉核对:AI 表格登记信息(持卡人姓名/身份证号/开户银行/卡号)↔ 照片 OCR 结果。 + +两边都可能错,所以逐字段给出「双源结论」: + + 一致 / 高度疑似 / 部分命中 / 冲突 / 照片未读出 / 表格缺失 + +再用校验位判断「哪一边更可疑」:身份证模 11-2、银行卡 Luhn 都是独立的第三方判据。 + +用法(仓库根): + .venv\\Scripts\\python.exe tests\\aitable_probe\\audit_bankcards.py --json tests\\aitable_probe\\_out\\cardocr_v5.json --limit 10 + .venv\\Scripts\\python.exe tests\\aitable_probe\\audit_bankcards.py --json ... --out 交叉核对表.xlsx +""" +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path +from typing import Dict, List, Optional + +HERE = Path(__file__).resolve().parent +REPO_ROOT = HERE.parents[1] +sys.path.insert(0, str(REPO_ROOT / "libs" / "aitable")) +sys.path.insert(0, str(REPO_ROOT / "libs" / "desktopauto")) + +from openpyxl import Workbook # noqa: E402 +from openpyxl.styles import Alignment, Border, Font, PatternFill, Side # noqa: E402 +from openpyxl.utils import get_column_letter # noqa: E402 + +from aitable.client import AiTable, resolve_base # noqa: E402 +from desktopauto.cardocr.match import digits, coverage # noqa: E402 +from desktopauto.cardocr.validators import bin_bank, id_checksum_ok, luhn_ok # noqa: E402 + +SHEET = "uavChPe" +FIELDS = ("持卡人姓名", "持卡人身份证号", "开户银行", "银行卡号") + +# 开户银行别名归一(表格里常写简称) +BANK_ALIAS = { + "招商银行": "招商银行", "招行": "招商银行", + "中国民生银行": "民生银行", "民生银行": "民生银行", + "中国农业银行": "农业银行", "农业银行": "农业银行", "农行": "农业银行", + "中国工商银行": "工商银行", "工商银行": "工商银行", "工行": "工商银行", + "中国建设银行": "建设银行", "建设银行": "建设银行", "建行": "建设银行", + "中国银行": "中国银行", "中行": "中国银行", + "兴业银行": "兴业银行", "浦发银行": "浦发银行", "交通银行": "交通银行", + "中国邮政储蓄银行": "邮储银行", "邮政储蓄银行": "邮储银行", "邮储银行": "邮储银行", + "中信银行": "中信银行", "中国光大银行": "光大银行", "光大银行": "光大银行", + "华夏银行": "华夏银行", "广发银行": "广发银行", "平安银行": "平安银行", + "重庆农村商业银行": "重庆农商行", "重庆农商行": "重庆农商行", +} + + +def norm_bank(name: str) -> str: + s = re.sub(r"\s+", "", str(name or "")) + return BANK_ALIAS.get(s, s) + + +def emp_name(rec: dict) -> str: + v = (rec.get("fields") or {}).get("员工姓名") + if isinstance(v, list) and v: + return str((v[0] or {}).get("name") or "") + if isinstance(v, dict): + return str(v.get("name") or "") + return "" + + +def compare_id(table_no: str, ocr_no: str) -> tuple[str, str]: + t, o = digits(table_no), digits(ocr_no) + if not t: + return "表格缺失", "" + if not o: + return "照片未读出", "" + if t == o: + return "一致", "表格校验不通过" if not id_checksum_ok(t) else "" + t_ok, o_ok = id_checksum_ok(t), id_checksum_ok(o) + if t_ok and not o_ok: + return "冲突", "表格校验通过、照片号码校验不通过 → 照片疑似有误" + if o_ok and not t_ok: + return "冲突", "照片校验通过、表格号码校验不通过 → 表格疑似有误" + return "冲突", "两边都像真的,需人工核实" + + +def compare_name(table_name: str, ocr_name: str) -> tuple[str, str]: + t = (table_name or "").strip() + o = (ocr_name or "").strip() + if not t: + return "表格缺失", "" + if not o: + return "照片未读出", "" + if t == o: + return "一致", "" + return "冲突", f"表格「{t}」vs 照片「{o}」" + + +def table_bin_mismatch(table_card: str, table_bank: str) -> str: + """表格自己的卡号 BIN 与「开户银行」对不上 → 表格内部自相矛盾。""" + t = digits(table_card) + known = bin_bank(t) + if known and norm_bank(table_bank) and norm_bank(known) != norm_bank(table_bank): + return f"表格卡号 BIN 属{known},与开户银行「{table_bank}」不一致" + return "" + + +def compare_card(table_card: str, ocr_card: str, runs: List[str], id_no: str = "", + table_bank: str = "") -> tuple: + t = digits(table_card) + o = digits(ocr_card) + notes = [x for x in (table_bin_mismatch(table_card, table_bank), + "" if luhn_ok(t) else "表格卡号不通过 Luhn(疑似录入有误)") if x] + if not t: + return "表格缺失", 0.0, ";".join(notes) + if o and t == o: + return "一致", 1.0, ";".join(notes) + if o and o != t: + return "冲突", 0.0, ";".join(notes + ["识别出的卡号与表格不同"]) + # 照片没读出完整卡号 → 用片段比对 + cov, status, run = coverage(t, runs, card_mode=True, id_digits=id_no) + if status == "exact": + return "一致", 1.0, ";".join(notes) + if status == "strong": + return "高度疑似(差 1 位左右)", cov, ";".join(notes) + if status == "partial": + return "部分命中(只见前缀/后缀)", cov, ";".join(notes) + return "照片未读出", cov, ";".join(notes) + + +def compare_bank(table_bank: str, ocr_bank: str) -> tuple[str, str]: + t = norm_bank(table_bank) + o = norm_bank(ocr_bank) + if not t: + return "表格缺失", "" + if not o: + return "照片未读出", "" + if t == o: + return "一致", "" + return "冲突", f"表格「{table_bank}」vs 照片「{ocr_bank}」" + + +def conclusion(statuses: Dict[str, str], table_issue: bool = False) -> str: + """按「身份证号 + 卡号」这两个硬字段决定结论,姓名/银行只做补充。""" + if any("冲突" in v for v in statuses.values()): + return "需人工核实(照片与表格冲突)" + if table_issue: + return "需人工核实(表格卡号可疑)" + core_ok = statuses["身份证"] == "一致" and statuses["卡号"] in ( + "一致", "高度疑似(差 1 位左右)") + if core_ok: + weak = [k for k, v in statuses.items() if "未读出" in v] + return "通过" + (f"({'/'.join(weak)}未读出)" if weak else "") + if statuses["身份证"] == "一致" and "未读出" in statuses["卡号"]: + return "照片卡号不可读,需补拍" + return "需人工核实" + + +def table_only(out_path: str) -> int: + """只体检 AI 表格自身:身份证校验、卡号 Luhn、BIN 与开户银行、重复卡号、缺照片。""" + cli = AiTable() + base, _ = resolve_base("hr") + sheet = cli.resolve_sheet(base, SHEET) + recs = cli.records(base, sheet) + + cards: Dict[str, List[str]] = {} + rows: List[dict] = [] + for rec in recs: + f = rec.get("fields") or {} + name = str(f.get("持卡人姓名") or "") + idn = digits(f.get("持卡人身份证号") or "") + card = digits(f.get("银行卡号") or "") + bank = str(f.get("开户银行") or "") + issues: List[str] = [] + if not idn: + issues.append("身份证号缺失") + elif not id_checksum_ok(idn): + issues.append("身份证校验不通过") + if not card: + issues.append("银行卡号缺失") + else: + if not luhn_ok(card): + issues.append("卡号 Luhn 不通过") + if len(card) not in (16, 18, 19): + issues.append(f"卡号位数 {len(card)}(非 16/18/19)") + b = bin_bank(card) + if b and bank and norm_bank(b) != norm_bank(bank): + issues.append(f"卡号 BIN 属{b},与开户银行「{bank}」不一致") + cards.setdefault(card, []).append(name) + if not (f.get("持卡人身份证照片") or f.get("银行卡卡号面照片")): + issues.append("无照片") + if issues: + rows.append({ + "记录ID": rec.get("id", ""), + "持卡人姓名": name, + "员工姓名": emp_name(rec), + "身份证号": idn, + "银行卡号": card, + "开户银行": bank, + "问题": ";".join(issues), + "照片": "有" if (f.get("持卡人身份证照片") or f.get("银行卡卡号面照片")) else "无", + }) + for card, names in cards.items(): + if len(names) > 1: + rows.append({"记录ID": "", "持卡人姓名": "、".join(names), "员工姓名": "", + "身份证号": "", "银行卡号": card, "开户银行": "", + "问题": f"同一卡号出现在 {len(names)} 条记录里", "照片": ""}) + + wb = Workbook() + ws = wb.active + ws.title = "表格自检问题" + widths = [12, 18, 10, 21, 22, 14, 46, 8] + head_fill = PatternFill("solid", fgColor="C00000") + thin = Side(style="thin", color="BFBFBF") + border = Border(left=thin, right=thin, top=thin, bottom=thin) + for i, w in enumerate(widths, 1): + ws.cell(row=1, column=i, value=list(rows[0].keys())[i - 1] if rows else "") + c = ws.cell(row=1, column=i) + c.font = Font(bold=True, color="FFFFFF", size=10) + c.fill = head_fill + c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) + c.border = border + ws.column_dimensions[get_column_letter(i)].width = w + ws.freeze_panes = "A2" + for r_i, row in enumerate(rows, 2): + for c_i, v in enumerate(row.values(), 1): + c = ws.cell(row=r_i, column=c_i, value=v) + c.border = border + c.alignment = Alignment(horizontal="left", vertical="center") + ws.auto_filter.ref = f"A1:{get_column_letter(len(widths))}{len(rows) + 1}" + out = Path(out_path) + out.parent.mkdir(parents=True, exist_ok=True) + wb.save(out) + + print(f"记录 {len(recs)} 条,命中问题 {len(rows)} 条 → {out}") + counts: Dict[str, int] = {} + for r in rows: + for issue in str(r["问题"]).split(";"): + key = issue.split(" ")[0] + counts[key] = counts.get(key, 0) + 1 + for k, v in counts.items(): + print(f" {k}: {v}") + return 0 + + +def main() -> int: + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: # noqa: BLE001 + pass + ap = argparse.ArgumentParser() + ap.add_argument("--json", default="", help="cardocr scan 输出的 JSON(含照片 OCR 结果)") + ap.add_argument("--table-only", action="store_true", help="只体检表格字段本身,不做照片 OCR") + ap.add_argument("--limit", type=int, default=0, help="只看前 N 条记录(0=全部有照片的)") + ap.add_argument("--out", default=str(HERE / "_out" / "交叉核对表.xlsx")) + args = ap.parse_args() + if args.table_only: + return table_only(args.out) + + persons = {p.get("folder"): p for p in json.load( + open(args.json, encoding="utf-8")).get("persons", [])} + + cli = AiTable() + base, _ = resolve_base("hr") + sheet = cli.resolve_sheet(base, SHEET) + recs = cli.records(base, sheet) + + rows: List[dict] = [] + for rec in recs: + f = rec.get("fields") or {} + if not (f.get("持卡人身份证照片") or f.get("银行卡卡号面照片")): + continue + name = str(f.get("持卡人姓名") or "") + person = persons.get(name) + ocr = {"id": "", "name": "", "card": "", "bank": "", "runs": []} + if person: + idc = person.get("id_card") or {} + bk = person.get("bank_card") or {} + ocr = {"id": idc.get("number") or "", "name": idc.get("name") or "", + "card": bk.get("number") or "", "bank": bk.get("bank") or "", + "runs": [r for raw in (person.get("raw") or []) + for r in (raw.get("digit_runs") or [])]} + + id_status, id_note = compare_id(f.get("持卡人身份证号", ""), ocr["id"]) + name_status, name_note = compare_name(name, ocr["name"]) + card_status, card_cov, card_note = compare_card(f.get("银行卡号", ""), ocr["card"], + ocr["runs"], ocr["id"], + f.get("开户银行", "")) + bank_status, bank_note = compare_bank(f.get("开户银行", ""), ocr["bank"]) + evid = ";".join(x for x in (id_note, name_note, card_note, bank_note) if x) + table_issue = any(k in card_note for k in ("不一致", "Luhn")) + rows.append({ + "记录ID": rec.get("id", ""), + "持卡人姓名(表格)": name, + "员工姓名": emp_name(rec), + "身份证号(表格)": f.get("持卡人身份证号", ""), + "身份证号(照片)": ocr["id"], + "身份证": id_status, + "姓名(照片)": ocr["name"], + "姓名": name_status, + "银行卡号(表格)": f.get("银行卡号", ""), + "银行卡号(照片)": ocr["card"], + "卡号命中率": round(card_cov, 2), + "卡号": card_status, + "开户银行(表格)": f.get("开户银行", ""), + "开户银行(照片)": ocr["bank"], + "开户银行": bank_status, + "结论": conclusion({"身份证": id_status, "姓名": name_status, + "卡号": card_status, "开户银行": bank_status}, + table_issue=table_issue), + "说明": evid, + "照片": ";".join(fn.get("filename", "") for fn in (person or {}).get("files", [])), + }) + if args.limit and len(rows) >= args.limit: + break + + # ---- 写 Excel + wb = Workbook() + ws = wb.active + ws.title = "交叉核对" + head_fill = PatternFill("solid", fgColor="1F4E79") + thin = Side(style="thin", color="BFBFBF") + border = Border(left=thin, right=thin, top=thin, bottom=thin) + widths = [12, 12, 10, 21, 21, 12, 10, 12, 21, 21, 9, 22, 12, 12, 12, 22, 34, 40] + for i, (k, w) in enumerate(zip(rows[0].keys(), widths) if rows else [], 1): + c = ws.cell(row=1, column=i, value=k) + c.font = Font(bold=True, color="FFFFFF", size=10) + c.fill = head_fill + c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) + c.border = border + ws.column_dimensions[get_column_letter(i)].width = w + ws.freeze_panes = "A2" + for r_i, row in enumerate(rows, 2): + for c_i, v in enumerate(row.values(), 1): + c = ws.cell(row=r_i, column=c_i, value=v) + c.border = border + c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=False) + if c_i in (16,): # 结论列高亮 + c.font = Font(bold=True) + ws.auto_filter.ref = f"A1:{get_column_letter(len(widths))}{len(rows) + 1}" + + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + wb.save(out) + + # ---- 控制台摘要 + print(f"记录 {len(rows)} 条 → {out}") + for key in ("身份证", "姓名", "卡号", "开户银行", "结论"): + counts: Dict[str, int] = {} + for r in rows: + counts[r[key]] = counts.get(r[key], 0) + 1 + print(f" {key}: " + ";".join(f"{k} {v}" for k, v in counts.items())) + print("\n需人工核实 / 冲突:") + for r in rows: + if "冲突" in r["结论"] or "疑似" in r["结论"] or "不可读" in r["结论"]: + print(f" {r['持卡人姓名(表格)']:<4} 结论={r['结论']:<18} " + f"卡号={r['卡号']:<22} 说明={r['说明'][:60]}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/aitable_probe/diag_hard.py b/tests/aitable_probe/diag_hard.py new file mode 100644 index 0000000..d339a29 --- /dev/null +++ b/tests/aitable_probe/diag_hard.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +"""诊断:对识别失败的卡面照片做多方向 / 多增强扫描,看卡号像素里到底有没有信息。 + +用法(仓库根): + .venv\\Scripts\\python.exe tests\\aitable_probe\\diag_hard.py +""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO_ROOT = HERE.parents[1] +sys.path.insert(0, str(REPO_ROOT / "libs" / "desktopauto")) + +import numpy as np # noqa: E402 + +from desktopauto.cardocr.engine import lines as ocr # noqa: E402 +from desktopauto.cardocr.img import gray_variants, imread, resize_side, rotate90, to_gray # noqa: E402 +from desktopauto.cardocr.validators import _CONFUSABLE, normalize_text # noqa: E402 + +OUT = HERE / "_out" + +# 识别失败的 4 个卡号样本(真值来自人工核对表) +CASES = [ + ("丁丽", OUT / "丁丽" / "银行卡-丁丽.jpg", "6214832377534461", (0, 3)), + ("李瑞雪", OUT / "李瑞雪" / "银行卡-李瑞雪银行卡.JPG", "6214830893671585", (0,)), + ("李诗灿", OUT / "李诗灿" / "银行卡-e2b49e6270df400c7b027ac7ab760d54db92a644be3243391401f9e8045ed24b.png", + "6214832377534412", (0,)), + ("陈宇欣", OUT / "陈宇欣" / "银行卡-488291ab4cab19369f7102b6b2e9280b3e35ca042e5692c90d3ee220c4dd37f6.png", + "6214832377534396", (0,)), +] + + +def digit_runs(text: str, min_len: int = 6) -> list[str]: + s = normalize_text(text) + norm = "".join(ch if ch.isdigit() else _CONFUSABLE.get(ch, (" ",))[0] for ch in s) + import re # noqa: PLC0415 + + return re.findall(r"[0-9]{%d,}" % min_len, norm) + + +def main() -> int: + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: # noqa: BLE001 + pass + for name, path, truth, rots in CASES: + print(f"\n===== {name} 真值 {truth} =====") + img = imread(str(path)) + print(f" 原图 {img.shape[1]}x{img.shape[0]}") + for k in rots: + rot = rotate90(img, k) + small = resize_side(rot, max_side=1800, min_side=900) + for vname, var in gray_variants(to_gray(small), upscale=1.0): + if vname not in ("gray", "clahe", "blackhat", "otsu_inv", "sharp"): + continue + t0 = time.time() + ls = ocr(var) + hits = [] + for ln in ls: + d = len(digit_runs(ln.text)) + if d or "银行" in ln.text or "Union" in ln.text: + hits.append(ln.text[:40]) + runs = digit_runs(" ".join(ln.text for ln in ls), 8) + print(f" k={k} {vname:9s} {time.time() - t0:4.1f}s 段={len(ls):2d} " + f"数字runs={runs[:3]} 文本={hits[:4]}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/aitable_probe/ocr_probe.py b/tests/aitable_probe/ocr_probe.py new file mode 100644 index 0000000..72979f5 --- /dev/null +++ b/tests/aitable_probe/ocr_probe.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +"""OCR 可行性探针:对已落盘的身份证/银行卡照片跑 RapidOCR,打印原始识别结果。 + +用法(仓库根): + .venv\\Scripts\\python.exe tests\\aitable_probe\\ocr_probe.py # 全部样本 + .venv\\Scripts\\python.exe tests\\aitable_probe\\ocr_probe.py --mark # 额外输出标注图 +""" +from __future__ import annotations + +import argparse +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO_ROOT = HERE.parents[1] +sys.path.insert(0, str(REPO_ROOT / "libs" / "desktopauto")) + +from desktopauto import ocr # noqa: E402 + +OUT = HERE / "_out" +IMG_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} + + +def main() -> int: + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: + pass + ap = argparse.ArgumentParser() + ap.add_argument("--mark", action="store_true", help="输出标注图到 _out_marked/") + ap.add_argument("--min-score", type=float, default=0.0) + args = ap.parse_args() + + files = sorted(p for p in OUT.rglob("*") if p.is_file() and p.suffix.lower() in IMG_EXT) + print(f"待识别 {len(files)} 张图,输出目录 {OUT}") + + t_all = time.time() + marked_dir = OUT.parent / "_out_marked" + for i, p in enumerate(files, 1): + rel = p.relative_to(OUT).as_posix() + t0 = time.time() + try: + items = ocr.recognize(str(p), min_score=args.min_score) + except Exception as e: # noqa: BLE001 + print(f"\n[{i}/{len(files)}] {rel} !! 失败:{e}") + continue + dt = time.time() - t0 + print(f"\n[{i}/{len(files)}] {rel} ({dt:.1f}s, {len(items)} 段)") + for it in items: + print(f" {it.score:.2f} ({it.left},{it.top},{it.width}x{it.height}) {it.text}") + if args.mark: + out = marked_dir / (rel.replace("/", "_") + ".marked.png") + ocr.mark_text(str(p), items, str(out)) + + print(f"\n总耗时 {time.time() - t_all:.1f}s") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/aitable_probe/probe_bankcard_images.py b/tests/aitable_probe/probe_bankcard_images.py new file mode 100644 index 0000000..02af492 --- /dev/null +++ b/tests/aitable_probe/probe_bankcard_images.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +"""探针:用 aitable SDK 的下载能力,把「银行卡-变更收集表」两列照片取到本地。 + +表格:37°人资领域相关工作台账 / hr base(YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA) +sheet:银行卡-变更收集表(uavChPe) +目标列:银行卡卡号面照片、持卡人身份证照片(attachment,预签名 OSS url 约 2h 过期) + +统计全量覆盖情况,并按 --limit 条记录落盘样本(默认 10 人);落盘目录已被 .gitignore 忽略。 + +用法(仓库根): + .venv\\Scripts\\python.exe tests\\aitable_probe\\probe_bankcard_images.py # 全量统计 + 10 人落盘 + .venv\\Scripts\\python.exe tests\\aitable_probe\\probe_bankcard_images.py --limit 0 # 全量落盘 +""" +from __future__ import annotations + +import argparse +import json +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO_ROOT = HERE.parents[1] +sys.path.insert(0, str(REPO_ROOT / "libs" / "aitable")) + +from aitable.client import AiTable, attachment_items, resolve_base # noqa: E402 + +BASE = "hr" +SHEET = "uavChPe" # 银行卡-变更收集表 +FIELDS = {"银行卡卡号面照片": "银行卡-", "持卡人身份证照片": "身份证-"} # 字段 → 文件名前缀 +NAME_FIELD = "持卡人姓名" + + +def main() -> int: + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: + pass + ap = argparse.ArgumentParser() + ap.add_argument("--limit", type=int, default=10, help="落盘记录数(人),0=全量") + ap.add_argument("--out", default=str(HERE / "_out"), help="落盘目录") + args = ap.parse_args() + + out_dir = Path(args.out) + cli = AiTable() + base, _ = resolve_base(BASE) + sheet = cli.resolve_sheet(base, SHEET) + print(f"base={base} sheet={sheet}({SHEET}) 拉记录…") + recs = cli.records(base, sheet) + + stat = {"records": len(recs), "people_with_card": 0, "people_with_id": 0, + "people_with_both": 0, "card_images": 0, "id_images": 0, + "people_downloaded": 0, "downloaded": 0, "failed": 0, + "expired": 0, "size_mismatch": 0, "unknown_kind": 0, "bytes": 0} + details, seen = [], 0 + + for rec in recs: + f = rec.get("fields") or {} + card = attachment_items(f.get("银行卡卡号面照片")) + idc = attachment_items(f.get("持卡人身份证照片")) + stat["card_images"] += len(card) + stat["id_images"] += len(idc) + stat["people_with_card"] += bool(card) + stat["people_with_id"] += bool(idc) + stat["people_with_both"] += bool(card and idc) + + if not (card or idc) or (args.limit and seen >= args.limit): + continue + seen += 1 + stat["people_downloaded"] += 1 + name = str(f.get(NAME_FIELD) or rec.get("id", "")) + folder = out_dir / name + row = {"记录id": rec.get("id", ""), "姓名": name, "files": []} + for field, prefix in FIELDS.items(): + for r in cli.download_attachments(f.get(field), folder, prefix=prefix, col=field): + row["files"].append({k: r.get(k) for k in + ("col", "filename", "ok", "bytes", "kind", + "size_match", "expired", "error")} | + {"path": Path(r["path"]).relative_to(out_dir).as_posix()}) + if r["ok"]: + stat["downloaded"] += 1 + stat["bytes"] += r.get("bytes") or 0 + stat["size_mismatch"] += r.get("size_match") is False + stat["unknown_kind"] += r.get("kind") == "unknown" + elif r.get("expired"): + stat["expired"] += 1 + else: + stat["failed"] += 1 + details.append(row) + + summary = {"base": base, "sheet": SHEET, "sheet_id": sheet, + "fields": list(FIELDS), "stats": stat, + "generated_at": time.strftime("%Y-%m-%d %H:%M:%S")} + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1), + encoding="utf-8") + (out_dir / "details.json").write_text(json.dumps(details, ensure_ascii=False, indent=1), + encoding="utf-8") + + print("\n===== 汇总 =====") + for k, v in stat.items(): + print(f" {k:22s} {v}") + print(f"\n落盘:{stat['downloaded']} 个文件 / {stat['bytes'] / 1024:.0f} KB → {out_dir}") + bad = [x for d in details for x in d["files"] if not x.get("ok")] + for x in bad[:5]: + print(f"[x] {x.get('col')} {x.get('filename')}:{x.get('error')}") + return 0 if not bad else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/download_xq0084_images.py b/tests/download_xq0084_images.py new file mode 100644 index 0000000..aecd297 --- /dev/null +++ b/tests/download_xq0084_images.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +"""把 XQ0084「银行卡-变更收集表」里的全部照片下载到本地。 + +输出(每次全量覆盖式复用目录,同名文件自动追加序号,不会删已有文件): + tests/_out/<工号>_<姓名>/银行卡_*.jpg + tests/_out/<工号>_<姓名>/身份证_*.jpg + tests/_out/_manifest.csv 记录 → 本地文件对照表 + +运行(仓库根目录,本地 .venv): + .venv\\Scripts\\python.exe tests\\download_xq0084_images.py + +说明: + - 凭证 / base / sheet / 字段名全部从插件 config 读取,不在此重复写死; + - 钉钉附件是预签名地址(约 2 小时过期),脚本遇到「已过期」会自动重拉记录再试一次。 +""" +from __future__ import annotations + +import csv +import importlib.util +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +OUT_DIR = ROOT / "tests" / "_out" +CONFIG_FILE = (ROOT / "plugins" / "XQ0001-0100" / "XQ0084 银行卡更新EHR系统" + / "config" / "__init__.py") + +# 插件 SDK 未装进 .venv,这里按仓库目录直接挂上 +sys.path.insert(0, str(ROOT / "libs" / "dingtalk")) + +from dingtalk_sdk.aitable import AiTable, attachment_items, flatten # noqa: E402 + + +def load_config(): + """把插件 config 当普通模块加载(它不 import 插件内其它模块)。""" + spec = importlib.util.spec_from_file_location("xq0084_config", str(CONFIG_FILE)) + if spec is None or spec.loader is None: + raise SystemExit(f"读不到插件配置:{CONFIG_FILE}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def pick_folder(cfg, used: dict, item: dict) -> Path: + """每条记录一个目录:<工号>_<姓名>;同名重复时补记录号后 6 位。""" + base = cfg.safe_name(f"{item['emp_no'] or '无工号'}_{item['holder'] or item['name'] or '无姓名'}") + folder = OUT_DIR / base + if base in used and used[base] != item["record_id"]: + folder = OUT_DIR / f"{base}_{item['record_id'][-6:]}" + used.setdefault(base, item["record_id"]) + return folder + + +def download_batch(cli, cfg, items, used: dict, attempt: int): + """下载一批记录的两个影像字段,返回需要重试的记录 id 集合(预签名过期)。""" + expired: set[str] = set() + for n, item in enumerate(items, 1): + folder = pick_folder(cfg, used, item) + print(f"[{attempt}-{n}/{len(items)}] {item['emp_no'] or '-'} {item['holder'] or item['name'] or '-'}" + f" → {folder.name}") + for field, prefix in ((cfg.F_CARD_IMG, "银行卡"), (cfg.F_ID_IMG, "身份证")): + value = item["fields"].get(field) + if value and not attachment_items(value): + print(f" ! {field} 无直连地址(可能只有相对 resourceUrl),跳过") + if not attachment_items(value): + continue + try: + got = cli.download_attachments(value, folder, prefix=f"{prefix}_", col=field) + except Exception as exc: # noqa: BLE001 单条失败不影响其它人 + item["errors"].append(f"{field}: {exc}") + print(f" ! {field} 失败:{exc}") + continue + for g in got: + if g.get("ok") and g.get("path"): + item["files"].append(g["path"]) + else: + msg = g.get("error") or "未知错误" + item["errors"].append(f"{field}/{g.get('filename')}: {msg}") + print(f" ! {g.get('filename')}:{msg}") + if g.get("expired"): + expired.add(item["record_id"]) + print(f" 已存 {len(item['files'])} 个文件") + return expired + + +def main() -> int: + cfg = load_config() + OUT_DIR.mkdir(parents=True, exist_ok=True) + print(f"表:{cfg.AI_BASE} / {cfg.AI_SHEET}({cfg.PENDING_FIELD} 不过滤,全量下载)") + + cli = AiTable(app_key=cfg.DINGTALK_APP_KEY, app_secret=cfg.DINGTALK_APP_SECRET, + operator=cfg.AITABLE_OPERATOR_UNIONID, log=lambda m: None) + records = cli.records(cfg.AI_BASE, cfg.AI_SHEET) + print(f"记录数:{len(records)}") + + items = [] + for rec in records: + fields = rec.get("fields") or {} + row = flatten(rec) + items.append({ + "record_id": str(rec.get("id") or rec.get("recordId") or ""), + "fields": fields, + "row": row, + "name": cfg.text(row.get(cfg.F_EMP_NAME)), + "emp_no": cfg.text(row.get(cfg.F_EMP_NO)), + "holder": cfg.text(row.get(cfg.F_HOLDER)), + "card": cfg.text(row.get(cfg.F_CARD)), + "id_no": cfg.text(row.get(cfg.F_ID)), + "files": [], + "errors": [], + }) + + expired = download_batch(cli, cfg, items, {}, 1) + if expired: + print(f"有 {len(expired)} 条记录的附件地址过期,重新拉取记录后重试…") + fresh = {str(r.get("id") or ""): r for r in cli.records(cfg.AI_BASE, cfg.AI_SHEET)} + retry = [] + for item in items: + if item["record_id"] in expired and item["record_id"] in fresh: + item["fields"] = fresh[item["record_id"]].get("fields") or {} + item["errors"] = [e for e in item["errors"] if "过期" not in e] + retry.append(item) + if retry: + download_batch(cli, cfg, retry, {}, 2) + + # ---- 对照表(工号/姓名/表格登记卡号 → 本地文件),供后续核对识别准确率 + manifest = OUT_DIR / "_manifest.csv" + with open(manifest, "w", newline="", encoding="utf-8-sig") as f: + w = csv.writer(f) + w.writerow(["记录ID", "工号", "姓名", "持卡人", "银行卡号", "身份证号", + "文件数", "错误", "文件"]) + for item in items: + w.writerow([item["record_id"], item["emp_no"], item["name"], item["holder"], + item["card"], item["id_no"], len(item["files"]), + " | ".join(item["errors"]), " | ".join(item["files"])]) + + total = sum(len(i["files"]) for i in items) + bad = sum(1 for i in items if i["errors"]) + print(f"\n完成:{total} 个文件,{len(items)} 条记录,{bad} 条有错误") + print(f"目录:{OUT_DIR}") + print(f"对照表:{manifest}") + for item in items: + for e in item["errors"]: + print(f" ! {item['emp_no']} {item['holder'] or item['name']}: {e}") + cli.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/prepare_xq0084_dataset.py b/tests/prepare_xq0084_dataset.py new file mode 100644 index 0000000..62a10a9 --- /dev/null +++ b/tests/prepare_xq0084_dataset.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +"""把 tests/_out 里已下载的银行卡照片整理成 PaddleOCR 识别微调数据集。 + +前置:先跑 tests\\download_xq0084_images.py 把影像下载到 tests/_out(含 _manifest.csv)。 + +运行(仓库根目录,本地 .venv): + .venv\\Scripts\\python.exe tests\\prepare_xq0084_dataset.py + +产出: + tests/dataset_v2/train/images/*.jpg 卡号带裁切图 + tests/dataset_v2/train/label.txt 每行「images/xxx.jpg 16位卡号」(PaddleOCR rec 格式) + tests/dataset_v2/val/images/*.jpg + tests/dataset_v2/val/label.txt + tests/dataset_v2/_samples.csv 每张:命中窗口 / 自读 / 与标签吻合度 / 去向 + tests/dataset_v2/_skipped.csv 确实读不出(或标签缺失)的图 + +核心思路 ——「标签反搜裁切窗口」: + 我们已知每条记录的卡号(表里人工处理过,可信),所以不再赌卡号带定位准不准, + 而是:先在「摆正后的卡图 / 原图」上生成一批候选窗口(MSER 文字行 + 文本行 + + 按卡面比例扫的网格),逐窗 OCR,用「读出的数字串 vs 标签」的相似度挑最像的那个窗口。 + 这样裁得对不对有答案兜底,误标风险接近 0;所有窗口都低分的图判为确实不可读。 +""" +from __future__ import annotations + +import csv +import difflib +import importlib.util +import random +import sys +from collections import Counter +from pathlib import Path + +import cv2 +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +OUT_DIR = ROOT / "tests" / "_out" +DATA_DIR = ROOT / "tests" / "dataset_v2" +MANIFEST = OUT_DIR / "_manifest.csv" + +TRAIN_COUNT = 130 # 样本够就正好 130 训练,不够按 8:2 切 +SEED = 20261118 +MIN_SHORT_SIDE = 400 # 原图短边下限:再小卡号字高不足,放大后也是糊的 +PAD_RATIO = 0.04 # 命中窗口四周补一点边 +VERIFY_SCORE = 0.55 # 吻合度 ≥ 该值 = 窗口可信(可直接进训练) +MIN_SCORE = 0.30 # 低于该值 = 所有窗口都不像卡号,判不可读 + +# 卡号带在「摆正卡图」上的网格先验:中心位置 × 高度占比 +_GRID_YC = (0.62, 0.74) +_GRID_H = (0.10,) + +CONFIG_FILE = (ROOT / "plugins" / "XQ0001-0100" / "XQ0084 银行卡更新EHR系统" + / "config" / "__init__.py") +# 只有「已上传 HR 系统」的记录,表格登记卡号才与影像一致,才配当标签 +REQUIRE_HR_DONE = True + +sys.path.insert(0, str(ROOT / "libs" / "desktopauto")) +sys.path.insert(0, str(ROOT / "libs" / "dingtalk")) + +from dingtalk_sdk.aitable import AiTable # noqa: E402 +from desktopauto.cardocr.cards import locate_bank_card # noqa: E402 +from desktopauto.cardocr.enhance import _text_bands, find_number_bands # noqa: E402 +from desktopauto.cardocr.engine import text_line # noqa: E402 +from desktopauto.cardocr.img import apply_exif, imread, to_gray # noqa: E402 +from desktopauto.cardocr.validators import digitize # noqa: E402 + +IMAGE_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"} +LOG_PATH = OUT_DIR / "_build_v2.log" + + +def log(msg: str, **_) -> None: + """控制台 + 落盘双写:重定向/管道时也能随时看进度。""" + print(msg, flush=True) + try: + with open(LOG_PATH, "a", encoding="utf-8") as f: + f.write(msg + "\n") + except OSError: + pass + + +def read_manifest(): + """读下载脚本产出的对照表,返回 [{记录ID, 工号, 姓名, 卡号, 银行卡图[]}, ...]。""" + if not MANIFEST.is_file(): + raise SystemExit(f"找不到 {MANIFEST},请先运行 tests\\download_xq0084_images.py") + rows = [] + with open(MANIFEST, encoding="utf-8-sig", newline="") as f: + for r in csv.DictReader(f): + files = [p.strip() for p in (r.get("文件") or "").split("|") if p.strip()] + rows.append({ + "record_id": (r.get("记录ID") or "").strip(), + "emp_no": r.get("工号") or "", + "name": r.get("姓名") or "", + "card_no": (r.get("银行卡号") or "").strip(), + "cards": [p for p in files if Path(p).name.startswith("银行卡_")], + }) + return rows + + +def load_config(): + spec = importlib.util.spec_from_file_location("xq0084_config", str(CONFIG_FILE)) + if spec is None or spec.loader is None: + raise SystemExit(f"读不到插件配置:{CONFIG_FILE}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def load_hr_done(): + """拉 AI 表,返回 (已上传 HR 的记录 id 集合, {取值: 条数});失败抛异常。""" + cfg = load_config() + cli = AiTable(app_key=cfg.DINGTALK_APP_KEY, app_secret=cfg.DINGTALK_APP_SECRET, + operator=cfg.AITABLE_OPERATOR_UNIONID, log=lambda m: None) + try: + records = cli.records(cfg.AI_BASE, cfg.AI_SHEET) + finally: + cli.close() + dist: Counter = Counter() + done: set[str] = set() + for rec in records: + mark = cfg.text((rec.get("fields") or {}).get(cfg.F_DONE)) + dist[mark or "<空>"] += 1 + # 与插件口径一致:空 / 否 = 尚未上传;其它值(是 等)= 已完成,标签可采信 + if mark and mark not in cfg.PENDING_VALUES: + done.add(str(rec.get("id") or "")) + return done, dict(dist) + + +def label_of(card_no: str) -> str: + digits = "".join(ch for ch in card_no if ch.isdigit()) + return digits if len(digits) in (16, 18, 19) else "" + + +def match_score(read: str, label: str) -> float: + """读出串与标签的吻合度:序列相似度 × 长度惩罚(多读/少读都要扣)。""" + if not read or not label: + return 0.0 + ratio = difflib.SequenceMatcher(None, read, label).ratio() + return ratio * min(len(read), len(label)) / max(len(read), len(label)) + + +def _bands_of(view: np.ndarray, with_grid: bool): + """一个视图上的候选窗口:MSER 文字行 + 文本行(+ 摆正卡图上按比例扫的网格)。""" + gray = to_gray(view) + h, w = gray.shape[:2] + bands = list(find_number_bands(gray)) + bands += list(_text_bands(view)) + if with_grid: + for yc in _GRID_YC: + for hh in _GRID_H: + y1 = int(h * (yc - hh / 2.0)) + y2 = int(h * (yc + hh / 2.0)) + bands.append((int(w * 0.02), max(0, y1), int(w * 0.98), min(h, y2))) + return bands + + +def _cut(gray: np.ndarray, band) -> "np.ndarray | None": + """切窗口并把高度归一到 ~120px(识别网络吃小图更稳,训练时字高也统一)。""" + h, w = gray.shape[:2] + x1, y1, x2, y2 = band + pad = max(4, int((x2 - x1) * PAD_RATIO)) + x1, x2 = max(0, x1 - pad), min(w, x2 + pad) + y1, y2 = max(0, y1 - pad), min(h, y2 + pad) + if x2 - x1 < 80 or y2 - y1 < 16: + return None + crop = gray[y1:y2, x1:x2] + if crop.shape[0] > 160: + scale = 120.0 / crop.shape[0] + crop = cv2.resize(crop, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA) + elif crop.shape[0] < 60: + scale = 120.0 / crop.shape[0] + crop = cv2.resize(crop, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC) + return np.ascontiguousarray(crop) + + +def find_best_crop(img: np.ndarray, label: str): + """在「摆正卡图 / 原图」上逐窗试读,取与标签最吻合的窗口。 + + 返回 (crop 或 None, 吻合度, 自读串, 命中窗口说明)。 + """ + views = [] + card = None + try: + card = locate_bank_card(img) + except Exception: # noqa: BLE001 找卡失败就退回原图 + card = None + if card is not None and card.size: + views.append(("card", card, True)) + views.append(("raw", img, False)) + if card is None: # 找卡失败时补 90/270 度 + views.append(("rot90", np.ascontiguousarray(np.rot90(img, 1)), False)) + views.append(("rot270", np.ascontiguousarray(np.rot90(img, 3)), False)) + + best = (0.0, None, "", "") + for view_name, view, with_grid in views: + gray = to_gray(view) + for band in _bands_of(view, with_grid): + crop = _cut(gray, band) + if crop is None: + continue + read, _ = digitize(text_line(crop)) + score = match_score(read, label) + if score > best[0]: + best = (score, crop, read, f"{view_name} {tuple(int(v) for v in band)}") + if score >= 0.80: # 已很贴合,不再浪费 OCR + return best + return best + + +def safe_stem(name: str) -> str: + return "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in name)[:80] + + +def write_csv(path: Path, rows, fields) -> None: + with open(path, "w", encoding="utf-8-sig", newline="") as f: + w = csv.DictWriter(f, fieldnames=fields) + w.writeheader() + for r in rows: + w.writerow({k: r.get(k, "") for k in fields}) + + +FIELDS = ["工号", "姓名", "源文件", "标签", "吻合度", "自读", "命中窗口", "结果"] + + +def main() -> int: + rows = read_manifest() + DATA_DIR.mkdir(parents=True, exist_ok=True) + samples, skipped = [], [] + + done: set[str] = set() + if REQUIRE_HR_DONE: + try: + done, dist = load_hr_done() + except Exception as exc: # noqa: BLE001 拉不到就不能保证标签可信 + raise SystemExit(f"拉取「是否更新HR系统」失败:{exc}\n" + "(标签准确性依赖该字段;确认网络/凭证后再跑)") + log(f"AI 表「是否更新HR系统」分布:{dist}") + log(f"可用于训练标签(已上传HR)的记录:{len(done)} 条") + if not done: + raise SystemExit("没有任何已上传HR的记录,无法生成可信标签") + rows = [r for r in rows if r["record_id"] in done] + + total = sum(len(r["cards"]) for r in rows) + log(f"参与处理的记录 {len(rows)} 条 / 银行卡图 {total} 张,开始反搜裁切窗口…") + + n = 0 + for row in rows: + emp_no, name, label = row["emp_no"], row["name"], label_of(row["card_no"]) + for path in row["cards"]: + n += 1 + p = Path(path) + rec = {"工号": emp_no, "姓名": name, "源文件": str(p), "标签": label, + "吻合度": "", "自读": "", "命中窗口": "", "结果": ""} + if not label: + rec["结果"] = "登记卡号为空/非法" + skipped.append(rec) + continue + if p.suffix.lower() not in IMAGE_EXT: + rec["结果"] = f"不支持的格式 {p.suffix}" + skipped.append(rec) + continue + try: + img = apply_exif(imread(str(p)), str(p)) + except Exception as exc: # noqa: BLE001 单张坏图不影响整批 + rec["结果"] = f"图片读取失败:{exc}" + skipped.append(rec) + continue + if img is None or img.size == 0: + rec["结果"] = "图片读取失败" + skipped.append(rec) + continue + if min(img.shape[:2]) < MIN_SHORT_SIDE: + rec["结果"] = f"分辨率过低 短边 {min(img.shape[:2])}px" + skipped.append(rec) + continue + + score, crop, read, hit = find_best_crop(img, label) + rec["吻合度"] = f"{score:.2f}" + rec["自读"] = read + rec["命中窗口"] = hit + if crop is None or score < MIN_SCORE: + rec["结果"] = f"所有窗口都不像卡号(最高 {score:.2f})" + skipped.append(rec) + else: + rec["结果"] = "ok" if score >= VERIFY_SCORE else "weak(窗口存疑)" + rec["crop"] = crop + rec["_score"] = score + samples.append(rec) + if n % 5 == 0: + log(f" 进度 {n}/{total},已收集 {len(samples)} 张", flush=True) + + log(f"可用样本 {len(samples)} 张(其中吻合度≥{VERIFY_SCORE} 的 " + f"{sum(1 for s in samples if s['_score'] >= VERIFY_SCORE)} 张),跳过 {len(skipped)} 张") + + if not samples: + write_csv(DATA_DIR / "_skipped.csv", skipped, FIELDS) + raise SystemExit("没有可用样本,检查 _skipped.csv 的原因分布") + + samples.sort(key=lambda s: (-s["_score"], s["工号"])) + random.Random(SEED).shuffle(samples) + train_n = TRAIN_COUNT if len(samples) > TRAIN_COUNT else max(1, int(len(samples) * 0.8)) + train, val = samples[:train_n], samples[train_n:] + log(f"训练集 {len(train)} 张,验证集 {len(val)} 张") + + for split, items in (("train", train), ("val", val)): + (DATA_DIR / split / "images").mkdir(parents=True, exist_ok=True) + with open(DATA_DIR / split / "label.txt", "w", encoding="utf-8") as f: + for i, rec in enumerate(items, 1): + stem = safe_stem(f"{rec['工号'] or '无工号'}_{rec['姓名'] or '无姓名'}_{i}.jpg") + rel = f"images/{stem}" + ok, buf = cv2.imencode(".jpg", rec["crop"], [int(cv2.IMWRITE_JPEG_QUALITY), 95]) + if not ok: + rec["结果"] = "写图失败" + continue + (DATA_DIR / split / rel).write_bytes(buf.tobytes()) + f.write(f"{rel}\t{rec['标签']}\n") + rec["结果"] = f"{rec['结果']} → {split}/{rel}" + + for rec in samples: + rec.pop("crop", None) + rec.pop("_score", None) + write_csv(DATA_DIR / "_samples.csv", samples + skipped, FIELDS) + write_csv(DATA_DIR / "_skipped.csv", skipped, FIELDS) + + log(f"\n数据集:{DATA_DIR}") + log(f" 训练 label:{DATA_DIR / 'train' / 'label.txt'}({len(train)} 行)") + log(f" 验证 label:{DATA_DIR / 'val' / 'label.txt'}({len(val)} 行)") + log(f" 明细:{DATA_DIR / '_samples.csv'};跳过:{DATA_DIR / '_skipped.csv'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())