π Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
chore: update files
SWHLf10eab5a360b
diff --git a/python/demo.py b/python/demo.pyindex 4d456d6..209a5b7 100644--- a/python/demo.py+++ b/python/demo.py@@ -11,7 +11,10 @@ from rapidocr import RapidOCR, VisRes# from rapidocr_paddle import RapidOCR, VisRes# from rapidocr_openvino import RapidOCR, VisRes-engine = RapidOCR()+# yaml_path = "tests/test_files/config.yaml"+# engine = RapidOCR(config_path=yaml_path)++engine = RapidOCR(params={"Cls.model_path": "1.onnx"})vis = VisRes()image_path = "tests/test_files/ch_en_num.jpg"diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yamlindex 6d314c7..b4f114b 100644--- a/python/rapidocr/config.yaml+++ b/python/rapidocr/config.yaml@@ -17,7 +17,7 @@ Global:with_paddle: falsewith_torch: false-InferEngineConfig:+EngineConfig:onnxruntime:intra_op_num_threads: -1inter_op_num_threads: -1diff --git a/python/rapidocr/main.py b/python/rapidocr/main.pyindex 2df4199..7232f54 100644--- a/python/rapidocr/main.py+++ b/python/rapidocr/main.py@@ -7,7 +7,6 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport cv2import numpy as np-from omegaconf import OmegaConffrom .cal_rec_boxes import CalRecBoxesfrom .ch_ppocr_cls import TextClassifier, TextClsOutput@@ -17,7 +16,6 @@ from .inference_engine import get_engine_namefrom .utils import (LoadImage,RapidOCROutput,- UpdateParameters,VisRes,add_round_letterbox,get_logger,@@ -25,8 +23,8 @@ from .utils import (init_args,parse_lang,reduce_max_side,- update_model_path,)+from .utils.parse_parameters import ParseParamsroot_dir = Path(__file__).resolve().parentDEFAULT_CFG_PATH = root_dir / "config.yaml"@@ -34,16 +32,17 @@ logger = get_logger("RapidOCR")class RapidOCR:- def __init__(self, config_path: Optional[str] = None, **kwargs):+ def __init__(+ self, config_path: Optional[str] = None, params: Optional[Dict[str, Any]] = None+ ):if config_path is not None and Path(config_path).exists():- config = OmegaConf.load(config_path)+ config = ParseParams.load(config_path)else:- config = OmegaConf.load(DEFAULT_CFG_PATH)- config = update_model_path(config)+ config = ParseParams.load(DEFAULT_CFG_PATH)+ config = ParseParams.update_model_path(config)- if kwargs:- updater = UpdateParameters()- config = updater(config, **kwargs)+ if params:+ config = ParseParams.update_batch(config, params)engine_name = get_engine_name(config)@@ -58,18 +57,18 @@ class RapidOCR:self.use_det = config.Global.use_detconfig.Det.lang = det_langconfig.Det.engine_name = engine_name- config.Det.engine_cfg = config.InferEngineConfig[engine_name]+ config.Det.engine_cfg = config.EngineConfig[engine_name]self.text_det = TextDetector(config.Det)self.use_cls = config.Global.use_clsconfig.Cls.engine_name = engine_name- config.Cls.engine_cfg = config.InferEngineConfig[engine_name]+ config.Cls.engine_cfg = config.EngineConfig[engine_name]self.text_cls = TextClassifier(config.Cls)self.use_rec = config.Global.use_recconfig.Rec.lang = rec_langconfig.Rec.engine_name = engine_name- config.Rec.engine_cfg = config.InferEngineConfig[engine_name]+ config.Rec.engine_cfg = config.EngineConfig[engine_name]self.text_rec = TextRecognizer(config.Rec)self.load_img = LoadImage()@@ -314,7 +313,7 @@ class RapidOCR:def export_config(self, save_path: Union[Path, str]) -> None:with open(save_path, "w", encoding="utf-8") as f:- OmegaConf.save(self.config, f)+ ParseParams.save(self.config, f)def main():diff --git a/python/rapidocr/utils/__init__.py b/python/rapidocr/utils/__init__.pyindex 7535b42..fd66bf8 100644--- a/python/rapidocr/utils/__init__.py+++ b/python/rapidocr/utils/__init__.py@@ -3,7 +3,7 @@# @Contact: [email protected]from .load_image import LoadImage, LoadImageErrorfrom .logger import get_logger-from .parse_parameters import UpdateParameters, init_args, parse_lang, update_model_path+from .parse_parameters import ParseParams, init_args, parse_langfrom .process_img import add_round_letterbox, increase_min_side, reduce_max_sidefrom .typings import RapidOCROutputfrom .vis_res import VisResdiff --git a/python/rapidocr/utils/parse_parameters.py b/python/rapidocr/utils/parse_parameters.pyindex f1d79cd..c8d4216 100644--- a/python/rapidocr/utils/parse_parameters.py+++ b/python/rapidocr/utils/parse_parameters.py@@ -3,7 +3,7 @@# @Contact: [email protected]import argparsefrom pathlib import Path-from typing import Dict, List, Optional, Union+from typing import Dict, Unionimport numpy as npfrom omegaconf import DictConfig, OmegaConf@@ -101,12 +101,6 @@ def parse_lang(lang):elif lang in devanagari_lang:lang = "devanagari"- assert (- lang in MODEL_URLS["OCR"][DEFAULT_OCR_MODEL_VERSION]["rec"]- ), "param lang must in {}, but got {}".format(- MODEL_URLS["OCR"][DEFAULT_OCR_MODEL_VERSION]["rec"].keys(), lang- )-if lang == "ch":det_lang = "ch"elif lang in ["en", "latin"]:@@ -117,12 +111,22 @@ def parse_lang(lang):return det_lang, lang-def update_model_path(config: DictConfig) -> DictConfig:- key = "model_path"- OmegaConf.update(config, f"Det.{key}", str(root_dir / config.Det[key]))- OmegaConf.update(config, f"Cls.{key}", str(root_dir / config.Cls[key]))- OmegaConf.update(config, f"Rec.{key}", str(root_dir / config.Rec[key]))- return config+class ParseParams(OmegaConf):+ def __init__(self):+ pass++ @classmethod+ def update_model_path(cls, cfg: DictConfig, key: str = "model_path") -> DictConfig:+ cls.update(cfg, f"Det.{key}", str(root_dir / cfg.Det[key]))+ cls.update(cfg, f"Cls.{key}", str(root_dir / cfg.Cls[key]))+ cls.update(cfg, f"Rec.{key}", str(root_dir / cfg.Rec[key]))+ return cfg++ @classmethod+ def update_batch(cls, cfg: DictConfig, params: Dict[str, str]) -> DictConfig:+ for k, v in params.items():+ cls.update(cfg, k, v)+ return cfgdef init_args():@@ -199,103 +203,3 @@ def init_args():args = parser.parse_args()return args---class UpdateParameters:- def __init__(self) -> None:- pass-- def parse_kwargs(self, **kwargs):- global_dict, det_dict, cls_dict, rec_dict = {}, {}, {}, {}- for k, v in kwargs.items():- if k.startswith("det"):- k = k.split("det_")[1]- if k == "donot_use_dilation":- k = "use_dilation"- v = not v-- det_dict[k] = v- elif k.startswith("cls"):- cls_dict[k] = v- elif k.startswith("rec"):- rec_dict[k] = v- else:- global_dict[k] = v- return global_dict, det_dict, cls_dict, rec_dict-- def __call__(self, config, **kwargs):- global_dict, det_dict, cls_dict, rec_dict = self.parse_kwargs(**kwargs)- new_config = {- "Global": self.update_global_params(config["Global"], global_dict),- "Det": self.update_params(- config["Det"],- det_dict,- "det_",- ["det_model_path", "det_use_cuda", "det_use_dml"],- ),- "Cls": self.update_params(- config["Cls"],- cls_dict,- "cls_",- ["cls_label_list", "cls_model_path", "cls_use_cuda", "cls_use_dml"],- ),- "Rec": self.update_params(- config["Rec"],- rec_dict,- "rec_",- ["rec_model_path", "rec_use_cuda", "rec_use_dml"],- ),- }-- update_params = ["intra_op_num_threads", "inter_op_num_threads"]- new_config = self.update_global_to_module(- config, update_params, src="Global", dsts=["Det", "Cls", "Rec"]- )- return new_config-- def update_global_to_module(- self, config, params: List[str], src: str, dsts: List[str]- ):- for dst in dsts:- for param in params:- config[dst].update({param: config[src][param]})- return config-- def update_global_params(self, config, global_dict):- if global_dict:- config.update(global_dict)- return config-- def update_params(- self,- config,- param_dict: Dict[str, str],- prefix: str,- need_remove_prefix: Optional[List[str]] = None,- ):- if not param_dict:- return config-- filter_dict = self.remove_prefix(param_dict, prefix, need_remove_prefix)- model_path = filter_dict.get("model_path", None)- if not model_path:- filter_dict["model_path"] = str(root_dir / config["model_path"])-- config.update(filter_dict)- return config-- @staticmethod- def remove_prefix(- config: Dict[str, str],- prefix: str,- need_remove_prefix: Optional[List[str]] = None,- ) -> Dict[str, str]:- if not need_remove_prefix:- return config-- new_rec_dict = {}- for k, v in config.items():- if k in need_remove_prefix:- k = k.split(prefix)[1]- new_rec_dict[k] = v- return new_rec_dictdiff --git a/python/tests/test_files/config.yaml b/python/tests/test_files/config.yamlnew file mode 100644index 0000000..b4f114b--- /dev/null+++ b/python/tests/test_files/config.yaml@@ -0,0 +1,62 @@+Global:+ lang: "ch"+ text_score: 0.5+ use_det: true+ use_cls: true+ use_rec: true++ print_verbose: false+ min_height: 30+ width_height_ratio: 8+ max_side_len: 2000+ min_side_len: 30+ return_word_box: false++ with_onnx: false+ with_openvino: false+ with_paddle: false+ with_torch: false++EngineConfig:+ onnxruntime:+ intra_op_num_threads: -1+ inter_op_num_threads: -1+ use_cuda: false+ use_dml: false++ paddlepaddle:+ cpu_math_library_num_threads: -1+ gpu_id: 0+ gpu_mem: 500++Det:+ model_path: models/ch_PP-OCRv4_det_infer.onnx+ paddle_model_dir: models/paddle/ch_PP-OCRv4_det_infer++ limit_side_len: 736+ limit_type: min+ std: [ 0.5, 0.5, 0.5 ]+ mean: [ 0.5, 0.5, 0.5 ]++ thresh: 0.3+ box_thresh: 0.5+ max_candidates: 1000+ unclip_ratio: 1.6+ use_dilation: true+ score_mode: fast++Cls:+ model_path: models/ch_ppocr_mobile_v2.0_cls_infer.onnx+ paddle_model_dir: models/paddle/ch_ppocr_mobile_v2_cls_infer++ cls_image_shape: [3, 48, 192]+ cls_batch_num: 6+ cls_thresh: 0.9+ label_list: ['0', '180']++Rec:+ model_path: models/ch_PP-OCRv4_rec_infer.onnx+ paddle_model_dir: models/paddle/ch_PP-OCRv4_rec_infer++ rec_img_shape: [3, 48, 320]+ rec_batch_num: 6diff --git a/python/tests/test_main.py b/python/tests/test_main.pyindex b46c578..85517e2 100644--- a/python/tests/test_main.py+++ b/python/tests/test_main.py@@ -36,7 +36,9 @@ def test_long_img():def test_ort_cuda_warning(caplog):- engine = RapidOCR(det_use_cuda=True)+ engine = RapidOCR(+ params={"Global.with_onnx": True, "EngineConfig.onnxruntime.use_cuda": True}+ )caplog.set_level(logging.WARNING)assert caplog.records[0].levelname == "WARNING"@@ -44,7 +46,9 @@ def test_ort_cuda_warning(caplog):def test_ort_dml_warning(caplog):- engine = RapidOCR(det_use_dml=True)+ engine = RapidOCR(+ params={"Global.with_onnx": True, "EngineConfig.onnxruntime.use_dml": True}+ )caplog.set_level(logging.WARNING)assert caplog.records[0].levelname == "WARNING"@@ -173,14 +177,14 @@ def test_input_path():def test_input_parameters():img_path = tests_dir / "ch_en_num.jpg"- engine = RapidOCR(text_score=1)+ engine = RapidOCR(params={"Global.text_score": 1})result = engine(img_path)assert result.boxes is Nonedef test_input_det_parameters():with pytest.raises(FileNotFoundError) as exc_info:- engine = RapidOCR(det_model_path="1.onnx")+ engine = RapidOCR(params={"Det.model_path": "1.onnx"})result = engine(img_path)raise FileNotFoundError()assert exc_info.type is FileNotFoundError@@ -188,7 +192,7 @@ def test_input_det_parameters():def test_input_cls_parameters():with pytest.raises(FileNotFoundError) as exc_info:- engine = RapidOCR(cls_model_path="1.onnx")+ engine = RapidOCR(params={"Cls.model_path": "1.onnx"})result = engine(img_path)raise FileNotFoundError()assert exc_info.type is FileNotFoundError@@ -196,7 +200,7 @@ def test_input_cls_parameters():def test_input_rec_parameters():with pytest.raises(FileNotFoundError) as exc_info:- engine = RapidOCR(rec_model_path="1.onnx")+ engine = RapidOCR(params={"Rec.model_path": "1.onnx"})result = engine(img_path)raise FileNotFoundError()assert exc_info.type is FileNotFoundError