π Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
perf: lazily initialize OCR models
SWHL0ad7c04d8cc4
diff --git a/python/rapidocr/main.py b/python/rapidocr/main.pyindex cdd9a73..fbce202 100644--- a/python/rapidocr/main.py+++ b/python/rapidocr/main.py@@ -39,11 +39,11 @@ class RapidOCR:def __init__(self, config_path: Optional[str] = None, params: Optional[Dict[str, Any]] = None):- cfg = self._load_config(config_path, params)+ self.cfg = self._load_config(config_path, params)- logger.setLevel(cfg.Global.log_level.upper())+ logger.setLevel(self.cfg.Global.log_level.upper())- self._initialize(cfg)+ self._initialize(self.cfg)def _load_config(self, config_path: Optional[str], params: Optional[Dict[str, Any]]@@ -66,20 +66,13 @@ class RapidOCR:self.width_height_ratio = cfg.Global.width_height_ratioself.use_det = cfg.Global.use_det- cfg.Det.engine_cfg = cfg.EngineConfig[cfg.Det.engine_type.value]- cfg.Det.model_root_dir = cfg.Global.model_root_dir- self.text_det = TextDetector(cfg.Det)+ self.text_det = Noneself.use_cls = cfg.Global.use_cls- cfg.Cls.engine_cfg = cfg.EngineConfig[cfg.Cls.engine_type.value]- cfg.Cls.model_root_dir = cfg.Global.model_root_dir- self.text_cls = TextClassifier(cfg.Cls)+ self.text_cls = Noneself.use_rec = cfg.Global.use_rec- cfg.Rec.engine_cfg = cfg.EngineConfig[cfg.Rec.engine_type.value]- cfg.Rec.font_path = cfg.Global.font_path- cfg.Rec.model_root_dir = cfg.Global.model_root_dir- self.text_rec = TextRecognizer(cfg.Rec)+ self.text_rec = Noneself.load_img = LoadImage()self.max_side_len = cfg.Global.max_side_len@@ -122,6 +115,34 @@ class RapidOCR:ori_img, det_res, cls_res, rec_res, cropped_img_list, op_record)+ def _load_det_model(self):+ if self.text_det is None:+ self.cfg.Det.engine_cfg = self.cfg.EngineConfig[+ self.cfg.Det.engine_type.value+ ]+ self.cfg.Det.model_root_dir = self.cfg.Global.model_root_dir+ self.text_det = TextDetector(self.cfg.Det)+ return self.text_det++ def _load_cls_model(self):+ if self.text_cls is None:+ self.cfg.Cls.engine_cfg = self.cfg.EngineConfig[+ self.cfg.Cls.engine_type.value+ ]+ self.cfg.Cls.model_root_dir = self.cfg.Global.model_root_dir+ self.text_cls = TextClassifier(self.cfg.Cls)+ return self.text_cls++ def _load_rec_model(self):+ if self.text_rec is None:+ self.cfg.Rec.engine_cfg = self.cfg.EngineConfig[+ self.cfg.Rec.engine_type.value+ ]+ self.cfg.Rec.font_path = self.cfg.Global.font_path+ self.cfg.Rec.model_root_dir = self.cfg.Global.model_root_dir+ self.text_rec = TextRecognizer(self.cfg.Rec)+ return self.text_rec+def run_ocr_steps(self, img: np.ndarray, op_record: Dict[str, Any]):det_res, cls_res, rec_res = TextDetOutput(), TextClsOutput(), TextRecOutput()@@ -260,14 +281,20 @@ class RapidOCR:"return_word_box": ("return_word_box",),"return_single_char_box": ("return_single_char_box",),"text_score": ("text_score",),- "box_thresh": ("text_det", "postprocess_op", "box_thresh"),- "unclip_ratio": ("text_det", "postprocess_op", "unclip_ratio"),}+ det_params = {"box_thresh", "unclip_ratio"}for key, value in kwargs.items():if value is None:continue+ if key in det_params:+ setattr(self.cfg.Det, key, value)++ if self.text_det is not None:+ setattr(self.text_det.postprocess_op, key, value)+ continue+path = param_map.get(key)if not path:raise ValueError(f"Unknown parameter: {key}")@@ -291,6 +318,8 @@ class RapidOCR:def detect_and_crop(self, img: np.ndarray, op_record: Dict[str, Any]) -> Tuple[List[np.ndarray], TextDetOutput]:+ det_model = self._load_det_model()+if self.cfg.Global.use_vertical_padding:img, op_record = apply_vertical_padding(img, op_record, self.width_height_ratio, self.min_height@@ -298,7 +327,7 @@ class RapidOCR:else:op_record["padding_1"] = {"top": 0, "left": 0}- det_res = self.text_det(img)+ det_res = det_model(img)if det_res.boxes is None:raise RapidOCRError("The text detection result is empty")@@ -317,15 +346,18 @@ class RapidOCR:def cls_and_rotate(self, img: List[np.ndarray]) -> Tuple[List[np.ndarray], TextClsOutput]:- cls_res = self.text_cls(img)+ cls_model = self._load_cls_model()++ cls_res = cls_model(img)if cls_res.img_list is None:raise RapidOCRError("The text classifier is empty")return cls_res.img_list, cls_resdef recognize_txt(self, img: List[np.ndarray]) -> TextRecOutput:+ rec_model = self._load_rec_model()rec_input = TextRecInput(img=img, return_word_box=self.return_word_box)- rec_res = self.text_rec(rec_input)+ rec_res = rec_model(rec_input)if rec_res.txts is None:raise RapidOCRError("The text recognize result is empty")diff --git a/python/tests/test_default_config.py b/python/tests/test_default_config.pyindex 44d5346..c73e50c 100644--- a/python/tests/test_default_config.py+++ b/python/tests/test_default_config.py@@ -2,6 +2,7 @@# @Author: SWHL# @Contact: [email protected]from pathlib import Path+from types import SimpleNamespaceimport pytest@@ -245,11 +246,32 @@ def test_default_engine_runtime_config(default_engine):assert default_engine.cfg.Rec.model_type == ModelType.SMALLassert default_engine.cfg.Cls.ocr_version == OCRVersion.PPOCRV4assert default_engine.cfg.Cls.model_type == ModelType.MOBILE- assert default_engine.text_det.limit_side_len == 736- assert default_engine.text_det.limit_type == "min"- assert default_engine.text_cls.cls_image_shape == [3, 48, 192]- assert default_engine.text_rec.rec_image_shape == [3, 48, 320]- assert default_engine.text_rec.rec_batch_num == 6+++def test_update_det_params_before_model_load():+ engine = RapidOCR()++ assert engine.text_det is None++ engine.update_params(box_thresh=0.7, unclip_ratio=2.0)++ assert engine.text_det is None+ assert engine.cfg.Det.box_thresh == 0.7+ assert engine.cfg.Det.unclip_ratio == 2.0+++def test_update_det_params_after_model_load():+ engine = RapidOCR()+ engine.text_det = SimpleNamespace(+ postprocess_op=SimpleNamespace(box_thresh=0.5, unclip_ratio=1.6)+ )++ engine.update_params(box_thresh=0.7, unclip_ratio=2.0)++ assert engine.cfg.Det.box_thresh == 0.7+ assert engine.cfg.Det.unclip_ratio == 2.0+ assert engine.text_det.postprocess_op.box_thresh == 0.7+ assert engine.text_det.postprocess_op.unclip_ratio == 2.0def test_default_engine_real_full_pipeline(default_engine):diff --git a/python/tests/test_image_preprocessing.py b/python/tests/test_image_preprocessing.pyindex 635e1d8..4f8ad97 100644--- a/python/tests/test_image_preprocessing.py+++ b/python/tests/test_image_preprocessing.py@@ -12,9 +12,7 @@ from rapidocr.ch_ppocr_det import TextDetOutputdef test_preprocess_img_returns_original_when_disabled(monkeypatch):engine = RapidOCR.__new__(RapidOCR)- engine.cfg = SimpleNamespace(- Global=SimpleNamespace(use_preprocess_img=False)- )+ engine.cfg = SimpleNamespace(Global=SimpleNamespace(use_preprocess_img=False))ori_img = np.zeros((20, 40, 3), dtype=np.uint8)def fail_if_called(*args, **kwargs):@@ -30,9 +28,7 @@ def test_preprocess_img_returns_original_when_disabled(monkeypatch):def test_detect_and_crop_skips_vertical_padding_when_disabled(monkeypatch):engine = RapidOCR.__new__(RapidOCR)- engine.cfg = SimpleNamespace(- Global=SimpleNamespace(use_vertical_padding=False)- )+ engine.cfg = SimpleNamespace(Global=SimpleNamespace(use_vertical_padding=False))img = np.zeros((20, 40, 3), dtype=np.uint8)boxes = np.array([[[0, 0], [10, 0], [10, 10], [0, 10]]], dtype=np.float32)detected_images = []