diff --git a/.gitignore b/.gitignore index 0bd7f7d..417cbda 100644 --- a/.gitignore +++ b/.gitignore @@ -116,3 +116,13 @@ tests/dataset*/ tests/*_dataset*.zip tests/下载/ tests/downloads/ +# YOLO 标注母本 / 数据集 / 训练产物(银行卡照片属员工隐私材料 + 大体积权重,禁止入库) +tests/yolo/images/ +tests/yolo/dataset/ +tests/yolo/runs/ +tests/yolo/*.pt +tests/yolo/*.onnx +tests/yolo/labels_auto.js +tests/yolo/labels_auto.json +tests/yolo/labels_fixed.json +tests/yolo/_train.log diff --git a/tests/download_xq0084_images.py b/tests/download_xq0084_images.py deleted file mode 100644 index aecd297..0000000 --- a/tests/download_xq0084_images.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- 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 deleted file mode 100644 index 62a10a9..0000000 --- a/tests/prepare_xq0084_dataset.py +++ /dev/null @@ -1,332 +0,0 @@ -# -*- 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())