- hr_sdk.wage_import:DrissionPage 注入 cookie 打开 HR 门户,页面内 WS 订阅 + fetch 上传,解析 over: 结果;build_xlsx 第 9 列卡号强制数值(修复「卡号必须是数字」) - 纯 HTTP 导入不可用:服务端异步任务与浏览器会话强绑定,且前端无轮询接口(已核实),结果通道只能用浏览器上下文 - desktopauto 0.5.0 新增 cardocr:身份证/银行卡 OCR、号码纠错、Luhn 与模 11-2 校验、交叉核对 - 新增插件 XQ0084 银行卡更新EHR系统:AI 表格待处理行 → 影像识别 → 一致性核对/异常名单 - .gitignore 忽略 tests/aitable_probe/_out/(含员工证件照,禁止入库)
187 lines
7.0 KiB
Python
187 lines
7.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""身份证字段抽取:号码 / 姓名 / 性别 / 民族 / 出生 / 住址。"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from typing import Dict, List, Optional, Sequence
|
|
|
|
from .engine import Line, join_text
|
|
from .validators import (IdCandidate, id_birth, id_candidates, id_checksum_ok,
|
|
id_gender, id_plausible, id_region, normalize_text)
|
|
|
|
ID_KEYWORDS = ("公民身份号码", "身份号码", "姓名", "性别", "民族", "出生", "住址",
|
|
"签发机关", "有效期限", "中华人民共和国", "居民身份证")
|
|
|
|
# 这些词不能当姓名
|
|
_NOT_NAME = set(ID_KEYWORDS) | {"男", "女", "汉", "回", "苗", "彝", "壮", "藏", "维吾尔",
|
|
"身份证", "公民", "号码", "地址", "出生日期"}
|
|
|
|
|
|
@dataclass
|
|
class IdCardResult:
|
|
number: str = ""
|
|
checksum_ok: bool = False
|
|
birth: str = ""
|
|
gender: str = ""
|
|
name: str = ""
|
|
ethnicity: str = ""
|
|
address: str = ""
|
|
issue: str = ""
|
|
valid_to: str = ""
|
|
confidence: str = "low" # high / medium / low
|
|
evidence: List[str] = field(default_factory=list)
|
|
candidates: List[dict] = field(default_factory=list)
|
|
found: bool = False
|
|
|
|
def to_dict(self) -> dict:
|
|
return {
|
|
"found": self.found,
|
|
"number": self.number,
|
|
"checksum_ok": self.checksum_ok,
|
|
"birth": self.birth,
|
|
"gender": self.gender,
|
|
"name": self.name,
|
|
"ethnicity": self.ethnicity,
|
|
"address": self.address,
|
|
"issue": self.issue,
|
|
"valid_to": self.valid_to,
|
|
"confidence": self.confidence,
|
|
"evidence": self.evidence,
|
|
"candidates": self.candidates,
|
|
}
|
|
|
|
|
|
def looks_like_id(text: str) -> bool:
|
|
hits = sum(1 for k in ID_KEYWORDS if k in text)
|
|
return hits >= 2 or "公民身份号码" in text or "居民身份证" in text
|
|
|
|
|
|
def _norm_name(s: str) -> str:
|
|
s = normalize_text(s)
|
|
s = re.sub(r"^姓名", "", s)
|
|
s = re.sub(r"[·•.\s]", "", s)
|
|
return s
|
|
|
|
|
|
# 这些词长得像姓名,绝不能当姓名
|
|
_BANK_WORDS = ("银行", "银联", "UNIONPAY", "信用卡", "借记卡", "储蓄卡", "一卡通",
|
|
"有限公司", "保险", "支行", "分行")
|
|
|
|
|
|
def _name_candidate(text: str) -> str:
|
|
t = _norm_name(text)
|
|
if not (2 <= len(t) <= 4 and re.fullmatch(r"[一-龥]+", t)):
|
|
return ""
|
|
if t in _NOT_NAME or any(w in t.upper() for w in _BANK_WORDS):
|
|
return ""
|
|
return t
|
|
|
|
|
|
def _pick_name(lines: Sequence[Line], expected: str, full_text: str) -> str:
|
|
"""姓名优先用外部给的姓名做交叉验证,其次取「姓名」标签旁边那一段 2~4 字中文。"""
|
|
if expected:
|
|
exp = _norm_name(expected)
|
|
if exp and exp in normalize_text(full_text):
|
|
return exp
|
|
# 情况一:OCR 把标签和名字连成一段(「姓名李诗灿」)
|
|
for ln in lines:
|
|
m = re.match(r"姓名([一-龥]{2,4})$", normalize_text(ln.text))
|
|
if m and _name_candidate(m.group(1)):
|
|
return _name_candidate(m.group(1))
|
|
# 情况二:标签和名字是两段,取离「姓名」标签最近的那段中文
|
|
labels = [ln for ln in lines if "姓名" in normalize_text(ln.text)]
|
|
cands = []
|
|
for ln in lines:
|
|
c = _name_candidate(ln.text)
|
|
if not c:
|
|
continue
|
|
for lab in labels:
|
|
d = abs(ln.y_mid - lab.y_mid) * 2.0 + abs(ln.left - lab.right)
|
|
cands.append((d, c))
|
|
if cands:
|
|
cands.sort(key=lambda x: x[0])
|
|
return cands[0][1]
|
|
return ""
|
|
|
|
|
|
def _pick_field(text: str, patterns: Sequence[str]) -> str:
|
|
for pat in patterns:
|
|
m = re.search(pat, text)
|
|
if m:
|
|
return m.group(1)
|
|
return ""
|
|
|
|
|
|
def parse(lines: Sequence[Line], expected_name: str = "",
|
|
full_text: str = "", rows: Optional[Sequence[str]] = None) -> IdCardResult:
|
|
"""从身份证那一面的 OCR 结果里抽字段。"""
|
|
res = IdCardResult()
|
|
text = normalize_text(full_text) if full_text else normalize_text(join_text(lines))
|
|
if not text:
|
|
return res
|
|
|
|
cands: List[IdCandidate] = id_candidates(rows if rows else text)
|
|
if not cands:
|
|
# 逐行再试(号码被拆成两段时)
|
|
for ln in lines:
|
|
cands.extend(id_candidates(ln.text))
|
|
cands = sorted(cands, key=lambda c: -c.score)[:8]
|
|
|
|
if cands:
|
|
top = cands[0]
|
|
res.candidates = [{"number": c.number, "checksum_ok": c.checksum_ok,
|
|
"origin": c.origin, "edits": c.edits,
|
|
"score": round(c.score, 2)} for c in cands]
|
|
res.number = top.number
|
|
res.checksum_ok = top.checksum_ok
|
|
res.birth = id_birth(top.number)
|
|
res.gender = id_gender(top.number)
|
|
res.found = True
|
|
if top.origin == "repaired":
|
|
res.evidence.append(f"号码经 {top.edits} 位纠错后通过校验码(原始识别有误)")
|
|
|
|
# 与 OCR 文字里的「出生 / 性别」交叉核对,不一致时优先相信 OCR 文字并打标注
|
|
birth_txt = _pick_field(text, (r"出生(\d{4}年\d{1,2}月\d{1,2}日)",
|
|
r"出生(\d{4}[.\-/]\d{1,2}[.\-/]\d{1,2})"))
|
|
if birth_txt:
|
|
res.evidence.append(f"卡面出生:{birth_txt}")
|
|
|
|
gender_txt = ""
|
|
m = re.search(r"性别[男女]", text) or re.search(r"(男|女)", text)
|
|
if m:
|
|
gender_txt = "女" if "女" in m.group(0) else "男"
|
|
if gender_txt:
|
|
res.evidence.append(f"卡面性别:{gender_txt}")
|
|
if res.gender and res.gender != gender_txt:
|
|
res.evidence.append(f"⚠ 号码推导性别({res.gender})与卡面({gender_txt})不一致")
|
|
|
|
eth = _pick_field(text, (r"民族([\u4e00-\u9fa5]{1,4}?)(?=出生|性别|姓名|住址|公|$)",))
|
|
res.ethnicity = eth
|
|
|
|
res.name = _pick_name(lines, expected_name, text)
|
|
|
|
# 住址:从「住址」开始到号码/签发机关之前
|
|
m = re.search(r"住址(.+?)(公民身份号码|签发机关|有效期限|$)", text)
|
|
addr = m.group(1) if m else ""
|
|
res.address = re.sub(r"[。,,]", "", addr)[:60]
|
|
|
|
res.issue = _pick_field(text, (r"签发机关([^有效]+?)(?:有效|$)",))
|
|
vt = re.search(r"有效期限?(\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?(?:[-—~至]\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?|长期))", text)
|
|
res.valid_to = vt.group(1) if vt else ""
|
|
|
|
# 置信度
|
|
high = res.checksum_ok and bool(res.name) and bool(res.birth)
|
|
if (expected_name and res.name and _norm_name(res.name) != _norm_name(expected_name)):
|
|
high = False
|
|
res.evidence.append(f"⚠ 姓名({res.name})与表格姓名({expected_name})不一致")
|
|
if not res.checksum_ok:
|
|
res.confidence = "low" if not cands else "medium"
|
|
elif high and (top.origin == "raw" if cands else False):
|
|
res.confidence = "high"
|
|
else:
|
|
res.confidence = "medium"
|
|
if res.birth and not id_plausible(res.number or ""):
|
|
res.evidence.append("⚠ 号码生日不合法")
|
|
return res
|