主要变更: 1. 统一替换rapidocr-onnxruntime为rapidocr+onnxruntime依赖包 2. 适配rapidocr v3+ API变更:调整OCR结果解析逻辑 3. 补充展示员工岗位信息到OA审批通知 4. 优化OA详情链接格式为Markdown可点击样式 5. 修复OCR图片EXIF旋转问题与文件名解码 6. 新增RPA开发提成评分规则文档 7. 重构OA登录入口参数,简化调用逻辑 8. 删除临时测试脚本
294 lines
9.4 KiB
Python
294 lines
9.4 KiB
Python
# -*- 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, ImageOps
|
||
import numpy as np
|
||
|
||
try:
|
||
from rapidocr 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:
|
||
# 应用 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 ()
|
||
|
||
if debug:
|
||
print("=" * 60)
|
||
print("【OCR原始识别片段(含置信度)】")
|
||
for idx, (txt, score) in enumerate(zip(txts, scores)):
|
||
print(f" [{idx:02d}] 置信度:{score:.3f} | 文本: {txt}")
|
||
print("=" * 60 + "\n")
|
||
|
||
raw_text = ""
|
||
full_text = ""
|
||
for text, score in zip(txts, scores):
|
||
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 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, [], "")
|
||
"""
|
||
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
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# 简单自测入口
|
||
path = r"D:\downloads\ocr_test_01.png"
|
||
print("病假关键词:", check_leave_attachment(path, "sick", debug=True))
|