# -*- 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())