Files
37duAutomation/app/service/hrbp/oa/leave/attachment_check.py
T
puddy 3b5ce2d219 feat: 新增离职电子签流程审批功能,重构请假OCR业务逻辑
1.  新增离职电子签全流程校验:包括附件下载、PDF解析、表单与文书核验
2.  重构通用OCR模块,剥离业务逻辑到单独的请假附件检测模块
3.  新增PyMuPDF依赖用于PDF文本与扫描件OCR解析
4.  新增附件清单查询接口与离职附件检测工具类
2026-08-31 11:55:25 +08:00

222 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@Module: app.service.hrbp.oa.leave.attachment_check
@FileName: attachment_check.py
@Author: 小布丁
@Description: 请假附件内容检测(业务层)。
基于通用图像 OCR(app.utils.ocr.recognize_text / recognize_text_raw):
1. 按假期类型做关键词命中检测(病假/婚假/产检假)
2. 结婚证登记日期识别 + 1 年内判断
@Version: 1.0.0
"""
import os
import re
from datetime import date
from typing import List, Optional, Tuple
from app.utils.ocr import recognize_text, recognize_text_raw
# 按假期类型分类的关键词库
LEAVE_KEYWORDS = {
# 病假/医疗类:对应医院诊断证明、病历、检验单等
"sick": {
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
},
# 婚假类:对应结婚证、婚姻登记证明
"marriage": {
"结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关",
"婚姻证", "中华人民共和国结婚证",
},
# 产检假类:对应产检报告、B超单、妊娠诊断证明
"maternity": {
"产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期",
"超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心",
},
}
VALID_TYPES = set(LEAVE_KEYWORDS.keys()) | {"all"}
def _ocr_read(file_path: str, debug: bool = False) -> Tuple[str, str]:
"""识别附件图片,返回 (清洗后文本, 原始文本);文件异常/识别失败返回 ("", "")。"""
if not os.path.isfile(file_path):
return "", ""
try:
return recognize_text(file_path, debug=debug), recognize_text_raw(file_path, debug=debug)
except Exception as e:
if debug:
print(f"[识别异常] {e}")
return "", ""
def _hit_keywords(full_text: str, leave_type: str) -> List[str]:
"""返回文本命中的关键词列表(leave_type 支持 all 汇总全部关键词)。"""
if leave_type not in VALID_TYPES:
return []
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]
return [kw for kw in target_keywords if kw in full_text]
def check_leave_attachment(file_path: str, leave_type: str = "sick", debug: bool = False) -> bool:
"""
检测请假附件图片是否包含对应假期的关键词。
Args:
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
leave_type: sick / marriage / maternity / all
debug: 是否打印调试信息
Returns:
命中关键词返回 True;未命中 / 文件异常 / 识别失败返回 False
"""
full_text, _ = _ocr_read(file_path, debug=debug)
if not full_text:
return False
if debug:
print("【清洗后匹配文本】")
print(full_text)
print("=" * 60 + "\n")
hit_words = _hit_keywords(full_text, leave_type)
if debug:
print(f"【命中关键词】: {hit_words}")
return len(hit_words) > 0
def check_leave_attachment_detail(
file_path: str, leave_type: str = "sick", debug: bool = False
) -> Tuple[bool, List[str], str]:
"""
检测请假附件图片是否包含对应假期的关键词,并返回命中的具体关键词列表与 OCR 原文。
Args:
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
leave_type: sick / marriage / maternity / all
debug: 是否打印调试信息
Returns:
(是否命中, 命中的关键词列表, OCR 识别原文);文件异常/识别失败返回 (False, [], "")
"""
full_text, raw_text = _ocr_read(file_path, debug=debug)
if not full_text:
return False, [], ""
hit_words = _hit_keywords(full_text, leave_type)
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()
full_text, _ = _ocr_read(file_path, debug=debug)
if not full_text:
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
if __name__ == "__main__":
# 简单自测入口
path = r"D:\downloads\ocr_test_01.png"
print("病假关键词:", check_leave_attachment(path, "sick", debug=True))