Files
douyin_guaji-main/operations/ocr_operations.py
T
CodexandClaude Opus 4.7 5a381698d8 operations/{screenshot,ocr}_operations: print → logging
- screenshot_operations.py: 19 处 print → _ops_log(带 [截图]/[截图操作] 前缀)
- ocr_operations.py: 7 处 print → _ocr_log(带 [OCR] 前缀)
- 两处都新增模块级 logger + 兜底 helper,与 douyin_yanghao / screenshot_service
  采用相同模式

回归:149 .py 编译通过;test_filter_logging / check_web_gui_config_sync 通过;
ScreenshotOperations、analyse_pic_word 仍可正常加载。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:38:07 +08:00

255 lines
9.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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))
import logging as _logging
# 模块级 logger:原代码用 print 输出 OCR 引擎初始化日志,统一走 logging。
# 保留消息中已有的 "[OCR]" 前缀,避免改变历史搜索习惯。
_LOGGER = _logging.getLogger("operations.ocr_operations")
def _ocr_log(msg: str, level: str = "INFO") -> None:
"""统一 OCR 操作日志出口;失败兜底 stdout。"""
try:
lv = str(level or "INFO").upper()
if lv == "ERROR":
_LOGGER.error(str(msg))
elif lv == "WARNING":
_LOGGER.warning(str(msg))
elif lv == "DEBUG":
_LOGGER.debug(str(msg))
else:
_LOGGER.info(str(msg))
except Exception:
try:
_ocr_log(str(msg))
except Exception:
pass
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"
_ocr_log(f"[OCR] 使用 EasyOCR(CPU模式)")
except Exception as e:
# EasyOCR初始化失败,回退到PaddleOCR
_ocr_log(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"
_ocr_log(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)")
_ocr_log(
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模式"
_ocr_log(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"
_ocr_log(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)")
except Exception as e:
_ocr_log(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 douyin.core.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 douyin.core.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 douyin.core.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",
]