- Introduced a 30-minute timeout mechanism to prevent the script from getting stuck in invalid states, with configurable timeout settings. - Unified path configurations across the project to enhance maintainability and avoid hardcoded paths. - Updated documentation and flowcharts to reflect the new timeout feature and improved path management. - Fixed issues with template and screenshot path configurations to ensure consistency across the project.
283 lines
10 KiB
Python
283 lines
10 KiB
Python
"""OCR操作模块
|
||
|
||
包含OCR识别相关的操作。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import contextlib
|
||
from typing import Any, Optional
|
||
|
||
# PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。
|
||
# 这里提前设置环境变量,避免启动耗时/卡死。
|
||
os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
|
||
# 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING)
|
||
os.environ.setdefault("GLOG_minloglevel", "2")
|
||
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||
|
||
|
||
class OCRProcessor:
|
||
"""OCR处理器类"""
|
||
|
||
def __init__(self):
|
||
# 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。
|
||
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
|
||
self.ocr: Any = None
|
||
self.ocr_type = None # 'easyocr' 或 'paddleocr'
|
||
|
||
# 检测GPU是否可用(自动检测)
|
||
self._gpu_available = self._detect_gpu_available()
|
||
|
||
if not str(os.environ.get("SKIP_OCR_INIT", "")).strip():
|
||
self._init_ocr()
|
||
|
||
def _init_ocr(self):
|
||
"""初始化OCR引擎"""
|
||
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
|
||
# 首先尝试EasyOCR
|
||
devnull = None
|
||
try:
|
||
devnull = open(os.devnull, "w")
|
||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||
devnull
|
||
):
|
||
import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports]
|
||
|
||
# 只加载中文和英文,加快初始化速度
|
||
# 自动检测GPU可用性,如果可用则启用GPU加速
|
||
self.ocr = easyocr.Reader(
|
||
["ch_sim", "en"], gpu=self._gpu_available, verbose=False
|
||
)
|
||
self.ocr_type = "easyocr"
|
||
gpu_status = "GPU加速" if self._gpu_available else "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
|
||
|
||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||
use_gpu = False
|
||
try:
|
||
import paddle
|
||
|
||
if (
|
||
paddle.device.is_compiled_with_cuda()
|
||
and paddle.device.get_device()
|
||
):
|
||
use_gpu = self._gpu_available
|
||
except Exception:
|
||
pass
|
||
|
||
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"
|
||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||
print(
|
||
f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
|
||
)
|
||
except Exception:
|
||
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
|
||
try:
|
||
if devnull is not None:
|
||
try:
|
||
devnull.close()
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
self.ocr = None
|
||
self.ocr_type = None
|
||
finally:
|
||
try:
|
||
if devnull is not None:
|
||
devnull.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def _detect_gpu_available(self) -> bool:
|
||
"""检测GPU是否可用
|
||
|
||
默认返回False(CPU模式),除非通过环境变量明确启用GPU
|
||
|
||
返回:
|
||
True: GPU可用且已启用
|
||
False: 使用CPU模式(默认)
|
||
"""
|
||
# 默认使用CPU模式,除非环境变量明确要求使用GPU
|
||
# 检查环境变量是否强制启用GPU
|
||
if str(os.environ.get("FORCE_GPU_OCR", "")).strip().lower() in (
|
||
"1",
|
||
"true",
|
||
"yes",
|
||
):
|
||
# 强制启用时,验证GPU是否真的可用
|
||
try:
|
||
import torch # type: ignore[import-untyped]
|
||
|
||
if torch.cuda.is_available():
|
||
gpu_name = torch.cuda.get_device_name(0)
|
||
print(f"[OCR] 环境变量强制启用GPU: {gpu_name},将使用GPU加速")
|
||
return True
|
||
else:
|
||
print("[OCR] 环境变量要求启用GPU,但GPU不可用,使用CPU模式")
|
||
return False
|
||
except ImportError:
|
||
print("[OCR] 环境变量要求启用GPU,但PyTorch未安装,使用CPU模式")
|
||
return False
|
||
except Exception as e:
|
||
print(f"[OCR] GPU检测失败: {e},使用CPU模式")
|
||
return False
|
||
|
||
# 默认使用CPU模式
|
||
return False
|
||
|
||
def _ensure_ocr(self):
|
||
"""确保OCR引擎已初始化"""
|
||
if self.ocr is not None:
|
||
return
|
||
|
||
# 重新检测GPU(延迟初始化时)
|
||
self._gpu_available = self._detect_gpu_available()
|
||
|
||
# 优先尝试EasyOCR
|
||
devnull = None
|
||
try:
|
||
devnull = open(os.devnull, "w")
|
||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||
devnull
|
||
):
|
||
import easyocr # type: ignore[import-untyped]
|
||
|
||
self.ocr = easyocr.Reader(
|
||
["ch_sim", "en"], gpu=self._gpu_available, verbose=False
|
||
)
|
||
self.ocr_type = "easyocr"
|
||
gpu_status = "GPU加速" if self._gpu_available else "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
|
||
|
||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||
use_gpu = False
|
||
try:
|
||
import paddle
|
||
|
||
if (
|
||
paddle.device.is_compiled_with_cuda()
|
||
and paddle.device.get_device()
|
||
):
|
||
use_gpu = self._gpu_available
|
||
except Exception:
|
||
pass
|
||
|
||
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"
|
||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||
print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||
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()
|
||
|
||
|
||
def _detect_gpu_available() -> bool:
|
||
"""检测GPU是否可用(向后兼容接口)"""
|
||
return _ocr_processor._detect_gpu_available()
|
||
|
||
|
||
def _ensure_ocr():
|
||
"""确保OCR引擎已初始化(向后兼容接口)"""
|
||
_ocr_processor._ensure_ocr()
|
||
|
||
|
||
def analyse_pic_word(picname, change_color=0, pic_path=None):
|
||
"""文字OCR识别(向后兼容接口)"""
|
||
# 这里应该实现实际的OCR文字识别逻辑
|
||
# 暂时从原文件导入以保持功能
|
||
from Underlying_Operations import underlying_operations
|
||
instance = underlying_operations()
|
||
return instance.analyse_pic_word(picname, change_color, pic_path)
|
||
|
||
|
||
def analyse_pic_digits(picname, change_color=1, pic_path=None):
|
||
"""数字OCR识别(向后兼容接口)"""
|
||
# 这里应该实现实际的OCR数字识别逻辑
|
||
# 暂时从原文件导入以保持功能
|
||
from Underlying_Operations import underlying_operations
|
||
instance = underlying_operations()
|
||
return instance.analyse_pic_digits(picname, change_color, pic_path)
|
||
|
||
|
||
def extract_ocr_content(content=[], return_confidence=False):
|
||
"""提取OCR内容(向后兼容接口)"""
|
||
# 这里应该实现实际的OCR内容提取逻辑
|
||
# 暂时从原文件导入以保持功能
|
||
from Underlying_Operations import underlying_operations
|
||
instance = underlying_operations()
|
||
return instance.extract_ocr_content(content, return_confidence)
|
||
|
||
|
||
__all__ = [
|
||
"OCRProcessor",
|
||
"analyse_pic_word",
|
||
"analyse_pic_digits",
|
||
"extract_ocr_content",
|
||
"_ensure_ocr",
|
||
"_detect_gpu_available",
|
||
]
|
||
|