π Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
refactor: modularize MNN and OpenVINO Inference Engines (#629)
locviettri4818b4f1e135
diff --git a/python/rapidocr/inference_engine/mnn/__init__.py b/python/rapidocr/inference_engine/mnn/__init__.pynew file mode 100644index 0000000..8185667--- /dev/null+++ b/python/rapidocr/inference_engine/mnn/__init__.py@@ -0,0 +1,4 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+from .main import MNNError, MNNInferSessiondiff --git a/python/rapidocr/inference_engine/mnn.py b/python/rapidocr/inference_engine/mnn/main.pysimilarity index 89%rename from python/rapidocr/inference_engine/mnn.pyrename to python/rapidocr/inference_engine/mnn/main.pyindex 45034ea..09934d4 100644--- a/python/rapidocr/inference_engine/mnn.py+++ b/python/rapidocr/inference_engine/mnn/main.py@@ -1,4 +1,6 @@# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]import tracebackfrom pathlib import Path@@ -6,9 +8,9 @@ import MNNimport numpy as npfrom omegaconf import DictConfig-from ..utils.download_file import DownloadFile, DownloadFileInput-from ..utils.log import logger-from .base import FileInfo, InferSession+from ...utils.download_file import DownloadFile, DownloadFileInput+from ...utils.log import logger+from ..base import FileInfo, InferSessionclass MNNInferSession(InferSession):@@ -59,9 +61,7 @@ class MNNInferSession(InferSession):output = self.interpreter.getSessionOutput(self.session)out_shape = output.getShape()out_tensor = MNN.Tensor(- out_shape,- MNN.Halide_Type_Float,- MNN.Tensor_DimensionType_Caffe+ out_shape, MNN.Halide_Type_Float, MNN.Tensor_DimensionType_Caffe)output.copyToHostTensor(out_tensor)diff --git a/python/rapidocr/inference_engine/openvino/__init__.py b/python/rapidocr/inference_engine/openvino/__init__.pynew file mode 100644index 0000000..bd42998--- /dev/null+++ b/python/rapidocr/inference_engine/openvino/__init__.py@@ -0,0 +1,4 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+from .main import OpenVINOInferSession, OpenVIONErrordiff --git a/python/rapidocr/inference_engine/openvino/device_config.py b/python/rapidocr/inference_engine/openvino/device_config.pynew file mode 100644index 0000000..baea701--- /dev/null+++ b/python/rapidocr/inference_engine/openvino/device_config.py@@ -0,0 +1,51 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+import os+from typing import Any, Dict++from omegaconf import DictConfig++from ...utils.log import logger+++class CPUConfig:+ """Configuration handler for OpenVINO CPU execution."""++ def __init__(self, engine_cfg: DictConfig):+ self.cfg = engine_cfg++ def get_config(self) -> Dict[str, Any]:+ """Build OpenVINO CPU configuration dictionary."""+ config = {}++ infer_num_threads = self.cfg.get("inference_num_threads", -1)+ if infer_num_threads != -1 and 1 <= infer_num_threads <= os.cpu_count():+ config["INFERENCE_NUM_THREADS"] = str(infer_num_threads)++ performance_hint = self.cfg.get("performance_hint", None)+ if performance_hint is not None:+ config["PERFORMANCE_HINT"] = str(performance_hint)++ performance_num_requests = self.cfg.get("performance_num_requests", -1)+ if performance_num_requests != -1:+ config["PERFORMANCE_HINT_NUM_REQUESTS"] = str(performance_num_requests)++ enable_cpu_pinning = self.cfg.get("enable_cpu_pinning", None)+ if enable_cpu_pinning is not None:+ config["ENABLE_CPU_PINNING"] = str(enable_cpu_pinning)++ num_streams = self.cfg.get("num_streams", -1)+ if num_streams != -1:+ config["NUM_STREAMS"] = str(num_streams)++ enable_hyper_threading = self.cfg.get("enable_hyper_threading", None)+ if enable_hyper_threading is not None:+ config["ENABLE_HYPER_THREADING"] = str(enable_hyper_threading)++ scheduling_core_type = self.cfg.get("scheduling_core_type", None)+ if scheduling_core_type is not None:+ config["SCHEDULING_CORE_TYPE"] = str(scheduling_core_type)++ logger.info(f"Using OpenVINO config: {config}")+ return configdiff --git a/python/rapidocr/inference_engine/openvino.py b/python/rapidocr/inference_engine/openvino/main.pysimilarity index 50%rename from python/rapidocr/inference_engine/openvino.pyrename to python/rapidocr/inference_engine/openvino/main.pyindex c50c02c..b9fe5cd 100644--- a/python/rapidocr/inference_engine/openvino.py+++ b/python/rapidocr/inference_engine/openvino/main.py@@ -1,21 +1,21 @@# -*- encoding: utf-8 -*-# @Author: SWHL# @Contact: [email protected]-import osimport tracebackfrom pathlib import Path-from typing import Any, Dictimport numpy as npfrom omegaconf import DictConfig+try:from openvino import Core-except ImportError: # fallback for older OpenVINO versions+except ImportError:from openvino.runtime import Core-from ..utils.download_file import DownloadFile, DownloadFileInput-from ..utils.log import logger-from .base import FileInfo, InferSession+from ...utils.download_file import DownloadFile, DownloadFileInput+from ...utils.log import logger+from ..base import FileInfo, InferSession+from .device_config import CPUConfigclass OpenVINOInferSession(InferSession):@@ -48,48 +48,14 @@ class OpenVINOInferSession(InferSession):model_path = Path(model_path)self._verify_model(model_path)- config = self._init_config(cfg)- core.set_property("CPU", config)+ # Use dedicated config class+ cpu_config = CPUConfig(cfg.get("engine_cfg", {}))+ core.set_property("CPU", cpu_config.get_config())model_onnx = core.read_model(model_path)compile_model = core.compile_model(model=model_onnx, device_name="CPU")self.session = compile_model.create_infer_request()- def _init_config(self, cfg: DictConfig) -> Dict[Any, Any]:- config = {}- engine_cfg = cfg.get("engine_cfg", {})-- infer_num_threads = engine_cfg.get("inference_num_threads", -1)- if infer_num_threads != -1 and 1 <= infer_num_threads <= os.cpu_count():- config["INFERENCE_NUM_THREADS"] = str(infer_num_threads)-- performance_hint = engine_cfg.get("performance_hint", None)- if performance_hint is not None:- config["PERFORMANCE_HINT"] = str(performance_hint)-- performance_num_requests = engine_cfg.get("performance_num_requests", -1)- if performance_num_requests != -1:- config["PERFORMANCE_HINT_NUM_REQUESTS"] = str(performance_num_requests)-- enable_cpu_pinning = engine_cfg.get("enable_cpu_pinning", None)- if enable_cpu_pinning is not None:- config["ENABLE_CPU_PINNING"] = str(enable_cpu_pinning)-- num_streams = engine_cfg.get("num_streams", -1)- if num_streams != -1:- config["NUM_STREAMS"] = str(num_streams)-- enable_hyper_threading = engine_cfg.get("enable_hyper_threading", None)- if enable_hyper_threading is not None:- config["ENABLE_HYPER_THREADING"] = str(enable_hyper_threading)-- scheduling_core_type = engine_cfg.get("scheduling_core_type", None)- if scheduling_core_type is not None:- config["SCHEDULING_CORE_TYPE"] = str(scheduling_core_type)-- logger.info(f"Using OpenVINO config: {config}")- return config-def __call__(self, input_content: np.ndarray) -> np.ndarray:try:self.session.infer(inputs=[input_content])diff --git a/python/rapidocr/inference_engine/paddle/device_config.py b/python/rapidocr/inference_engine/paddle/device_config.pyindex 9acddb5..d059940 100644--- a/python/rapidocr/inference_engine/paddle/device_config.py+++ b/python/rapidocr/inference_engine/paddle/device_config.py@@ -70,7 +70,8 @@ class DeviceConfig:if hasattr(self.infer_opts, "enable_new_executor"):self.infer_opts.enable_new_executor()- self.infer_opts.set_optimization_level(3)+ if hasattr(self.infer_opts, "set_optimization_level"):+ self.infer_opts.set_optimization_level(3)@staticmethoddef setup_device_envs(envs):