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:
@@ -49,7 +49,7 @@ except ImportError as _import_err:
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
"(钉钉推送相关依赖 pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/"
|
||||
"rapidocr-onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
|
||||
"rapidocr onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
@@ -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 = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始日期", "开始日期"),
|
||||
|
||||
@@ -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 = [
|
||||
("加班人员", "加班人员"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("岗位", "岗位"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
依赖(影刀「Python包管理」安装;启动校验不懒加载):
|
||||
pip install pyautogui pywin32 pyperclip psutil
|
||||
pip install Pillow numpy rapidocr-onnxruntime
|
||||
pip install Pillow numpy rapidocr onnxruntime
|
||||
|
||||
入口:
|
||||
main(messages) 影刀自定义指令调用入口,直接传列表,每项为 (search_keyword, text, verify_keyword) 元组:
|
||||
@@ -58,13 +58,13 @@ try:
|
||||
import psutil
|
||||
from PIL import Image, ImageGrab
|
||||
import numpy as np
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
from rapidocr import RapidOCR
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(钉钉推送指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pyautogui pywin32 pyperclip psutil\n"
|
||||
" pip install Pillow numpy rapidocr-onnxruntime\n"
|
||||
" pip install Pillow numpy rapidocr onnxruntime\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
@@ -379,10 +379,10 @@ def _dt_ocr_image(img):
|
||||
if img is None:
|
||||
return []
|
||||
img_np = np.array(img)
|
||||
result, _ = _dt_get_ocr()(img_np)
|
||||
result = _dt_get_ocr()(img_np)
|
||||
ocr_data = []
|
||||
if result is not None:
|
||||
for box, text, score in result:
|
||||
if result is not None and result.boxes is not None:
|
||||
for box, text, score in zip(result.boxes, result.txts, result.scores):
|
||||
xs = [p[0] for p in box]
|
||||
ys = [p[1] for p in box]
|
||||
x1, y1 = min(xs), min(ys)
|
||||
|
||||
@@ -32,8 +32,8 @@
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main({"force": true}))
|
||||
main(force=True) 影刀自定义指令调用入口,force 传 True/False(是否强制重新登录),返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main(force=True))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
@@ -221,15 +221,12 @@ def ensure_login(force=False):
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
def main(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
@@ -238,5 +235,5 @@ def main(args):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": True})
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
临时联调脚本:测试「37du钉钉推送」指令在不同会话间切换是否正常。
|
||||
向两个测试接收人(夏一平 37036361 / 人资专用号 37036273)交替推送测试消息。
|
||||
运行:
|
||||
.\\.venv\\Scripts\\python.exe yingdao\\test_dingtalk_push.py
|
||||
说明:会真实操作本机钉钉(打开/搜索/发送),请确保钉钉已登录并保持在前台可用。
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
YINGDAO_DIR = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(YINGDAO_DIR / "share"))
|
||||
sys.path.insert(0, str(YINGDAO_DIR / "hr"))
|
||||
|
||||
from dingtalk_sender import main as dingtalk_push_main
|
||||
from attendance_abnormal import build_notify_text
|
||||
|
||||
# 两个测试接收人(交替推送,验证会话切换)
|
||||
RECEIVERS = [
|
||||
("37036361", "夏一平"), # 测试接收人1
|
||||
("37036273", "人资专用号"), # 测试接收人2
|
||||
]
|
||||
|
||||
|
||||
def build_text(seq):
|
||||
"""用周考勤的推送模板生成一条测试消息。"""
|
||||
items = [
|
||||
{"STAFF_NAME": "测试员工", "base_code": "37000001",
|
||||
"work_day": "2026-08-12", "abnormal": "上班旷工", "abnormal_minute": "194"},
|
||||
]
|
||||
return f"【会话切换测试{seq}】\n" + build_notify_text(items)
|
||||
|
||||
|
||||
def main():
|
||||
total = 8 # 共 4 条,交替发两个接收人
|
||||
messages = []
|
||||
for seq in range(1, total + 1):
|
||||
search, verify = RECEIVERS[(seq - 1) % 2]
|
||||
messages.append((search, build_text(seq), verify))
|
||||
|
||||
print("=" * 60)
|
||||
for i, (s, t, v) in enumerate(messages, 1):
|
||||
print(f"msg{i}: search={s} verify={v}")
|
||||
print("=" * 60)
|
||||
|
||||
result = dingtalk_push_main(messages)
|
||||
print("RESULT:", result)
|
||||
if not result.get("success"):
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user