feat: 新增离职电子签流程审批功能,重构请假OCR业务逻辑

1.  新增离职电子签全流程校验:包括附件下载、PDF解析、表单与文书核验
2.  重构通用OCR模块,剥离业务逻辑到单独的请假附件检测模块
3.  新增PyMuPDF依赖用于PDF文本与扫描件OCR解析
4.  新增附件清单查询接口与离职附件检测工具类
This commit is contained in:
2026-08-31 11:55:25 +08:00
parent 9cfa096ec8
commit 3b5ce2d219
17 changed files with 1454 additions and 771 deletions
+55 -218
View File
@@ -3,16 +3,15 @@
@Module: app.utils.ocr
@FileName: ocr.py
@Author: 小布丁
@Description: 请假附件 OCR 内容检测模块。
1. 按假期类型做关键词命中检测(病假/婚假/产检假)
2. 结婚证登记日期识别 + 1 年内判断
@Version: 1.0.0
@Description: 通用图像文字识别模块(RapidOCR)。
只做「传图片 -> 返回识别文本」,不含任何业务判断;
业务判断由各业务脚本负责(如请假附件关键词检测见
app/service/hrbp/oa/leave/attachment_check.py)。
@Version: 2.0.0
"""
import os
import re
from datetime import date, timedelta
from typing import Any, Dict, List, Optional, Tuple
from typing import Tuple
from PIL import Image, ImageEnhance, ImageOps
import numpy as np
@@ -22,57 +21,34 @@ try:
except ImportError:
RapidOCR = None
# ==================== 配置 ====================
# 按假期类型分类的关键词库
LEAVE_KEYWORDS: Dict[str, set] = {
# 病假/医疗类:对应医院诊断证明、病历、检验单等
"sick": {
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
},
# 婚假类:对应结婚证、婚姻登记证明
"marriage": {
"结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关",
"婚姻证", "中华人民共和国结婚证",
},
# 产检假类:对应产检报告、B超单、妊娠诊断证明
"maternity": {
"产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期",
"超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心",
},
}
# 置信度阈值:低于该分数的识别片段会被丢弃
CONFIDENCE_THRESHOLD = 0.5
VALID_TYPES = set(LEAVE_KEYWORDS.keys()) | {"all"}
_CONFIDENCE_THRESHOLD = 0.5
# 全局初始化 OCR 引擎,首次运行自动下载模型
_ocr_engine = RapidOCR() if RapidOCR is not None else None
# =============================================
def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]:
def _preprocess_image(img) -> np.ndarray:
"""预处理图像:EXIF 转正(修正手机横拍)+ 转灰度 + 提升对比度,返回可喂给 OCR 的图像数组。"""
img = ImageOps.exif_transpose(img)
gray_img = img.convert("L")
enhancer = ImageEnhance.Contrast(gray_img)
enhanced_img = enhancer.enhance(2.0)
return np.array(enhanced_img)
def _run_ocr(img_array: np.ndarray, debug: bool = False) -> Tuple[str, str]:
"""
OCR 识别图片,返回 (清洗后拼接文本 full_text, 原始拼接文本 raw_text)。
对预处理后的图像数组执行 OCR,返回 (清洗后拼接文本, 原始拼接文本)。
- 转灰度 + 提升对比度优化拍照单据识别
- 过滤低置信度片段
- 去空格与特殊符号,便于关键词匹配
- 清洗:去空格与特殊符号,便于关键词匹配
"""
with Image.open(file_path) as img:
# 应用 EXIF 方向信息,修正手机横拍导致的旋转
img = ImageOps.exif_transpose(img)
gray_img = img.convert("L")
enhancer = ImageEnhance.Contrast(gray_img)
enhanced_img = enhancer.enhance(2.0)
img_array = np.array(enhanced_img)
if _ocr_engine is None:
raise RuntimeError("RapidOCR 未安装,请执行: pip install rapidocr onnxruntime")
result = _ocr_engine(img_array)
boxes = result.boxes if result and result.boxes is not None else []
txts = result.txts if result and result.txts is not None else ()
scores = result.scores if result and result.scores is not None else ()
@@ -86,7 +62,7 @@ def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]:
raw_text = ""
full_text = ""
for text, score in zip(txts, scores):
if score < CONFIDENCE_THRESHOLD:
if score < _CONFIDENCE_THRESHOLD:
continue
raw_text += text
clean_text = text.replace(" ", "").replace("\u3000", "")
@@ -99,195 +75,56 @@ def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]:
return full_text, raw_text
def check_leave_attachment(file_path: str, leave_type: str = "sick", debug: bool = False) -> bool:
def _read_image(img, debug: bool = False) -> Tuple[str, str]:
"""对 PIL.Image 做预处理并 OCR,返回 (清洗后拼接文本, 原始拼接文本)。"""
img_array = _preprocess_image(img)
return _run_ocr(img_array, debug=debug)
def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]:
"""OCR 识别图片文件,返回 (清洗后拼接文本, 原始拼接文本)。"""
with Image.open(file_path) as img:
return _read_image(img, debug=debug)
def recognize_image(img, debug: bool = False) -> str:
"""
检测请假附件图片是否包含对应假期的关键词。
通用图像 OCR(图像输入):传入 PIL.Image 或 numpy 数组,返回识别出的清洗后文本。
供 PDF 扫描页渲染等内存图像场景复用;图片文件场景请使用 recognize_text()。
"""
if isinstance(img, np.ndarray):
img = Image.fromarray(img)
full_text, _ = _read_image(img, debug=debug)
return full_text
def recognize_text(file_path: str, debug: bool = False) -> str:
"""
通用图像 OCR(文件输入):传入图片路径,返回识别出的清洗后文本。
Args:
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
leave_type: sick / marriage / maternity / all
debug: 是否打印调试信息
Returns:
命中关键词返回 True;未命中 / 文件异常 / 识别失败返回 False
识别出的文本(已去空格、过滤特殊符号,便于关键词匹配);文件异常/识别失败抛异常
"""
if leave_type not in VALID_TYPES:
return False
if not os.path.isfile(file_path):
return False
try:
full_text, raw_text = _read_text(file_path, debug=debug)
except Exception as e:
if debug:
print(f"[识别异常] {e}")
return False
if debug:
print("【清洗后匹配文本】")
print(full_text)
print("=" * 60 + "\n")
if leave_type == "all":
target_keywords = set()
for kw_set in LEAVE_KEYWORDS.values():
target_keywords.update(kw_set)
else:
target_keywords = LEAVE_KEYWORDS[leave_type]
hit_words = [kw for kw in target_keywords if kw in full_text]
if debug:
print(f"【命中关键词】: {hit_words}")
return len(hit_words) > 0
full_text, _ = _read_text(file_path, debug=debug)
return full_text
def check_leave_attachment_detail(
file_path: str, leave_type: str = "sick", debug: bool = False
) -> Tuple[bool, List[str], str]:
def recognize_text_raw(file_path: str, debug: bool = False) -> str:
"""
检测请假附件图片是否包含对应假期的关键词,并返回命中的具体关键词列表与 OCR 全文。
通用图像 OCR(文件输入):返回原始拼接文本(保留识别片段原样,含空格/符号)。
Args:
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
leave_type: sick / marriage / maternity / all
debug: 是否打印调试信息
Returns:
(是否命中, 命中的关键词列表, OCR 识别全文);文件异常/识别失败返回 (False, [], "")
需要展示识别原文时使用;默认请用 recognize_text()。
"""
if leave_type not in VALID_TYPES:
return False, [], ""
if not os.path.isfile(file_path):
return False, [], ""
try:
full_text, raw_text = _read_text(file_path, debug=debug)
except Exception as e:
if debug:
print(f"[识别异常] {e}")
return False, [], ""
if leave_type == "all":
target_keywords: set = set()
for kw_set in LEAVE_KEYWORDS.values():
target_keywords.update(kw_set)
else:
target_keywords = LEAVE_KEYWORDS[leave_type]
hit_words = [kw for kw in target_keywords if kw in full_text]
return len(hit_words) > 0, hit_words, raw_text
def extract_dates(text: str) -> List[date]:
"""
从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。
Args:
text: OCR 拼接后的文本
Returns:
有效日期列表(datetime.date)
"""
dates: List[date] = []
patterns = [
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
]
for pat in patterns:
for m in re.finditer(pat, text):
try:
dates.append(date(int(m.group(1)), int(m.group(2)), int(m.group(3))))
except ValueError:
continue
return dates
def _extract_registration_date(text: str) -> Optional[date]:
"""
从结婚证文本中提取"登记日期"字段对应的日期。
优先查找"登记日期"关键词后面紧跟的日期,如果找不到则返回 None。
Args:
text: OCR 识别的全文
Returns:
登记日期(如果找到),否则返回 None
"""
# 查找"登记日期"关键词
reg_match = re.search(r'登记日期', text)
if not reg_match:
return None
# 从"登记日期"位置开始,提取后面紧跟的日期
text_after = text[reg_match.end():]
date_patterns = [
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
]
for pat in date_patterns:
m = re.search(pat, text_after)
if m:
try:
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
except ValueError:
continue
return None
def marriage_within_one_year(
file_path: str,
today: Optional[date] = None,
debug: bool = False,
) -> Tuple[bool, Optional[date]]:
"""
识别结婚证上的登记日期并判断是否在当前日期 1 年内。
优先查找"登记日期"关键词附近的日期,如果找不到则取识别到的最大日期作为兜底。
Args:
file_path: 结婚证图片路径
today: 基准日期(默认当天)
debug: 是否打印调试信息
Returns:
(是否 1 年内, 识别到的登记日期);识别失败/无日期返回 (False, None)
"""
if today is None:
today = date.today()
if not os.path.isfile(file_path):
return False, None
try:
full_text, raw_text = _read_text(file_path, debug=debug)
except Exception as e:
if debug:
print(f"[识别异常] {e}")
return False, None
dates = extract_dates(full_text)
if not dates:
if debug:
print("【未识别到任何日期】")
return False, None
# 优先查找"登记日期"关键词附近的日期
reg_date = _extract_registration_date(full_text)
if reg_date is None:
# 找不到"登记日期"关键词,fallback 到最大日期
reg_date = max(dates)
if debug:
print("【未找到登记日期关键词,使用最大日期兜底】")
ok = reg_date <= today and (today - reg_date).days <= 365
if debug:
print(f"【识别日期】: {dates}")
print(f"【登记日期】: {reg_date},1年内: {ok}")
return ok, reg_date
_, raw_text = _read_text(file_path, debug=debug)
return raw_text
if __name__ == "__main__":
# 简单自测入口
path = r"D:\downloads\ocr_test_01.png"
print("病假关键词:", check_leave_attachment(path, "sick", debug=True))
print(recognize_text(path, debug=True))