- Removed obsolete command-line test parameters from `run_cli.py` to streamline functionality. - Introduced a new `ocr_preprocess.py` module for unified OCR image preprocessing, enhancing recognition stability. - Updated various components to utilize the new preprocessing function, improving code organization and readability. - Adjusted configuration values in `config.json` for better performance and consistency. - Added comprehensive technical documentation for the Douyin project, detailing code modification standards and operational guidelines. - Cleaned up excessive blank lines across multiple files to enhance overall readability.
207 lines
7.4 KiB
Python
207 lines
7.4 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'
|
||
|
||
# 默认使用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]
|
||
|
||
# 只加载中文和英文,加快初始化速度
|
||
# 自动检测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
|
||
|
||
# 使用 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]
|
||
|
||
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
|
||
|
||
# 使用 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()
|
||
|
||
|
||
|
||
|
||
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",
|
||
]
|
||
|