cardocr(身份证/银行卡分析)与 YOLO 卡面检测模型整体迁入 cardreader,插件不再依赖 desktopauto;常规识别读不出合法卡号时按 balanced→thorough 补读。
166 lines
6.4 KiB
Python
166 lines
6.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0084 识别层:cardreader 常规识别 + 卡面检测补读银行卡号。
|
||
|
||
常规通道(cardreader 的 analyze_image)负责身份证与银行卡的整体识别;
|
||
银行卡号读不出 Luhn 合法值时,再用 cardreader 的 read_card(YOLO 找卡 +
|
||
多视角投票)兜底,仍不行才走浮雕增强候选,最终交人工核对。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
|
||
from .. import config
|
||
|
||
_CONF_RANK = {"high": 3, "medium": 2, "low": 1}
|
||
|
||
#: 卡面检测模块探测结果:None=未探测,False=不可用(依赖缺失,后续不再重试)
|
||
_reader = None
|
||
_reader_failed = False
|
||
|
||
|
||
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 _read_card():
|
||
"""懒加载卡面识别 SDK;未挂载或依赖缺失时降级为只用常规通道。"""
|
||
global _reader, _reader_failed
|
||
if _reader is None and not _reader_failed:
|
||
try:
|
||
from cardreader import read_card
|
||
_reader = read_card
|
||
except Exception as exc: # noqa: BLE001
|
||
_reader_failed = True
|
||
config.logger.warning("卡面识别 SDK(cardreader)不可用,卡号只走常规通道:%s", exc)
|
||
return _reader
|
||
|
||
|
||
def _rank(result):
|
||
return (1 if result.luhn_ok else 0, _CONF_RANK.get(result.confidence, 0),
|
||
int(result.votes or 0))
|
||
|
||
|
||
def _cardreader(paths, prefer=()):
|
||
"""卡面检测补读卡号,返回最优 Result;模块不可用或全部失败返回 None。
|
||
|
||
先 balanced;若检测到银行卡但仍未读出合法卡号,再用 thorough
|
||
(号带掩码密集搜索,专治压印银字/反光)。优先读常规通道已有银行卡痕迹的照片。
|
||
"""
|
||
read_card = _read_card()
|
||
if read_card is None:
|
||
return None
|
||
order = [p for p in paths if p in prefer] + [p for p in paths if p not in prefer]
|
||
best = None
|
||
for path in order:
|
||
try:
|
||
cur = read_card(path, mode="balanced")
|
||
if not cur.luhn_ok and "bank_card" in (cur.kinds or []):
|
||
deep = read_card(path, mode="thorough")
|
||
if _rank(deep) > _rank(cur):
|
||
cur = deep
|
||
except Exception as exc: # noqa: BLE001
|
||
config.logger.warning("卡面检测失败(%s):%s", os.path.basename(str(path)), exc)
|
||
continue
|
||
if best is None or _rank(cur) > _rank(best):
|
||
best = cur
|
||
if cur.luhn_ok and cur.confidence == "high":
|
||
break
|
||
return best
|
||
|
||
|
||
def _enhance(paths, bank_hint):
|
||
"""常规识别读不出卡号时,用浮雕增强接口兜底(只采信 Luhn 自身合法的高置信结果)。"""
|
||
try:
|
||
from cardreader import read_bank_card_number
|
||
except Exception: # noqa: BLE001 依赖缺失时只用常规通道
|
||
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 cardreader 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"]:
|
||
prefer = [p for p, r in zip(paths, results)
|
||
if (r.get("bank_card") or {}).get("number")
|
||
or (r.get("bank_card") or {}).get("bank")]
|
||
extra = _cardreader(paths, prefer)
|
||
if extra is not None and extra.luhn_ok:
|
||
bank.update(number=extra.number, luhn_ok=True,
|
||
confidence=extra.confidence,
|
||
source=f"卡面检测({extra.source or 'detect'},票数 {extra.votes})")
|
||
config.logger.info("卡面检测补读卡号成功:%s(%s,票数 %d)",
|
||
extra.number, extra.confidence, extra.votes)
|
||
else:
|
||
if extra is not None and "bank_card" in (extra.kinds or []):
|
||
bank["confidence"] = "low" # 检测到卡但没读准,交人工对照影像
|
||
# 卡面检测也没读准:再走浮雕增强兜底,仍不合法则只留候选
|
||
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),
|
||
}
|