# -*- coding: utf-8 -*- """ @Module: app.utils.ocr @FileName: ocr.py @Author: 小布丁 @Description: 通用图像文字识别模块(RapidOCR)。 只做「传图片 -> 返回识别文本」,不含任何业务判断; 业务判断由各业务脚本负责(如请假附件关键词检测见 app/service/hrbp/oa/leave/attachment_check.py)。 @Version: 2.0.0 """ import re from typing import Tuple from PIL import Image, ImageEnhance, ImageOps import numpy as np try: from rapidocr import RapidOCR except ImportError: RapidOCR = None # 置信度阈值:低于该分数的识别片段会被丢弃 _CONFIDENCE_THRESHOLD = 0.5 # 全局初始化 OCR 引擎,首次运行自动下载模型 _ocr_engine = RapidOCR() if RapidOCR is not None else None def _preprocess_image(img) -> np.ndarray: """预处理图像:EXIF 转正(修正手机横拍)+ 转灰度 + 提升对比度,返回可喂给 OCR 的图像数组。""" img = ImageOps.exif_transpose(img) gray_img = img.convert("L") enhancer = ImageEnhance.Contrast(gray_img) enhanced_img = enhancer.enhance(2.0) return np.array(enhanced_img) def _run_ocr(img_array: np.ndarray, debug: bool = False) -> Tuple[str, str]: """ 对预处理后的图像数组执行 OCR,返回 (清洗后拼接文本, 原始拼接文本)。 - 过滤低置信度片段 - 清洗:去空格与特殊符号,便于关键词匹配 """ if _ocr_engine is None: raise RuntimeError("RapidOCR 未安装,请执行: pip install rapidocr onnxruntime") result = _ocr_engine(img_array) 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 _read_image(img, debug: bool = False) -> Tuple[str, str]: """对 PIL.Image 做预处理并 OCR,返回 (清洗后拼接文本, 原始拼接文本)。""" img_array = _preprocess_image(img) return _run_ocr(img_array, debug=debug) def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]: """OCR 识别图片文件,返回 (清洗后拼接文本, 原始拼接文本)。""" with Image.open(file_path) as img: return _read_image(img, debug=debug) def recognize_image(img, debug: bool = False) -> str: """ 通用图像 OCR(图像输入):传入 PIL.Image 或 numpy 数组,返回识别出的清洗后文本。 供 PDF 扫描页渲染等内存图像场景复用;图片文件场景请使用 recognize_text()。 """ if isinstance(img, np.ndarray): img = Image.fromarray(img) full_text, _ = _read_image(img, debug=debug) return full_text def recognize_text(file_path: str, debug: bool = False) -> str: """ 通用图像 OCR(文件输入):传入图片路径,返回识别出的清洗后文本。 Args: file_path: 图片文件路径(png/jpg/jpeg/bmp 等) debug: 是否打印调试信息 Returns: 识别出的文本(已去空格、过滤特殊符号,便于关键词匹配);文件异常/识别失败抛异常 """ full_text, _ = _read_text(file_path, debug=debug) return full_text def recognize_text_raw(file_path: str, debug: bool = False) -> str: """ 通用图像 OCR(文件输入):返回原始拼接文本(保留识别片段原样,含空格/符号)。 需要展示识别原文时使用;默认请用 recognize_text()。 """ _, raw_text = _read_text(file_path, debug=debug) return raw_text if __name__ == "__main__": # 简单自测入口 path = r"D:\downloads\ocr_test_01.png" print(recognize_text(path, debug=True))