refactor: 升级OCR依赖与适配rapidocr v3+,补充业务字段展示

主要变更:
1. 统一替换rapidocr-onnxruntime为rapidocr+onnxruntime依赖包
2. 适配rapidocr v3+ API变更:调整OCR结果解析逻辑
3. 补充展示员工岗位信息到OA审批通知
4. 优化OA详情链接格式为Markdown可点击样式
5. 修复OCR图片EXIF旋转问题与文件名解码
6. 新增RPA开发提成评分规则文档
7. 重构OA登录入口参数,简化调用逻辑
8. 删除临时测试脚本
This commit is contained in:
2026-08-27 13:32:48 +08:00
parent 54e2fef25d
commit eabadf5a37
12 changed files with 209 additions and 158 deletions
+73 -21
View File
@@ -8,7 +8,7 @@
@Version: 2.2.0
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
pip install DrissionPage python-dotenv Pillow numpy rapidocr-onnxruntime
pip install DrissionPage python-dotenv Pillow numpy rapidocr onnxruntime
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
@@ -57,20 +57,20 @@ try:
import requests
from DrissionPage import ChromiumPage, SessionPage
from dotenv import load_dotenv
from PIL import Image, ImageEnhance
from PIL import Image, ImageEnhance, ImageOps
import numpy as np
from rapidocr_onnxruntime import RapidOCR
from rapidocr import RapidOCR
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install DrissionPage python-dotenv Pillow numpy rapidocr-onnxruntime requests\n"
" pip install DrissionPage python-dotenv Pillow numpy rapidocr onnxruntime requests\n"
f"缺失依赖详情: {_import_err}"
)
# ==================== OCR 附件内容检测(单文件自包含) ====================
# 影刀版不依赖项目目录,直接使用下方内置 OCR 实现(行为与原项目 app/utils/ocr.py 完全一致)。
# Pillow/numpy/rapidocr 已在上方启动校验中强制安装,不做懒加载。
# Pillow/numpy/rapidocr 已在上方启动校验中强制安装,不做懒加载(rapidocr >= 3.0 支持 numpy 2.x)。
# ==================== 路径 & 常量配置 ====================
@@ -178,26 +178,33 @@ _ocr_engine = None # 前向声明,稍后在模块加载时统一初始化(
def _ocr_read_text(file_path, debug=False):
"""OCR 识别图片,返回 (清洗后拼接文本, 原始拼接文本)。"""
if _ocr_engine is None:
raise RuntimeError("OCR 引擎未初始化(rapidocr-onnxruntime 缺失或初始化失败)")
logger.warning("OCR 引擎未初始化,跳过识别: %s", file_path)
raise RuntimeError("OCR 引擎未初始化(rapidocr 缺失或初始化失败)")
if not os.path.isfile(file_path):
logger.warning("OCR 附件文件不存在,跳过识别: %s", file_path)
raise FileNotFoundError(f"附件文件不存在: {file_path}")
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)
ocr_result, _ = _ocr_engine(img_array)
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")
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 ()
logger.info("【OCR识别结果】文件: %s, 识别到 %d 个文本块", os.path.basename(file_path), len(txts))
for idx, (txt, score) in enumerate(zip(txts, scores)):
logger.info(" [%02d] 置信度:%.3f | 文本: %s", idx, score, txt)
raw_text = ""
full_text = ""
for box, text, score in ocr_result or []:
for text, score in zip(txts, scores):
if score < _OCR_CONFIDENCE_THRESHOLD:
continue
raw_text += text
@@ -221,8 +228,7 @@ def _ocr_check_leave_attachment(file_path, leave_type="sick", debug=False):
try:
full_text, _ = _ocr_read_text(file_path, debug=debug)
except Exception as e:
if debug:
print(f"[识别异常] {e}")
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
return False
if debug:
@@ -254,8 +260,7 @@ def _ocr_check_leave_attachment_detail(file_path, leave_type="sick", debug=False
try:
full_text, raw_text = _ocr_read_text(file_path, debug=debug)
except Exception as e:
if debug:
print(f"[识别异常] {e}")
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
return False, [], ""
if leave_type == "all":
@@ -266,6 +271,7 @@ def _ocr_check_leave_attachment_detail(file_path, leave_type="sick", debug=False
target_keywords = _OCR_LEAVE_KEYWORDS[leave_type]
hit_words = [kw for kw in target_keywords if kw in full_text]
logger.info("【OCR关键词匹配】假期类型: %s, 命中: %s", leave_type, hit_words if hit_words else "无")
return len(hit_words) > 0, hit_words, raw_text
@@ -285,8 +291,37 @@ def _ocr_extract_dates(text):
return dates
def _ocr_extract_registration_date(text):
"""从结婚证文本中提取"登记日期"字段对应的日期。
优先查找"登记日期"关键词后面紧跟的日期,如果找不到则返回 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 datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
except ValueError:
continue
return None
def _ocr_marriage_within_one_year(file_path, today=None, debug=False):
"""识别结婚证登记日期(取最大日期)并判断是否在当前日期 1 年内。"""
"""识别结婚证登记日期并判断是否在当前日期 1 年内。
优先查找"登记日期"关键词附近的日期,如果找不到则取识别到的最大日期作为兜底。
"""
if today is None:
today = datetime.now().date()
if not os.path.isfile(file_path):
@@ -305,7 +340,14 @@ def _ocr_marriage_within_one_year(file_path, today=None, debug=False):
print("【未识别到任何日期】")
return False, None
reg_date = max(dates)
# 优先查找"登记日期"关键词附近的日期
reg_date = _ocr_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}")
@@ -804,6 +846,7 @@ def _parse_leave_form(result):
"工号": result.get("staff_code"),
"请假人员": result.get("staff_name"),
"组织全路径": result.get("org_full_path"),
"岗位": result.get("post_name"),
"假期类型": _resolve_vacation_type(result),
# 日期字段:开始日期用 start_date(请假实际开始日,与页面一致;跨天/夜班场景下
# begin_date 可能取成申请日导致起止倒挂),start_date 缺失时回退 begin_date;
@@ -888,6 +931,12 @@ def _download_one(session, file_id, save_dir):
raw = cd.split("filename=")[-1].strip().strip('"')
if raw.startswith("UTF-8''"):
raw = unquote(raw.split("UTF-8''", 1)[1])
else:
# 尝试修复 Latin-1 错误解码的 UTF-8 文件名
try:
raw = raw.encode('latin-1').decode('utf-8')
except (UnicodeDecodeError, UnicodeEncodeError):
pass
if raw:
filename = raw
@@ -1149,6 +1198,7 @@ def _format_leave_block(r):
label_map = [
("请假人员", "请假人员"),
("工号", "工号"),
("岗位", "岗位"),
("组织全路径", "组织全路径"),
("假期类型", "假期类型"),
]
@@ -1180,7 +1230,7 @@ def _format_leave_block(r):
lines.append(f"> 备注:{note}")
url = r.get("detail_url") or ""
if url:
lines.append(f"> 详情页:{url}")
lines.append(f"> 详情页:[查看详情]({url})")
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
return '\n\n'.join(lines)
@@ -1489,6 +1539,7 @@ def _verify_attachment(session, vacation_type, reason, file_id):
paths = [p for p in path.split(",") if p]
if not paths:
return "人工复核", "附件下载失败,需人工核验", None
logger.info("附件校验开始: vacation_type=%s, 附件数=%d, 路径=%s", vacation_type, len(paths), paths)
def _first_hit(checker):
return next((p for p in paths if checker(p)), None)
@@ -1678,6 +1729,7 @@ def _format_detail(info):
fields = [
("请假人员", "请假人员"),
("工号", "工号"),
("岗位", "岗位"),
("组织全路径", "组织全路径"),
("假期类型", "假期类型"),
("开始日期", "开始日期"),
+10 -3
View File
@@ -535,6 +535,7 @@ def parse_overtime_form(result):
"加班人员ID": result.get("staff_id"),
"加班人员": result.get("staff_name"),
"组织全路径": result.get("org_full_path"),
"岗位": result.get("post_name"),
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
"加班日期": result.get("ot_date"),
@@ -801,8 +802,13 @@ def _format_overtime_block(r):
name = info.get("加班人员") or r.get("creator") or "未知"
otype = info.get("加班类型") or ""
lines = [f"**🔹 {name}‑{otype}**"]
for key, label in [("加班人员", "加班人员"), ("组织全路径", "组织全路径"),
("加班类型", "加班类型"), ("补贴类型", "补贴类型")]:
for key, label in [
("加班人员", "加班人员"),
("岗位", "岗位"),
("组织全路径", "组织全路径"),
("加班类型", "加班类型"),
("补贴类型", "补贴类型")
]:
val = info.get(key)
if val is not None and val != "" and val != "无":
lines.append(f"> {label}:{val}")
@@ -827,7 +833,7 @@ def _format_overtime_block(r):
lines.append(f"> 备注:{note}")
url = r.get("detail_url") or ""
if url:
lines.append(f"> 详情页:{url}")
lines.append(f"> 详情页:[查看详情]({url})")
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
return '\n\n'.join(lines)
@@ -1604,6 +1610,7 @@ def _format_detail(info):
fields = [
("加班人员", "加班人员"),
("组织全路径", "组织全路径"),
("岗位", "岗位"),
("加班类型", "加班类型"),
("补贴类型", "补贴类型"),
("加班日期", "加班日期"),
+4 -1
View File
@@ -695,6 +695,9 @@ def _format_resign_block(r):
name = info.get("员工姓名") or r.get("creator") or "未知"
code = info.get("工号") or ""
lines = [f"**🔹 {name}**" + (f"(工号 {code})" if code else "")]
post = info.get("岗位") or ""
if post:
lines.append(f"> 岗位:{post}")
# 电子签状态(有值才展示,便于核对)
for key, label in (("是否已发起电子签", "发起"), ("员工签署状态", "员工"), ("企业签署状态", "企业")):
val = info.get(key)
@@ -708,7 +711,7 @@ def _format_resign_block(r):
lines.append(f"> 备注:{reason}")
url = r.get("detail_url") or ""
if url:
lines.append(f"> 详情链接:{url}")
lines.append(f"> 详情页:[查看详情]({url})")
return "\n".join(lines)