- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致 - dingtalk:AI 表格读写与错误封装扩充 - aitable:client/cli/自测与打包配置更新
424 lines
16 KiB
Python
424 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""号码校验与纠错:身份证 18 位校验码、银行卡 Luhn、OCR 易混字符还原。
|
|
|
|
两种号码都自带数学校验位,这让我们能把 OCR 出来的「b214 8338 3071 20bb」
|
|
这类文本,在有限候选里反推出唯一合法号码——这是本模块敢离线跑的关键。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
|
|
|
# ---------------------------------------------------------------- 字符归一
|
|
# OCR 把数字认成字母(或反过来)的常见映射;值是「可能对应的数字」
|
|
_CONFUSABLE: Dict[str, Tuple[str, ...]] = {
|
|
"O": ("0",), "o": ("0",), "D": ("0",),
|
|
"I": ("1",), "l": ("1",), "|": ("1",), "!": ("1",),
|
|
"L": ("1",), "Z": ("2",), "z": ("2",),
|
|
"S": ("5",), "s": ("5",), "$": ("5",),
|
|
"B": ("6", "8"), "b": ("6", "8"),
|
|
"G": ("9", "6"), "g": ("9", "6"), "q": ("9", "6"),
|
|
"A": ("4",), "a": ("4",), "E": ("8",), "e": ("8",),
|
|
"T": ("7",), "t": ("7",), "C": ("0", "6"),
|
|
"X": ("X",), "x": ("X",),
|
|
}
|
|
|
|
PRIMARY: Dict[str, str] = {k: v[0] for k, v in _CONFUSABLE.items()}
|
|
|
|
|
|
def normalize_text(text: str) -> str:
|
|
"""全角转半角、去空白(OCR 常在数字间插空格)。"""
|
|
out = []
|
|
for ch in str(text or ""):
|
|
o = ord(ch)
|
|
if 0xFF01 <= o <= 0xFF5E: # 全角 ASCII
|
|
ch = chr(o - 0xFEE0)
|
|
elif o == 0x3000: # 全角空格
|
|
ch = " "
|
|
out.append(ch)
|
|
return re.sub(r"\s+", "", "".join(out))
|
|
|
|
|
|
def digitize(text: str) -> Tuple[str, List[int]]:
|
|
"""把文本压成数字串(字母按首选映射),并返回「有歧义」的位置下标。"""
|
|
s = normalize_text(text)
|
|
digits, ambiguous = [], []
|
|
for ch in s:
|
|
if ch.isdigit():
|
|
digits.append(ch)
|
|
elif ch in _CONFUSABLE:
|
|
digits.append(PRIMARY[ch])
|
|
if len(_CONFUSABLE[ch]) > 1:
|
|
ambiguous.append(len(digits) - 1)
|
|
return "".join(digits), ambiguous
|
|
|
|
|
|
def digit_runs(text: str, min_len: int = 13) -> List[str]:
|
|
"""从一段文本里抽出连续数字串(允许中间夹易混字母)。"""
|
|
s = normalize_text(text)
|
|
# 把易混字母当数字,再做游程切分
|
|
norm = "".join(PRIMARY.get(c, c) if not c.isdigit() else c for c in s)
|
|
runs = re.findall(r"[0-9]{%d,}" % min_len, norm)
|
|
return runs
|
|
|
|
|
|
# ---------------------------------------------------------------- 身份证
|
|
# 18 位:6 位地址 + 8 位生日 + 3 位顺序 + 1 位校验
|
|
_ID_WEIGHTS = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
|
|
_ID_CHECK = "10X98765432"
|
|
|
|
|
|
def id_checksum_ok(no: str) -> bool:
|
|
if len(no) != 18:
|
|
return False
|
|
if not re.fullmatch(r"\d{17}[\dXx]", no):
|
|
return False
|
|
total = sum(int(no[i]) * _ID_WEIGHTS[i] for i in range(17))
|
|
return _ID_CHECK[total % 11] == no[17].upper()
|
|
|
|
|
|
def id_birth(no: str) -> str:
|
|
"""从身份证号取生日 YYYY-MM-DD(含合法性检查,不合法返回空)。"""
|
|
if len(no) != 18:
|
|
return ""
|
|
y, m, d = int(no[6:10]), int(no[10:12]), int(no[12:14])
|
|
if not (1900 <= y <= 2020) or not (1 <= m <= 12) or not (1 <= d <= 31):
|
|
return ""
|
|
return f"{y:04d}-{m:02d}-{d:02d}"
|
|
|
|
|
|
def id_gender(no: str) -> str:
|
|
if len(no) != 18:
|
|
return ""
|
|
return "男" if int(no[16]) % 2 == 1 else "女"
|
|
|
|
|
|
def id_region(no: str) -> str:
|
|
return no[:2] if len(no) == 18 else ""
|
|
|
|
|
|
_VALID_PROVINCE = {f"{i:02d}" for i in range(11, 66)}
|
|
|
|
|
|
def id_plausible(no: str) -> bool:
|
|
return (len(no) == 18
|
|
and id_region(no) in _VALID_PROVINCE
|
|
and bool(id_birth(no)))
|
|
|
|
|
|
@dataclass
|
|
class IdCandidate:
|
|
number: str
|
|
checksum_ok: bool
|
|
origin: str = "raw" # raw / repaired
|
|
edits: int = 0
|
|
score: float = 0.0
|
|
|
|
|
|
def id_candidates(text: Union[str, Sequence[str]], limit: int = 8) -> List[IdCandidate]:
|
|
"""从 OCR 文本里找身份证号候选,并做 1~2 位纠错。
|
|
|
|
text 可以是单段文本,也可以是「行文本列表」(推荐:按行抓,避免跨行串号)。
|
|
"""
|
|
rows = [text] if isinstance(text, str) else list(text)
|
|
seen: Dict[str, IdCandidate] = {}
|
|
|
|
def add(no: str, origin: str, edits: int) -> None:
|
|
no = no.upper()
|
|
if len(no) != 18:
|
|
return
|
|
c = seen.get(no)
|
|
ok = id_checksum_ok(no)
|
|
if c is None or (ok and not c.checksum_ok):
|
|
seen[no] = IdCandidate(no, ok, origin, edits, score=0.0)
|
|
|
|
for row in rows:
|
|
s = normalize_text(row)
|
|
# 原始文本里的 18 位窗口(允许 X 结尾、允许混入易混字母)
|
|
for raw in re.findall(r"[0-9OoIlLZzSBbGgqAaEeTtCc|!]{17}[0-9XxOoIl]", s):
|
|
d, amb = digitize(raw)
|
|
if len(d) == 18:
|
|
add(d, "raw", 0)
|
|
if len(amb) <= 4 and not id_checksum_ok(d):
|
|
for combo in _enumerate_ambiguous(d, amb, limit=200):
|
|
add(combo, "repaired", sum(1 for x, y in zip(d, combo) if x != y))
|
|
# 纯数字窗口(含标签粘连)
|
|
for m in re.finditer(r"\d{17}[\dXx]", s):
|
|
add(m.group(0), "raw", 0)
|
|
if not id_checksum_ok(m.group(0)):
|
|
for combo in _one_digit_sub(m.group(0), limit=200):
|
|
add(combo, "repaired", 1)
|
|
|
|
for c in seen.values():
|
|
c.score = (3.0 if c.checksum_ok else 0.0) + (2.0 if id_plausible(c.number) else 0.0) \
|
|
- 0.5 * c.edits
|
|
return sorted(seen.values(), key=lambda x: -x.score)[:limit]
|
|
|
|
|
|
def _enumerate_ambiguous(digits: str, positions: Sequence[int],
|
|
limit: int = 200) -> List[str]:
|
|
"""在歧义位置枚举替代数字。"""
|
|
out = [digits]
|
|
for pos in positions:
|
|
ch = digits[pos]
|
|
alts = [x for x in _CONFUSABLE.get(ch, ()) if x.isdigit()]
|
|
if len(alts) <= 1:
|
|
continue
|
|
new = []
|
|
for base in out:
|
|
for a in alts:
|
|
new.append(base[:pos] + a + base[pos + 1:])
|
|
out = new[:limit]
|
|
return out
|
|
|
|
|
|
def _one_digit_sub(no: str, limit: int = 200) -> List[str]:
|
|
out = []
|
|
for i in range(len(no)):
|
|
cur = no[i]
|
|
for d in "0123456789":
|
|
if d == cur:
|
|
continue
|
|
cand = no[:i] + d + no[i + 1:]
|
|
if id_checksum_ok(cand) and id_plausible(cand):
|
|
out.append(cand)
|
|
if len(out) >= limit:
|
|
return out
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------- 银行卡
|
|
def luhn_ok(no: str) -> bool:
|
|
if not no or not no.isdigit() or not (13 <= len(no) <= 19):
|
|
return False
|
|
total, alt = 0, False
|
|
for ch in reversed(no):
|
|
d = int(ch)
|
|
if alt:
|
|
d *= 2
|
|
if d > 9:
|
|
d -= 9
|
|
total += d
|
|
alt = not alt
|
|
return total % 10 == 0
|
|
|
|
|
|
def luhn_check_digit(prefix: str) -> str:
|
|
"""给前 n-1 位算 Luhn 校验位。"""
|
|
total, alt = 0, True
|
|
for ch in reversed(prefix):
|
|
d = int(ch)
|
|
if alt:
|
|
d *= 2
|
|
if d > 9:
|
|
d -= 9
|
|
total += d
|
|
alt = not alt
|
|
return str((10 - total % 10) % 10)
|
|
|
|
|
|
@dataclass
|
|
class CardCandidate:
|
|
number: str
|
|
digits: int
|
|
luhn_ok: bool
|
|
prefix: str = ""
|
|
bank: str = ""
|
|
origin: str = "raw" # raw / consensus / repaired
|
|
edits: int = 0
|
|
votes: int = 1
|
|
score: float = 0.0
|
|
|
|
|
|
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断。
|
|
# 与插件 XQ0005「银行卡检查」的已核验工资卡 BIN 对齐(重庆农商/三峡等本地卡种),
|
|
# 同一 BIN 只能对应一家银行,勿重复登记(Python dict 重复键会静默覆盖)。
|
|
BIN_BANK: Dict[str, str] = {
|
|
# 工商银行
|
|
"622200": "中国工商银行", "622202": "中国工商银行", "622203": "中国工商银行",
|
|
"622208": "中国工商银行", "621225": "中国工商银行", "621226": "中国工商银行",
|
|
"955880": "中国工商银行", "955882": "中国工商银行",
|
|
# 农业银行
|
|
"621336": "中国农业银行", "622841": "中国农业银行", "622845": "中国农业银行",
|
|
"622846": "中国农业银行", "622848": "中国农业银行", "622849": "中国农业银行",
|
|
# 建设银行
|
|
"621081": "中国建设银行", "621499": "中国建设银行", "621700": "中国建设银行",
|
|
"622280": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
|
|
# 中国银行
|
|
"456351": "中国银行", "601382": "中国银行", "621660": "中国银行",
|
|
"621661": "中国银行", "621662": "中国银行", "621663": "中国银行",
|
|
"621665": "中国银行", "621785": "中国银行", "621786": "中国银行",
|
|
"621787": "中国银行", "621788": "中国银行", "621789": "中国银行",
|
|
# 招商银行
|
|
"621286": "招商银行", "621483": "招商银行", "621485": "招商银行",
|
|
"621486": "招商银行", "622575": "招商银行", "622576": "招商银行",
|
|
"622577": "招商银行", "622578": "招商银行", "622579": "招商银行",
|
|
"622588": "招商银行", "622609": "招商银行",
|
|
# 民生银行
|
|
"421393": "中国民生银行", "621691": "中国民生银行", "622600": "中国民生银行",
|
|
"622601": "中国民生银行", "622602": "中国民生银行", "622603": "中国民生银行",
|
|
"622615": "中国民生银行", "622617": "中国民生银行", "622619": "中国民生银行",
|
|
"622620": "中国民生银行", "622621": "中国民生银行", "622622": "中国民生银行",
|
|
"622623": "中国民生银行",
|
|
# 兴业银行
|
|
"621084": "兴业银行", "622908": "兴业银行", "622909": "兴业银行",
|
|
# 浦发银行
|
|
"621792": "浦发银行", "621793": "浦发银行", "622516": "浦发银行",
|
|
"622517": "浦发银行", "622518": "浦发银行", "622521": "浦发银行",
|
|
"622522": "浦发银行", "622523": "浦发银行", "622525": "浦发银行",
|
|
"622526": "浦发银行",
|
|
# 交通银行
|
|
"622250": "交通银行", "622251": "交通银行", "622252": "交通银行",
|
|
"622253": "交通银行", "622254": "交通银行", "622255": "交通银行",
|
|
"622260": "交通银行", "622262": "交通银行",
|
|
# 邮储银行
|
|
"620062": "中国邮政储蓄银行", "621095": "中国邮政储蓄银行",
|
|
"622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行",
|
|
"955100": "中国邮政储蓄银行",
|
|
# 中信 / 光大 / 华夏 / 广发 / 平安
|
|
"622690": "中信银行", "622691": "中信银行", "622692": "中信银行",
|
|
"622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行",
|
|
"622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行",
|
|
"623020": "华夏银行",
|
|
"622568": "广发银行",
|
|
"622155": "平安银行", "622156": "平安银行", "622157": "平安银行",
|
|
# 重庆本地(工资卡主力卡种,XQ0005 实际数据核验)
|
|
"621258": "重庆农村商业银行", "621465": "重庆农村商业银行",
|
|
"621528": "重庆农村商业银行", "622867": "重庆农村商业银行",
|
|
"621755": "重庆三峡银行",
|
|
}
|
|
|
|
|
|
def bin_bank(no: str) -> str:
|
|
return BIN_BANK.get(no[:6], "") if len(no) >= 6 else ""
|
|
|
|
|
|
def prefix_ok(no: str) -> bool:
|
|
"""前缀是否像一张国内借记卡:62 开头,或命中已知 BIN(含 4/6/9 开头的老卡)。"""
|
|
return bool(bin_bank(no)) or no.startswith("62")
|
|
|
|
|
|
def _id_like(no: str) -> bool:
|
|
"""18 位且通过身份证校验码、又不是 62 开头 → 基本可判定是身份证号,不是卡号。"""
|
|
return len(no) == 18 and id_checksum_ok(no) and not no.startswith("62")
|
|
|
|
|
|
def card_candidates(text: Union[str, Sequence[str]], want_lengths: Sequence[int] = (16, 19, 18),
|
|
limit: int = 8, exclude: Sequence[str] = ()) -> List[CardCandidate]:
|
|
"""从 OCR 文本里找卡号候选:游程 + 歧义枚举 + Luhn 校验。
|
|
|
|
Args:
|
|
text: 单段文本或「行文本列表」(推荐按行传,避免跨行把两行数字连起来)。
|
|
exclude: 已知的身份证号等「长得像卡号」的号码,直接排除。
|
|
"""
|
|
excludes = {normalize_text(x).upper() for x in exclude if x}
|
|
rows = [text] if isinstance(text, str) else list(text)
|
|
runs: List[str] = []
|
|
for row in rows:
|
|
norm = normalize_text(row)
|
|
cur: List[str] = []
|
|
for ch in norm:
|
|
if ch.isdigit():
|
|
cur.append(ch)
|
|
elif ch in _CONFUSABLE:
|
|
cur.append(PRIMARY[ch])
|
|
else:
|
|
if len(cur) >= 13:
|
|
runs.append("".join(cur))
|
|
cur = []
|
|
if len(cur) >= 13:
|
|
runs.append("".join(cur))
|
|
|
|
seen: Dict[str, CardCandidate] = {}
|
|
|
|
def add(no: str, origin: str, edits: int, votes: int = 1) -> None:
|
|
if no in excludes or _id_like(no) or not prefix_ok(no):
|
|
return
|
|
ok = luhn_ok(no)
|
|
if not ok and origin == "raw":
|
|
return
|
|
c = seen.get(no)
|
|
if c is None:
|
|
seen[no] = CardCandidate(number=no, digits=len(no), luhn_ok=ok,
|
|
prefix=no[:6], bank=bin_bank(no),
|
|
origin=origin, edits=edits, votes=votes)
|
|
else:
|
|
c.votes += votes
|
|
c.luhn_ok = c.luhn_ok or ok
|
|
|
|
for run in runs:
|
|
if run in excludes or _id_like(run) or not prefix_ok(run):
|
|
continue
|
|
add(run, "raw", 0)
|
|
if luhn_ok(run):
|
|
continue
|
|
# 歧义位置枚举;只有唯一解才敢认定(多个解 = 不知道错在哪,宁可标人工)
|
|
if 13 <= len(run) <= 19:
|
|
solutions = _luhn_repair(run, max_edits=1)
|
|
for s in solutions:
|
|
add(s, "repaired", 1)
|
|
# 多遍 OCR 的「共识」由上层合并;这里只保证数量
|
|
cands = [c for c in seen.values() if c.luhn_ok]
|
|
for c in cands:
|
|
c.score = (4.0 if c.luhn_ok else 0.0) \
|
|
+ (2.0 if c.digits in want_lengths else 0.0) \
|
|
+ (1.0 if c.bank else 0.0) \
|
|
+ 0.5 * min(c.votes, 4) - 0.5 * c.edits
|
|
return sorted(cands, key=lambda x: -x.score)[:limit]
|
|
|
|
|
|
def _luhn_repair(no: str, max_edits: int = 1) -> List[str]:
|
|
"""返回「能通过 Luhn 的最少改动解」;多于一个解视为歧义,返回空。
|
|
|
|
卡号错一位时,Luhn 往往还能匹配出 5~9 种改法。若无其它证据(例如另一处
|
|
小字印的同一卡号、卡面 BIN),宁可不认,避免把身份证号「纠」成合法卡号。
|
|
"""
|
|
if luhn_ok(no):
|
|
return [no]
|
|
found: List[str] = []
|
|
if max_edits >= 1:
|
|
for i in range(len(no)):
|
|
for d in "0123456789":
|
|
if d == no[i]:
|
|
continue
|
|
cand = no[:i] + d + no[i + 1:]
|
|
if luhn_ok(cand):
|
|
found.append(cand)
|
|
if len(found) > 1:
|
|
return []
|
|
if max_edits >= 2 and not found:
|
|
for i in range(len(no)):
|
|
for j in range(i + 1, len(no)):
|
|
for d1 in "0123456789":
|
|
for d2 in "0123456789":
|
|
cand = no[:i] + d1 + no[i + 1:j] + d2 + no[j + 1:]
|
|
if luhn_ok(cand):
|
|
found.append(cand)
|
|
if len(found) > 1:
|
|
return []
|
|
return found
|
|
|
|
|
|
def consensus(numbers: Iterable[str]) -> List[str]:
|
|
"""多数投票:同长度、逐位取众数(用于多遍 OCR 结果合并)。"""
|
|
groups: Dict[int, List[str]] = {}
|
|
for n in numbers:
|
|
if n.isdigit():
|
|
groups.setdefault(len(n), []).append(n)
|
|
out = []
|
|
for length, items in groups.items():
|
|
if not items:
|
|
continue
|
|
votes = []
|
|
for i in range(length):
|
|
counts: Dict[str, int] = {}
|
|
for it in items:
|
|
counts[it[i]] = counts.get(it[i], 0) + 1
|
|
votes.append(max(counts.items(), key=lambda kv: kv[1])[0])
|
|
cand = "".join(votes)
|
|
score = sum(1 for it in items if it == cand)
|
|
if score >= max(2, len(items) // 2 + 1):
|
|
out.append(cand)
|
|
return out
|