test: XQ0084 数据集下载/准备脚本与兼容性报告,aitable 探针脚本
This commit is contained in:
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
Reference in New Issue
Block a user