📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
chore: update files
SWHL6a2b9e5034c1
diff --git a/python/demo.py b/python/demo.pyindex e855434..4a84af0 100644--- a/python/demo.py+++ b/python/demo.py@@ -15,10 +15,10 @@ from rapidocr import RapidOCR, VisRes# yaml_path = "tests/test_files/config.yaml"# engine = RapidOCR(config_path=yaml_path)-engine = engine = RapidOCR(- params={"Global.with_onnx": True, "EngineConfig.onnxruntime.use_cuda": True}-)-# engine = RapidOCR(params={"Global.with_openvino": True})+# engine = engine = RapidOCR(+# params={"Global.with_onnx": True, "EngineConfig.onnxruntime.use_cuda": True}+# )+engine = RapidOCR(params={"Global.lang": "en"})vis = VisRes()image_path = "tests/test_files/ch_en_num.jpg"diff --git a/python/rapidocr/ch_ppocr_rec/main.py b/python/rapidocr/ch_ppocr_rec/main.pyindex c138217..eaef13e 100644--- a/python/rapidocr/ch_ppocr_rec/main.py+++ b/python/rapidocr/ch_ppocr_rec/main.py@@ -23,7 +23,7 @@ from rapidocr.inference_engine.base import get_enginefrom .utils import CTCLabelDecode, TextRecInput, TextRecOutput-DEFAULT_DICT_PATH = str(Path(__file__).parent.parent / "models" / "ppocr_keys_v1.txt")+DEFAULT_DICT_PATH = Path(__file__).parent.parent / "models" / "ppocr_keys_v1.txt"DEFAULT_DICT_URL = "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txt"diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yamlindex 7e82857..8eaef5e 100644--- a/python/rapidocr/config.yaml+++ b/python/rapidocr/config.yaml@@ -30,6 +30,7 @@ EngineConfig:paddlepaddle:cpu_math_library_num_threads: -1+ use_cuda: falsegpu_id: 0gpu_mem: 500@@ -38,6 +39,7 @@ EngineConfig:Det:model_path: models/ch_PP-OCRv4_det_infer.onnx+ model_dir: models/ch_PP-OCRv4_det_inferlimit_side_len: 736limit_type: min@@ -53,6 +55,7 @@ Det:Cls:model_path: models/ch_ppocr_mobile_v2.0_cls_infer.onnx+ model_dir: models/ch_ppocr_mobile_v2_cls_infercls_image_shape: [3, 48, 192]cls_batch_num: 6@@ -61,7 +64,8 @@ Cls:Rec:model_path: models/ch_PP-OCRv4_rec_infer.onnx- rec_keys_path: models/ppocr_keys_v1.txt+ model_dir: models/ch_PP-OCRv4_rec_infer+ rec_keys_path: models/ppocr_keys_v1.txtrec_img_shape: [3, 48, 320]rec_batch_num: 6diff --git a/python/rapidocr/inference_engine/MODEL_URL.yaml b/python/rapidocr/inference_engine/MODEL_URL.yamlindex e35ff56..505db0b 100644--- a/python/rapidocr/inference_engine/MODEL_URL.yaml+++ b/python/rapidocr/inference_engine/MODEL_URL.yaml@@ -1,10 +1,12 @@onnxruntime:PP-OCRv4:det:+ default: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_infer.onnxch_PP-OCRv4_det_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_infer.onnxen_PP-OCRv3_det_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/en_PP-OCRv3_det_infer.onnxMultilingual_PP-OCRv3_det_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/Multilingual_PP-OCRv3_det_infer.onnxrec:+ default: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer.onnxarabic_PP-OCRv4_rec_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/arabic_PP-OCRv4_rec_infer.onnxch_PP-OCRv4_rec_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer.onnxchinese_cht_PP-OCRv3_rec_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/chinese_cht_PP-OCRv3_rec_infer.onnx@@ -23,10 +25,14 @@ onnxruntime:openvino:PP-OCRv4:det:+ default: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_infer.onnxch_PP-OCRv4_det_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_infer.onnxen_PP-OCRv3_det_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/en_PP-OCRv3_det_infer.onnxMultilingual_PP-OCRv3_det_infer.onnx: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/Multilingual_PP-OCRv3_det_infer.onnxrec:+ default:+ model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer.onnx+ dict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txtarabic_PP-OCRv4_rec_infer:model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/arabic_PP-OCRv4_rec_infer.onnxdict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/arabic_PP-OCRv4_rec_infer/arabic_dict.txt@@ -69,10 +75,14 @@ openvino:paddlepaddle:PP-OCRv4:det:+ default: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/det/ch_PP-OCRv4_det_inferch_PP-OCRv4_det_infer: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/det/ch_PP-OCRv4_det_inferen_PP-OCRv3_det_infer: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/det/en_PP-OCRv3_det_inferMultilingual_PP-OCRv3_det_infer: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/det/Multilingual_PP-OCRv3_det_inferrec:+ default:+ model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer+ dict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txtarabic_PP-OCRv4_rec_infer:model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/arabic_PP-OCRv4_rec_inferdict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/arabic_PP-OCRv4_rec_infer/arabic_dict.txt@@ -115,10 +125,18 @@ paddlepaddle:torch:PP-OCRv4:det:+ default: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_det_infer.pthch_PP-OCRv4_det_infer.pth: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_det_infer.pthch_PP-OCRv4_det_server_infer.pth: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_det_server_infer.pthrec:- ch_PP-OCRv4_rec_infer.pth: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_rec_infer.pth- ch_PP-OCRv4_rec_server_infer.pth: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_rec_server_infer.pth+ default:+ model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_rec_infer.pth+ dict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txt+ ch_PP-OCRv4_rec_infer.pth:+ model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_rec_infer.pth+ dict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txt+ ch_PP-OCRv4_rec_server_infer.pth:+ model_dir: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_PP-OCRv4_rec_server_infer.pth+ dict_url: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txtcls:ch_ptocr_mobile_v2.0_cls_infer.pth: https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/master/torch/ch_ptocr_mobile_v2.0_cls_infer.pthdiff --git a/python/rapidocr/inference_engine/paddlepaddle.py b/python/rapidocr/inference_engine/paddlepaddle.pyindex 302f2f3..9012507 100644--- a/python/rapidocr/inference_engine/paddlepaddle.py+++ b/python/rapidocr/inference_engine/paddlepaddle.py@@ -11,34 +11,58 @@ import paddlefrom paddle import inferencefrom ..utils.logger import Logger+from .base import InferSession-class PaddleInferSession:+class PaddleInferSession(InferSession):def __init__(self, config, mode: Optional[str] = None) -> None:self.logger = Logger(logger_name=__name__).get_log()self.mode = mode- model_dir = Path(config.model_path)+ model_dir = Path(config.model_dir)pdmodel_path = model_dir / "inference.pdmodel"pdiparams_path = model_dir / "inference.pdiparams"- self._verify_model(pdmodel_path)- self._verify_model(pdiparams_path)+ if not self._verify_model(pdmodel_path):+ self.logger.warning(+ "%s model path is invalid, try to download the default model.",+ pdmodel_path,+ )+ default_model_url = self.get_model_url(+ config.engine_name, config.task_type, config.lang+ )+ default_model_url = f"{default_model_url}/{pdmodel_path.name}"+ model_path = model_dir / pdmodel_path.name+ self.download_file(default_model_url, model_path)++ if not self._verify_model(pdiparams_path):+ self.logger.warning(+ "%s model path is invalid, try to download the default model.",+ pdiparams_path,+ )+ default_model_url = self.get_model_url(+ config.engine_name, config.task_type, config.lang+ )+ default_model_url = f"{default_model_url}/{pdiparams_path.name}"+ model_path = model_dir / pdiparams_path.name+ self.download_file(default_model_url, model_path)infer_opts = inference.Config(str(pdmodel_path), str(pdiparams_path))- if config["use_cuda"]:+ if config.engine_cfg.use_cuda:gpu_id = self.get_infer_gpuid()if gpu_id is None:self.logger.warning("GPU is not found in current device by nvidia-smi. Please check your device or ignore it if run on jetson.")- infer_opts.enable_use_gpu(config["gpu_mem"], config["gpu_id"])+ infer_opts.enable_use_gpu(+ config.engine_cfg.gpu_mem, config.engine_cfg.gpu_id+ )else:infer_opts.disable_gpu()cpu_nums = os.cpu_count()- infer_num_threads = config.get("cpu_math_library_num_threads", -1)+ infer_num_threads = config.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)@@ -67,14 +91,6 @@ class PaddleInferSession:self.predictor.try_shrink_memory()return outputs[0]- @staticmethod- def _verify_model(model_path):- model_path = Path(model_path)- if not model_path.exists():- raise FileNotFoundError(f"{model_path} does not exists.")- if not model_path.is_file():- raise FileExistsError(f"{model_path} is not a file.")-def get_input_tensors(self):input_names = self.predictor.get_input_names()for name in input_names:@@ -112,6 +128,9 @@ class PaddleInferSession:gpu_id = env_cuda[0].strip().split("=")[1]return int(gpu_id[0])+ def have_key(self, key: str = "character") -> bool:+ return False+class PaddleInferError(Exception):passdiff --git a/python/rapidocr/main.py b/python/rapidocr/main.pyindex 884d35c..0dea8c0 100644--- a/python/rapidocr/main.py+++ b/python/rapidocr/main.py@@ -61,6 +61,7 @@ class RapidOCR:self.text_det = TextDetector(config.Det)self.use_cls = config.Global.use_cls+ config.Cls.lang = "ch"config.Cls.engine_name = engine_nameconfig.Cls.engine_cfg = config.EngineConfig[engine_name]config.Cls.task_type = "cls"@@ -80,6 +81,7 @@ class RapidOCR:self.cal_rec_boxes = CalRecBoxes()self.return_paddleocr_format = False+ self.return_word_box = Falsedef __call__(self,@@ -87,22 +89,19 @@ class RapidOCR:use_det: Optional[bool] = None,use_cls: Optional[bool] = None,use_rec: Optional[bool] = None,- **kwargs,+ return_word_box: bool = False,+ text_score: float = 0.5,+ box_thresh: float = 0.5,+ unclip_ratio: float = 1.6,) -> RapidOCROutput:use_det = self.use_det if use_det is None else use_detuse_cls = self.use_cls if use_cls is None else use_clsuse_rec = self.use_rec if use_rec is None else use_rec- return_word_box = False- if kwargs:- box_thresh = kwargs.get("box_thresh", 0.5)- unclip_ratio = kwargs.get("unclip_ratio", 1.6)- text_score = kwargs.get("text_score", 0.5)- return_word_box = kwargs.get("return_word_box", False)- self.text_det.postprocess_op.box_thresh = box_thresh- self.text_det.postprocess_op.unclip_ratio = unclip_ratio- self.text_score = text_scoreself.return_word_box = return_word_box+ self.text_score = text_score+ self.text_det.postprocess_op.box_thresh = box_thresh+ self.text_det.postprocess_op.unclip_ratio = unclip_ratioimg = self.load_img(img_content)@@ -126,11 +125,11 @@ class RapidOCR:img = cls_res.img_listif use_rec:- rec_input = TextRecInput(img=img, return_word_box=return_word_box)+ rec_input = TextRecInput(img=img, return_word_box=self.return_word_box)rec_res = self.text_rec(rec_input)if (- return_word_box+ self.return_word_boxand det_res.boxes is not Noneand all(v for v in rec_res.word_results)):diff --git a/python/rapidocr/utils/parse_parameters.py b/python/rapidocr/utils/parse_parameters.pyindex 289fb00..b946fed 100644--- a/python/rapidocr/utils/parse_parameters.py+++ b/python/rapidocr/utils/parse_parameters.py@@ -116,10 +116,12 @@ class ParseParams(OmegaConf):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]))+ def update_model_path(cls, cfg: DictConfig) -> DictConfig:+ keys = ["model_path", "model_dir"]+ for key in keys:+ 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@classmethoddiff --git a/python/tests/test_main.py b/python/tests/test_main.pyindex ff44997..1d59739 100644--- a/python/tests/test_main.py+++ b/python/tests/test_main.py@@ -1,7 +1,6 @@# -*- encoding: utf-8 -*-# @Author: SWHL# @Contact: [email protected]-import loggingimport sysfrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -41,16 +40,10 @@ def test_engine_openvino():assert result.txts[0] == "正品促销"-# def test_engine_paddle():-# engine = RapidOCR(-# params={-# "Global.with_paddle": True,-# "Det.model_path": "tests/test_files/ch_ppocr_server_v2.0_det_infer.onnx",-# "Rec.model_path": "tests/test_files/ch_ppocr_server_v2.0_rec_infer.onnx",-# }-# )-# result = engine(img_path)-# assert result.txts[0] == "正品促销"+def test_engine_paddle():+ engine = RapidOCR(params={"Global.with_paddle": True})+ result = engine(img_path)+ assert result.txts[0] == "正品促销"def test_long_img(engine):@@ -65,25 +58,6 @@ def test_long_img(engine):img_path.unlink()-def test_ort_cuda_warning(caplog):- engine = RapidOCR(- params={"Global.with_onnx": True, "EngineConfig.onnxruntime.use_cuda": True}- )- caplog.set_level(logging.WARNING)- assert caplog.records[0].levelname == "WARNING"- assert "CUDAExecutionProvider" in caplog.records[0].message---def test_ort_dml_warning(caplog):- engine = RapidOCR(- params={"Global.with_onnx": True, "EngineConfig.onnxruntime.use_dml": True}- )- caplog.set_level(logging.WARNING)-- assert caplog.records[0].levelname == "WARNING"- assert "DirectML" in caplog.records[0].message--def test_mode_one_img(engine):img_path = tests_dir / "issue_170.png"result = engine(img_path)@@ -103,7 +77,7 @@ def test_mode_one_img(engine):),],)-def test_transparent_img(img_name: str, gt: str):+def test_transparent_img(engine, img_name: str, gt: str):img_path = tests_dir / img_nameresult = engine(img_path)assert result.txts[0] == gt@@ -120,7 +94,7 @@ def test_transparent_img(img_name: str, gt: str):("test_without_det.jpg", 1, "在中国作家协会第三届儿童文学"),],)-def test_letterbox_like(img_name, gt_len, gt_first_len):+def test_letterbox_like(engine, img_name, gt_len, gt_first_len):img_path = tests_dir / img_nameresult = engine(img_path)@@ -128,32 +102,32 @@ def test_letterbox_like(img_name, gt_len, gt_first_len):assert result.txts[0].lower() == gt_first_len.lower()-def test_only_det():+def test_only_det(engine):result = engine(img_path, use_det=True, use_cls=False, use_rec=False)assert len(result) == 18-def test_only_cls():+def test_only_cls(engine):img_path = tests_dir / "text_cls.jpg"result = engine(img_path, use_det=False, use_cls=True, use_rec=False)assert len(result) == 1assert result.cls_res[0][0] == "0"-def test_only_rec():+def test_only_rec(engine):img_path = tests_dir / "text_rec.jpg"result = engine(img_path, use_det=False, use_cls=False, use_rec=True)assert len(result) == 1assert result.txts[0] == "韩国小馆"-def test_det_rec():+def test_det_rec(engine):result = engine(img_path, use_det=True, use_cls=False, use_rec=True)assert len(result) == 18assert result.txts[0] == "正品促销"-def test_cls_rec():+def test_cls_rec(engine):img_path = tests_dir / "text_cls.jpg"result = engine(img_path, use_det=False, use_cls=True, use_rec=True)@@ -162,7 +136,7 @@ def test_cls_rec():assert result.txts[0] == "韩国小馆"-def test_det_cls_rec():+def test_det_cls_rec(engine):img = cv2.imread(str(img_path))result = engine(img)@@ -171,7 +145,7 @@ def test_det_cls_rec():assert result.txts[0] == "正品促销"-def test_empty():+def test_empty(engine):img = Nonewith pytest.raises(LoadImageError) as exc_info:engine(img)@@ -179,39 +153,37 @@ def test_empty():assert exc_info.type is LoadImageError-def test_zeros():+def test_zeros(engine):img = np.zeros([640, 640, 3], np.uint8)result = engine(img)assert result.boxes is None-def test_input_str():+def test_input_str(engine):result = engine(str(img_path))assert len(result) == 18assert result.txts[0] == "正品促销"-def test_input_bytes():+def test_input_bytes(engine):with open(img_path, "rb") as f:result = engine(f.read())assert len(result) == 18assert result.txts[0] == "正品促销"-def test_input_path():+def test_input_path(engine):result = engine(img_path)assert len(result) == 18assert result.txts[0] == "正品促销"-def test_input_parameters():- img_path = tests_dir / "ch_en_num.jpg"- engine = RapidOCR(params={"Global.text_score": 1})- result = engine(img_path)+def test_input_parameters(engine):+ result = engine(img_path, text_score=1.0)assert result.boxes is None-def test_input_three_ndim_two_channel():+def test_input_three_ndim_two_channel(engine):img_npy = tests_dir / "two_dim_image.npy"image_array = np.load(str(img_npy))result = engine(image_array)@@ -221,7 +193,7 @@ def test_input_three_ndim_two_channel():assert result.txts[0] == "TREND PLOT REPORT"-def test_input_three_ndim_one_channel():+def test_input_three_ndim_one_channel(engine):img = cv2.imread(str(img_path))img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = img[:, :, 0]@@ -278,7 +250,7 @@ def test_input_three_ndim_one_channel():),],)-def test_word_ocr(img_name: str, words: List[str]):+def test_word_ocr(engine, img_name: str, words: List[str]):img_path = tests_dir / img_nameresult = engine(img_path, return_word_box=True)txts, _, _ = list(zip(*result.word_results))