# -*- coding: utf-8 -*- """ @Module: app.utils.ocr @FileName: ocr.py @Author: 小布丁 @Description: 请假附件 OCR 内容检测模块。 1. 按假期类型做关键词命中检测(病假/婚假/产检假) 2. 结婚证登记日期识别 + 1 年内判断 @Version: 1.0.0 """ import os import re from datetime import date, timedelta from typing import Any, Dict, List, Optional, Tuple from PIL import Image, ImageEnhance import numpy as np try: from rapidocr_onnxruntime import RapidOCR 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"} # 全局初始化 OCR 引擎,首次运行自动下载模型 _ocr_engine = RapidOCR() if RapidOCR is not None else None # ============================================= def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]: """ OCR 识别图片,返回 (清洗后拼接文本 full_text, 原始拼接文本 raw_text)。 - 转灰度 + 提升对比度优化拍照单据识别 - 过滤低置信度片段 - 去空格与特殊符号,便于关键词匹配 """ with Image.open(file_path) as 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") ocr_result, _ = _ocr_engine(img_array) if debug: print("=" * 60) print("【OCR原始识别片段(含置信度)】") for idx, (box, txt, score) in enumerate(ocr_result or []): print(f" [{idx:02d}] 置信度:{score:.3f} | 文本: {txt}") print("=" * 60 + "\n") raw_text = "" full_text = "" for box, text, score in ocr_result or []: if score < CONFIDENCE_THRESHOLD: continue raw_text += text clean_text = text.replace(" ", "").replace("\u3000", "") full_text += clean_text # 过滤乱码特殊符号,保留常用字符 clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]') full_text = clean_pattern.sub('', full_text) return full_text, raw_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 """ 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 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 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 = max(dates) 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))