"""OCR操作模块 包含OCR识别相关的操作。 """ from __future__ import annotations import os import contextlib from typing import Any # PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。 # 这里提前设置环境变量,避免启动耗时/卡死。 os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True") # 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING) os.environ.setdefault("GLOG_minloglevel", "2") # 优化OMP_NUM_THREADS:允许底层库使用多线程,但不要设置太高避免线程竞争 # 设置为CPU核心数的一半,平衡性能和资源使用 import os as os_module cpu_count = os_module.cpu_count() or 4 # 对于OCR任务,每个线程内部会使用多个OMP线程,所以设置为2-4比较合适 # 如果CPU核心数>=8,设置为4;否则设置为2 optimal_omp_threads = min(4, max(2, cpu_count // 3)) os.environ.setdefault("OMP_NUM_THREADS", str(optimal_omp_threads)) class OCRProcessor: """OCR处理器类""" def __init__(self): # 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。 # 支持延迟初始化(测试流程/只做点击时不需要 OCR)。 self.ocr: Any = None self.ocr_type = None # 'easyocr' 或 'paddleocr' # 默认使用CPU模式(删除GPU检测) self._gpu_available = False if not str(os.environ.get("SKIP_OCR_INIT", "")).strip(): self._init_ocr() def _init_ocr(self): """初始化OCR引擎""" # 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR # 首先尝试EasyOCR try: # 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题 import easyocr # type: ignore[import-untyped, import] # pyright: ignore[reportMissingImports, reportMissingModuleSource] # pylint: disable=import-error # 只加载中文和英文,加快初始化速度 # 自动检测GPU可用性,如果可用则启用GPU加速 # 临时重定向输出以减少初始化时的噪音 import io from contextlib import redirect_stdout, redirect_stderr fake_stdout = io.StringIO() fake_stderr = io.StringIO() with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr): self.ocr = easyocr.Reader( ["ch_sim", "en"], gpu=False, verbose=False ) self.ocr_type = "easyocr" print(f"[OCR] 使用 EasyOCR(CPU模式)") except Exception as e: # EasyOCR初始化失败,回退到PaddleOCR print(f"[OCR] EasyOCR初始化失败: {e},回退到PaddleOCR") devnull = None try: devnull = open(os.devnull, "w") with contextlib.redirect_stdout( devnull ), contextlib.redirect_stderr(devnull): from paddleocr import PaddleOCR # type: ignore # pylint: disable=import-error # 使用 PaddleOCR(强制 CPU 模式,不进行 GPU 检测) use_gpu = False self.ocr = PaddleOCR( lang="ch", ocr_version="PP-OCRv4", use_angle_cls=False, use_gpu=use_gpu, use_doc_orientation_classify=False, use_doc_unwarping=False, use_textline_orientation=False, ) self.ocr_type = "paddleocr" print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") print( f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr" ) except Exception: # 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。 self.ocr = None self.ocr_type = None finally: try: if devnull is not None: devnull.close() except Exception: pass def _ensure_ocr(self): """确保OCR引擎已初始化""" if self.ocr is not None: return # 默认使用CPU模式(延迟初始化时) # 优先尝试EasyOCR devnull = None try: devnull = open(os.devnull, "w") with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr( devnull ): import easyocr # type: ignore[import-untyped] # pylint: disable=import-error self.ocr = easyocr.Reader( ["ch_sim", "en"], gpu=False, verbose=False ) self.ocr_type = "easyocr" gpu_status = "CPU模式" print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") except Exception: # EasyOCR失败,回退到PaddleOCR try: if devnull is not None: try: devnull.close() except Exception: pass except Exception: pass try: devnull = open(os.devnull, "w") with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr( devnull ): from paddleocr import PaddleOCR # type: ignore # pylint: disable=import-error # 使用 PaddleOCR(强制 CPU 模式) use_gpu = False self.ocr = PaddleOCR( lang="ch", ocr_version="PP-OCRv4", use_angle_cls=False, use_gpu=use_gpu, use_doc_orientation_classify=False, use_doc_unwarping=False, use_textline_orientation=False, ) self.ocr_type = "paddleocr" print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)") except Exception as e: print(f"[OCR] OCR引擎初始化失败: {e}") self.ocr = None self.ocr_type = None finally: try: if devnull is not None: devnull.close() except Exception: pass # 全局OCR处理器实例 _ocr_processor = OCRProcessor() # 全局OCR底层操作单例(延迟初始化) _UNDERLYING_OPS_SINGLETON = None def _ensure_ocr(): """确保OCR引擎已初始化(向后兼容接口)""" _ocr_processor._ensure_ocr() def analyse_pic_word(picname, change_color=0, pic_path=None): """文字OCR识别(向后兼容接口)""" # 使用全局复用的 underlying_operations 实例,避免每次调用都初始化 OCR(耗时) from Underlying_Operations import underlying_operations global _UNDERLYING_OPS_SINGLETON # type: ignore[name-defined] try: _UNDERLYING_OPS_SINGLETON # type: ignore[name-defined] except NameError: _UNDERLYING_OPS_SINGLETON = underlying_operations() return _UNDERLYING_OPS_SINGLETON.analyse_pic_word(picname, change_color, pic_path) def analyse_pic_digits(picname, change_color=1, pic_path=None): """数字OCR识别(向后兼容接口)""" # 使用全局复用的 underlying_operations 实例,避免每次调用都初始化 OCR(耗时) from Underlying_Operations import underlying_operations global _UNDERLYING_OPS_SINGLETON # type: ignore[name-defined] try: _UNDERLYING_OPS_SINGLETON # type: ignore[name-defined] except NameError: _UNDERLYING_OPS_SINGLETON = underlying_operations() return _UNDERLYING_OPS_SINGLETON.analyse_pic_digits(picname, change_color, pic_path) def extract_ocr_content(content=[], return_confidence=False): """提取OCR内容(向后兼容接口)""" # 使用全局复用的 underlying_operations 实例 from Underlying_Operations import underlying_operations global _UNDERLYING_OPS_SINGLETON # type: ignore[name-defined] try: _UNDERLYING_OPS_SINGLETON # type: ignore[name-defined] except NameError: _UNDERLYING_OPS_SINGLETON = underlying_operations() return _UNDERLYING_OPS_SINGLETON.extract_ocr_content(content, return_confidence) __all__ = [ "OCRProcessor", "analyse_pic_word", "analyse_pic_digits", "extract_ocr_content", "_ensure_ocr", ]