📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
fix: fixed issue #531
SWHL336e6424a5cb
diff --git a/python/rapidocr/ch_ppocr_cls/utils.py b/python/rapidocr/ch_ppocr_cls/utils.pyindex 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, Unionimport numpy as np-from ..utils.logger import Logger+from ..utils.log import loggerfrom ..utils.utils import save_imgfrom ..utils.vis_res import VisRes-logger = Logger(logger_name=__name__).get_log()-@dataclassclass TextClsOutput:diff --git a/python/rapidocr/ch_ppocr_det/utils.py b/python/rapidocr/ch_ppocr_det/utils.pyindex 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 npimport pyclipperfrom shapely.geometry import Polygon-from ..utils.logger import Logger+from ..utils.log import loggerfrom ..utils.utils import save_imgfrom ..utils.vis_res import VisRes-logger = Logger(logger_name=__name__).get_log()-@dataclassclass TextDetOutput:diff --git a/python/rapidocr/ch_ppocr_rec/main.py b/python/rapidocr/ch_ppocr_rec/main.pyindex 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 npfrom rapidocr.inference_engine.base import FileInfo, get_engine-from ..utils import Loggerfrom ..utils.download_file import DownloadFile, DownloadFileInput+from ..utils.log import loggerfrom ..utils.vis_res import VisResfrom .typings import TextRecInput, TextRecOutputfrom .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_pathcharacter, 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.pyindex 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, Unionimport numpy as np-from ..utils.logger import Logger+from ..utils.log import loggerfrom ..utils.utils import save_imgfrom ..utils.vis_res import VisRes-logger = Logger(logger_name=__name__).get_log()-@dataclassclass TextRecConfig:diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yamlindex e1ece5b..b43d622 100644--- a/python/rapidocr/config.yaml+++ b/python/rapidocr/config.yaml@@ -14,6 +14,7 @@ Global:return_single_char_box: falsefont_path: null+ log_level: "info" # debug / info / warning / error / criticalEngineConfig:onnxruntime:diff --git a/python/rapidocr/inference_engine/base.py b/python/rapidocr/inference_engine/base.pyindex 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, Unionimport numpy as npfrom omegaconf import OmegaConf-from ..utils.logger import Logger+from ..utils.log import loggerfrom ..utils.typings import EngineType, ModelType, OCRVersion, TaskTypefrom ..utils.utils import import_packagecur_dir = Path(__file__).resolve().parent.parentMODEL_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.abstractmethoddef __init__(self, config):diff --git a/python/rapidocr/inference_engine/onnxruntime/main.py b/python/rapidocr/inference_engine/onnxruntime/main.pyindex 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 npfrom onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptionsfrom ...utils import DownloadFile, DownloadFileInput-from ...utils.logger import Logger+from ...utils.log import loggerfrom ..base import FileInfo, InferSessionfrom .provider_config import ProviderConfigclass 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.pyindex 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, Tuplefrom onnxruntime import get_available_providers, get_device-from ...utils.logger import Logger+from ...utils.log import loggerclass 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 = loggerself.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.pyindex 4a3adff..a9f0484 100644--- a/python/rapidocr/inference_engine/openvino.py+++ b/python/rapidocr/inference_engine/openvino.py@@ -10,15 +10,15 @@ import numpy as npfrom omegaconf import DictConfigfrom openvino.runtime import Core-from ..utils import Loggerfrom ..utils.download_file import DownloadFile, DownloadFileInput+from ..utils.log import loggerfrom .base import FileInfo, InferSessionclass OpenVINOInferSession(InferSession):def __init__(self, cfg: DictConfig):super().__init__(cfg)- self.logger = Logger(logger_name=__name__).get_log()+ self.logger = loggercore = Core()diff --git a/python/rapidocr/inference_engine/paddle.py b/python/rapidocr/inference_engine/paddle.pyindex 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 ConfigKeyErrorfrom paddle import inferencefrom ..utils.download_file import DownloadFile, DownloadFileInput-from ..utils.logger import Logger+from ..utils.log import loggerfrom ..utils.typings import OCRVersionfrom .base import FileInfo, InferSessionclass PaddleInferSession(InferSession):def __init__(self, cfg, mode: Optional[str] = None) -> None:- self.logger = Logger(logger_name=__name__).get_log()+ self.logger = loggerself.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_pathdef 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.pyindex 1b6fb72..fc913ff 100644--- a/python/rapidocr/inference_engine/torch.py+++ b/python/rapidocr/inference_engine/torch.py@@ -9,7 +9,7 @@ from omegaconf import OmegaConffrom ..networks.architectures.base_model import BaseModelfrom ..utils.download_file import DownloadFile, DownloadFileInput-from ..utils.logger import Logger+from ..utils.log import loggerfrom .base import FileInfo, InferSessionroot_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 = loggermodel_path = cfg.get("model_path", None)if model_path is None:diff --git a/python/rapidocr/main.py b/python/rapidocr/main.pyindex 4eef34a..4eea334 100644--- a/python/rapidocr/main.py+++ b/python/rapidocr/main.py@@ -3,6 +3,7 @@# @Contact: [email protected]import argparseimport copy+import loggingfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple, Union@@ -17,7 +18,6 @@ from .ch_ppocr_rec import TextRecInput, TextRecognizer, TextRecOutputfrom .cli import check_install, generate_cfgfrom .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 loggerfrom .utils.parse_parameters import ParseParamsfrom .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__.pyindex c1daa88..ff42bbd 100644--- a/python/rapidocr/utils/__init__.py+++ b/python/rapidocr/utils/__init__.py@@ -3,7 +3,6 @@# @Contact: [email protected]from .download_file import DownloadFile, DownloadFileException, DownloadFileInputfrom .load_image import LoadImage, LoadImageError-from .logger import Loggerfrom .output import RapidOCROutputfrom .parse_parameters import ParseParamsfrom .process_img import (diff --git a/python/rapidocr/utils/logger.py b/python/rapidocr/utils/log.pysimilarity index 89%rename from python/rapidocr/utils/logger.pyrename to python/rapidocr/utils/log.pyindex 5d718df..036c996 100644--- a/python/rapidocr/utils/logger.py+++ b/python/rapidocr/utils/log.py@@ -7,7 +7,7 @@ import colorlogclass 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.pyindex 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, Unionimport numpy as np-from .logger import Logger+from .log import loggerfrom .to_json import ToJSONfrom .to_markdown import ToMarkdownfrom .utils import save_imgfrom .vis_res import VisRes-logger = Logger(logger_name=__name__).get_log()-@dataclassclass RapidOCROutput:diff --git a/python/rapidocr/utils/vis_res.py b/python/rapidocr/utils/vis_res.pyindex 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, ImageFontfrom .download_file import DownloadFile, DownloadFileInputfrom .load_image import LoadImage-from .logger import Logger+from .log import loggerfrom .typings import LangRecroot_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 = loggerself.text_score = text_scoreself.load_img = LoadImage()diff --git a/python/tests/test_main.py b/python/tests/test_main.pyindex 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, RapidOCRfrom rapidocr.main import main-from rapidocr.utils.logger import Loggerfrom rapidocr.utils.typings import OCRVersiontests_dir = root_dir / "tests" / "test_files"img_path = tests_dir / "ch_en_num.jpg"-logger = Logger(logger_name=__name__).get_log()@pytest.fixture()