From 336e6424a5cb44ae83f9a97e4e7ff0335b0000f7 Mon Sep 17 00:00:00 2001 From: SWHL Date: Wed, 3 Sep 2025 21:58:15 +0800 Subject: [PATCH] fix: fixed issue #531 --- python/rapidocr/ch_ppocr_cls/utils.py | 4 +--- python/rapidocr/ch_ppocr_det/utils.py | 4 +--- python/rapidocr/ch_ppocr_rec/main.py | 4 ++-- python/rapidocr/ch_ppocr_rec/typings.py | 4 +--- python/rapidocr/config.yaml | 1 + python/rapidocr/inference_engine/base.py | 5 +---- .../inference_engine/onnxruntime/main.py | 4 ++-- .../onnxruntime/provider_config.py | 4 ++-- python/rapidocr/inference_engine/openvino.py | 4 ++-- python/rapidocr/inference_engine/paddle.py | 19 +++++++++++++------ python/rapidocr/inference_engine/torch.py | 4 ++-- python/rapidocr/main.py | 9 ++++++--- python/rapidocr/utils/__init__.py | 1 - python/rapidocr/utils/{logger.py => log.py} | 5 ++++- python/rapidocr/utils/output.py | 4 +--- python/rapidocr/utils/vis_res.py | 4 ++-- python/tests/test_main.py | 2 -- 17 files changed, 41 insertions(+), 41 deletions(-) rename python/rapidocr/utils/{logger.py => log.py} (89%) diff --git a/python/rapidocr/ch_ppocr_cls/utils.py b/python/rapidocr/ch_ppocr_cls/utils.py index 7b9c229..caff7d9 100644 --- a/python/rapidocr/ch_ppocr_cls/utils.py +++ b/python/rapidocr/ch_ppocr_cls/utils.py @@ -17,12 +17,10 @@ from typing import List, Optional, Tuple, Union import numpy as np -from ..utils.logger import Logger +from ..utils.log import logger from ..utils.utils import save_img from ..utils.vis_res import VisRes -logger = Logger(logger_name=__name__).get_log() - @dataclass class TextClsOutput: diff --git a/python/rapidocr/ch_ppocr_det/utils.py b/python/rapidocr/ch_ppocr_det/utils.py index 4690b06..1311f32 100644 --- a/python/rapidocr/ch_ppocr_det/utils.py +++ b/python/rapidocr/ch_ppocr_det/utils.py @@ -9,12 +9,10 @@ import numpy as np import pyclipper from shapely.geometry import Polygon -from ..utils.logger import Logger +from ..utils.log import logger from ..utils.utils import save_img from ..utils.vis_res import VisRes -logger = Logger(logger_name=__name__).get_log() - @dataclass class TextDetOutput: diff --git a/python/rapidocr/ch_ppocr_rec/main.py b/python/rapidocr/ch_ppocr_rec/main.py index 6d1ad51..b63ba3d 100644 --- a/python/rapidocr/ch_ppocr_rec/main.py +++ b/python/rapidocr/ch_ppocr_rec/main.py @@ -21,8 +21,8 @@ import numpy as np from rapidocr.inference_engine.base import FileInfo, get_engine -from ..utils import Logger from ..utils.download_file import DownloadFile, DownloadFileInput +from ..utils.log import logger from ..utils.vis_res import VisRes from .typings import TextRecInput, TextRecOutput from .utils import CTCLabelDecode @@ -35,7 +35,7 @@ DEFAULT_MODEL_PATH = Path(__file__).parent.parent / "models" class TextRecognizer: def __init__(self, cfg: Dict[str, Any]): self.session = get_engine(cfg.engine_type)(cfg) - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger # onnx has inner character, other engine get or download character_dict_path character, character_dict_path = self.get_character_dict(cfg) diff --git a/python/rapidocr/ch_ppocr_rec/typings.py b/python/rapidocr/ch_ppocr_rec/typings.py index 5fa0a3b..0239d9f 100644 --- a/python/rapidocr/ch_ppocr_rec/typings.py +++ b/python/rapidocr/ch_ppocr_rec/typings.py @@ -8,12 +8,10 @@ from typing import List, Optional, Tuple, Union import numpy as np -from ..utils.logger import Logger +from ..utils.log import logger from ..utils.utils import save_img from ..utils.vis_res import VisRes -logger = Logger(logger_name=__name__).get_log() - @dataclass class TextRecConfig: diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yaml index e1ece5b..b43d622 100644 --- a/python/rapidocr/config.yaml +++ b/python/rapidocr/config.yaml @@ -14,6 +14,7 @@ Global: return_single_char_box: false font_path: null + log_level: "info" # debug / info / warning / error / critical EngineConfig: onnxruntime: diff --git a/python/rapidocr/inference_engine/base.py b/python/rapidocr/inference_engine/base.py index 7606e59..868cd96 100644 --- a/python/rapidocr/inference_engine/base.py +++ b/python/rapidocr/inference_engine/base.py @@ -10,15 +10,13 @@ from typing import Dict, Union import numpy as np from omegaconf import OmegaConf -from ..utils.logger import Logger +from ..utils.log import logger from ..utils.typings import EngineType, ModelType, OCRVersion, TaskType from ..utils.utils import import_package cur_dir = Path(__file__).resolve().parent.parent MODEL_URL_PATH = cur_dir / "default_models.yaml" -logger = Logger(logger_name=__name__).get_log() - def get_engine(engine_type: EngineType): logger.info("Using engine_name: %s", engine_type.value) @@ -70,7 +68,6 @@ class FileInfo: class InferSession(abc.ABC): model_info = OmegaConf.load(MODEL_URL_PATH) DEFAULT_MODEL_PATH = cur_dir / "models" - logger = Logger(logger_name=__name__).get_log() @abc.abstractmethod def __init__(self, config): diff --git a/python/rapidocr/inference_engine/onnxruntime/main.py b/python/rapidocr/inference_engine/onnxruntime/main.py index e7da50a..411eacf 100644 --- a/python/rapidocr/inference_engine/onnxruntime/main.py +++ b/python/rapidocr/inference_engine/onnxruntime/main.py @@ -10,14 +10,14 @@ import numpy as np from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions from ...utils import DownloadFile, DownloadFileInput -from ...utils.logger import Logger +from ...utils.log import logger from ..base import FileInfo, InferSession from .provider_config import ProviderConfig class OrtInferSession(InferSession): def __init__(self, cfg: Dict[str, Any]): - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger # support custom session (PR #451) session = cfg.get("session", None) diff --git a/python/rapidocr/inference_engine/onnxruntime/provider_config.py b/python/rapidocr/inference_engine/onnxruntime/provider_config.py index 23f4b5d..8b47144 100644 --- a/python/rapidocr/inference_engine/onnxruntime/provider_config.py +++ b/python/rapidocr/inference_engine/onnxruntime/provider_config.py @@ -7,7 +7,7 @@ from typing import Any, Dict, List, Sequence, Tuple from onnxruntime import get_available_providers, get_device -from ...utils.logger import Logger +from ...utils.log import logger class EP(Enum): @@ -19,7 +19,7 @@ class EP(Enum): class ProviderConfig: def __init__(self, engine_cfg: Dict[str, Any]): - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger self.had_providers: List[str] = get_available_providers() self.default_provider = self.had_providers[0] diff --git a/python/rapidocr/inference_engine/openvino.py b/python/rapidocr/inference_engine/openvino.py index 4a3adff..a9f0484 100644 --- a/python/rapidocr/inference_engine/openvino.py +++ b/python/rapidocr/inference_engine/openvino.py @@ -10,15 +10,15 @@ import numpy as np from omegaconf import DictConfig from openvino.runtime import Core -from ..utils import Logger from ..utils.download_file import DownloadFile, DownloadFileInput +from ..utils.log import logger from .base import FileInfo, InferSession class OpenVINOInferSession(InferSession): def __init__(self, cfg: DictConfig): super().__init__(cfg) - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger core = Core() diff --git a/python/rapidocr/inference_engine/paddle.py b/python/rapidocr/inference_engine/paddle.py index 56d0245..c8a5679 100644 --- a/python/rapidocr/inference_engine/paddle.py +++ b/python/rapidocr/inference_engine/paddle.py @@ -12,14 +12,14 @@ from omegaconf.errors import ConfigKeyError from paddle import inference from ..utils.download_file import DownloadFile, DownloadFileInput -from ..utils.logger import Logger +from ..utils.log import logger from ..utils.typings import OCRVersion from .base import FileInfo, InferSession class PaddleInferSession(InferSession): def __init__(self, cfg, mode: Optional[str] = None) -> None: - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger self.mode = mode # 设置设备特定的环境变量 @@ -43,7 +43,12 @@ class PaddleInferSession(InferSession): envs = {} _set_envs(envs) - elif not any([engine_cfg.get(f"use_{dev}", False) for dev in ["cuda", "npu", "xpu", "mlu", "dcu", "gcu"]]): + elif not any( + [ + engine_cfg.get(f"use_{dev}", False) + for dev in ["cuda", "npu", "xpu", "mlu", "dcu", "gcu"] + ] + ): envs = {} _set_envs(envs) @@ -109,11 +114,11 @@ class PaddleInferSession(InferSession): return pdmodel_path, pdiparams_path def download_model( - self, model_info, default_model_dir: str, model_file_name: str + self, model_info, default_model_dir: str, model_file_name: str ) -> Path: model_file_url = f"{default_model_dir}/{model_file_name}" model_file_path = ( - self.DEFAULT_MODEL_PATH / Path(default_model_dir).name / model_file_name + self.DEFAULT_MODEL_PATH / Path(default_model_dir).name / model_file_name ) DownloadFile.run( DownloadFileInput( @@ -191,7 +196,9 @@ class PaddleInferSession(InferSession): infer_num_threads = cfg.engine_cfg.get("cpu_math_library_num_threads", -1) if infer_num_threads != -1 and 1 <= infer_num_threads <= cpu_nums: infer_opts.set_cpu_math_library_num_threads(infer_num_threads) - self.logger.info(f"Set CPU math library threads to: {infer_num_threads}") + self.logger.info( + f"Set CPU math library threads to: {infer_num_threads}" + ) if hasattr(infer_opts, "enable_new_ir"): infer_opts.enable_new_ir(True) diff --git a/python/rapidocr/inference_engine/torch.py b/python/rapidocr/inference_engine/torch.py index 1b6fb72..fc913ff 100644 --- a/python/rapidocr/inference_engine/torch.py +++ b/python/rapidocr/inference_engine/torch.py @@ -9,7 +9,7 @@ from omegaconf import OmegaConf from ..networks.architectures.base_model import BaseModel from ..utils.download_file import DownloadFile, DownloadFileInput -from ..utils.logger import Logger +from ..utils.log import logger from .base import FileInfo, InferSession root_dir = Path(__file__).resolve().parent.parent @@ -18,7 +18,7 @@ DEFAULT_CFG_PATH = root_dir / "networks" / "arch_config.yaml" class TorchInferSession(InferSession): def __init__(self, cfg) -> None: - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger model_path = cfg.get("model_path", None) if model_path is None: diff --git a/python/rapidocr/main.py b/python/rapidocr/main.py index 4eef34a..4eea334 100644 --- a/python/rapidocr/main.py +++ b/python/rapidocr/main.py @@ -3,6 +3,7 @@ # @Contact: liekkaskono@163.com import argparse import copy +import logging from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union @@ -17,7 +18,6 @@ from .ch_ppocr_rec import TextRecInput, TextRecognizer, TextRecOutput from .cli import check_install, generate_cfg from .utils import ( LoadImage, - Logger, RapidOCROutput, VisRes, add_round_letterbox, @@ -25,6 +25,7 @@ from .utils import ( get_rotate_crop_image, resize_image_within_bounds, ) +from .utils.log import logger from .utils.parse_parameters import ParseParams from .utils.typings import LangRec @@ -37,9 +38,11 @@ class RapidOCR: self, config_path: Optional[str] = None, params: Optional[Dict[str, Any]] = None ): cfg = self._load_config(config_path, params) - self._initialize(cfg) - self.logger = Logger(logger_name=__name__).get_log() + logger.setLevel(logging.getLevelName(cfg.Global.log_level.upper())) + self.logger = logger + + self._initialize(cfg) def _load_config( self, config_path: Optional[str], params: Optional[Dict[str, Any]] diff --git a/python/rapidocr/utils/__init__.py b/python/rapidocr/utils/__init__.py index c1daa88..ff42bbd 100644 --- a/python/rapidocr/utils/__init__.py +++ b/python/rapidocr/utils/__init__.py @@ -3,7 +3,6 @@ # @Contact: liekkaskono@163.com from .download_file import DownloadFile, DownloadFileException, DownloadFileInput from .load_image import LoadImage, LoadImageError -from .logger import Logger from .output import RapidOCROutput from .parse_parameters import ParseParams from .process_img import ( diff --git a/python/rapidocr/utils/logger.py b/python/rapidocr/utils/log.py similarity index 89% rename from python/rapidocr/utils/logger.py rename to python/rapidocr/utils/log.py index 5d718df..036c996 100644 --- a/python/rapidocr/utils/logger.py +++ b/python/rapidocr/utils/log.py @@ -7,7 +7,7 @@ import colorlog class Logger: - def __init__(self, log_level=logging.DEBUG, logger_name=None): + def __init__(self, log_level=logging.INFO, logger_name=None): self.logger = logging.getLogger(logger_name) self.logger.setLevel(log_level) self.logger.propagate = False @@ -35,3 +35,6 @@ class Logger: def get_log(self): return self.logger + + +logger = Logger(log_level=logging.INFO).get_log() diff --git a/python/rapidocr/utils/output.py b/python/rapidocr/utils/output.py index 2d7f3f0..2672b4f 100644 --- a/python/rapidocr/utils/output.py +++ b/python/rapidocr/utils/output.py @@ -6,14 +6,12 @@ from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np -from .logger import Logger +from .log import logger from .to_json import ToJSON from .to_markdown import ToMarkdown from .utils import save_img from .vis_res import VisRes -logger = Logger(logger_name=__name__).get_log() - @dataclass class RapidOCROutput: diff --git a/python/rapidocr/utils/vis_res.py b/python/rapidocr/utils/vis_res.py index 2121d7e..f6f3c22 100644 --- a/python/rapidocr/utils/vis_res.py +++ b/python/rapidocr/utils/vis_res.py @@ -13,7 +13,7 @@ from PIL import Image, ImageDraw, ImageFont from .download_file import DownloadFile, DownloadFileInput from .load_image import LoadImage -from .logger import Logger +from .log import logger from .typings import LangRec root_dir = Path(__file__).resolve().parent.parent @@ -31,7 +31,7 @@ class VisRes: lang_type: Optional[LangRec] = None, font_path: Optional[str] = None, ): - self.logger = Logger(logger_name=__name__).get_log() + self.logger = logger self.text_score = text_score self.load_img = LoadImage() diff --git a/python/tests/test_main.py b/python/tests/test_main.py index 6ccdcef..ddb5cf4 100644 --- a/python/tests/test_main.py +++ b/python/tests/test_main.py @@ -16,12 +16,10 @@ sys.path.append(str(root_dir)) from rapidocr import EngineType, LangRec, LoadImageError, ModelType, RapidOCR from rapidocr.main import main -from rapidocr.utils.logger import Logger from rapidocr.utils.typings import OCRVersion tests_dir = root_dir / "tests" / "test_files" img_path = tests_dir / "ch_en_num.jpg" -logger = Logger(logger_name=__name__).get_log() @pytest.fixture()