Skip to content

πŸ“„ Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

fix(cli): handle language option and empty visualization results

SWHL49b4fcb44c70
diff --git a/python/rapidocr/main.py b/python/rapidocr/main.py
index 9cfa273..3334dc7 100644
--- a/python/rapidocr/main.py
+++ b/python/rapidocr/main.py
@@ -352,6 +352,38 @@ class RapidOCRError(Exception):
pass
+def has_vis_result(result: RapidOCROutput) -> bool:
+ return all(
+ getattr(result, attr, None) is not None for attr in ("boxes", "txts", "scores")
+ )
+
+
+def flatten_word_results(word_results):
+ if not word_results:
+ return []
+
+ flattened = []
+ for word_line in word_results:
+ if not word_line:
+ continue
+
+ if (
+ len(word_line) == 3
+ and isinstance(word_line[0], str)
+ and not isinstance(word_line[2], (list, tuple, np.ndarray))
+ ):
+ continue
+
+ for word_item in word_line:
+ if (
+ isinstance(word_item, tuple)
+ and len(word_item) == 3
+ and word_item[2] is not None
+ ):
+ flattened.append(word_item)
+ return flattened
+
+
def parse_args(arg_list: Optional[List[str]] = None):
parser = argparse.ArgumentParser()
parser.add_argument("-img", "--img_path", type=str, default=None)
@@ -401,6 +433,7 @@ def main(arg_list: Optional[List[str]] = None):
params = {
"Global.text_score": args.text_score,
"Global.return_word_box": args.return_word_box,
+ "Rec.lang_type": LangRec(args.lang_type),
}
ocr_engine = RapidOCR(params=params)
@@ -419,6 +452,10 @@ def main(arg_list: Optional[List[str]] = None):
print(result)
if args.vis_res:
+ if not has_vis_result(result):
+ logger.warning("No OCR result to visualize.")
+ return
+
vis = VisRes(
text_score=args.text_score,
font_path=args.font_path,
@@ -427,7 +464,11 @@ def main(arg_list: Optional[List[str]] = None):
cur_dir = args.vis_save_dir
if args.return_word_box:
- words_results = sum(result.word_results, ())
+ words_results = flatten_word_results(result.word_results)
+ if not words_results:
+ logger.warning("No word result to visualize.")
+ return
+
words, words_scores, words_boxes = list(zip(*words_results))
vis_img = vis(args.img_path, words_boxes, words, words_scores)
save_path = cur_dir / f"{Path(args.img_path).stem}_vis_single.png"
diff --git a/python/rapidocr/utils/parse_parameters.py b/python/rapidocr/utils/parse_parameters.py
index 2b87cda..16d2eb8 100644
--- a/python/rapidocr/utils/parse_parameters.py
+++ b/python/rapidocr/utils/parse_parameters.py
@@ -34,6 +34,7 @@ class ParseParams(OmegaConf):
@classmethod
def update_batch(cls, cfg: DictConfig, params: Dict[str, Any]) -> DictConfig:
global_keys = list(OmegaConf.to_container(cfg.Global).keys())
+ section_keys = set(OmegaConf.to_container(cfg).keys())
enum_params = [
"engine_type",
"model_type",
@@ -42,10 +43,21 @@ class ParseParams(OmegaConf):
"task_type",
]
for k, v in params.items():
- if k.startswith("Global") and k.split(".")[1] not in global_keys:
+ key_parts = k.split(".")
+ if len(key_parts) < 2 or not all(key_parts):
raise ValueError(f"{k} is not a valid key.")
- if k.split(".")[1] in enum_params and not isinstance(v, Enum):
+ section = key_parts[0]
+ if section not in section_keys:
+ raise ValueError(f"{k} is not a valid key.")
+
+ if section == "Global" and (
+ len(key_parts) != 2 or key_parts[1] not in global_keys
+ ):
+ raise ValueError(f"{k} is not a valid key.")
+
+ param_name = key_parts[-1]
+ if param_name in enum_params and not isinstance(v, Enum):
raise TypeError(f"The value of {k} must be Enum Type.")
cls.update(cfg, k, v)
diff --git a/python/tests/test_cli.py b/python/tests/test_cli.py
index e5ee7ab..fa4e492 100644
--- a/python/tests/test_cli.py
+++ b/python/tests/test_cli.py
@@ -12,7 +12,8 @@ from pytest import mark
root_dir = Path(__file__).resolve().parent.parent
sys.path.append(str(root_dir))
-from rapidocr import RapidOCR
+from rapidocr import LangRec, RapidOCR
+from rapidocr.utils.output import RapidOCROutput
from rapidocr.main import main
tests_dir = root_dir / "tests" / "test_files"
@@ -91,3 +92,58 @@ def test_cli_lang_type():
main(shlex.split(cmd))
assert vis_path.exists()
vis_path.unlink()
+
+
+def test_cli_lang_type_passed_to_engine(monkeypatch):
+ captured_params = {}
+
+ class DummyRapidOCR:
+ def __init__(self, params=None):
+ captured_params.update(params or {})
+
+ def __call__(self, img_path):
+ return RapidOCROutput()
+
+ monkeypatch.setattr("rapidocr.main.RapidOCR", DummyRapidOCR)
+
+ main(shlex.split(f"--img_path {img_path} --lang_type japan"))
+
+ assert captured_params["Rec.lang_type"] == LangRec.JAPAN
+
+
+def test_cli_vis_empty_result(monkeypatch, tmp_path):
+ class DummyRapidOCR:
+ def __init__(self, params=None):
+ pass
+
+ def __call__(self, img_path):
+ return RapidOCROutput()
+
+ monkeypatch.setattr("rapidocr.main.RapidOCR", DummyRapidOCR)
+
+ main(
+ shlex.split(
+ f"--img_path {img_path} -vis --vis_save_dir {tmp_path}"
+ )
+ )
+
+ assert not (tmp_path / f"{img_path.stem}_vis.png").exists()
+
+
+def test_cli_word_vis_empty_result(monkeypatch, tmp_path):
+ class DummyRapidOCR:
+ def __init__(self, params=None):
+ pass
+
+ def __call__(self, img_path, return_word_box=False):
+ return RapidOCROutput()
+
+ monkeypatch.setattr("rapidocr.main.RapidOCR", DummyRapidOCR)
+
+ main(
+ shlex.split(
+ f"--img_path {img_path} -vis --vis_save_dir {tmp_path} -word"
+ )
+ )
+
+ assert not (tmp_path / f"{img_path.stem}_vis_single.png").exists()
diff --git a/python/tests/test_input.py b/python/tests/test_input.py
index d3d665d..0df7aa8 100644
--- a/python/tests/test_input.py
+++ b/python/tests/test_input.py
@@ -13,9 +13,11 @@ root_dir = Path(__file__).resolve().parent.parent
sys.path.append(str(root_dir))
from rapidocr import LoadImageError, RapidOCR
+from rapidocr.utils.parse_parameters import ParseParams
test_dir = root_dir / "tests" / "test_files"
img_path = test_dir / "ch_en_num.jpg"
+config_path = root_dir / "rapidocr" / "config.yaml"
@pytest.fixture()
@@ -109,6 +111,21 @@ def test_input_parameters(engine):
assert result.boxes is None
[email protected]("params", [{"text_score": 0.5}, {"Global": 0.5}, {"Unknown.key": 1}])
+def test_invalid_init_parameters(params):
+ cfg = ParseParams.load(config_path)
+
+ with pytest.raises(ValueError):
+ ParseParams.update_batch(cfg, params)
+
+
+def test_nested_init_parameters():
+ cfg = ParseParams.load(config_path)
+ ParseParams.update_batch(cfg, {"EngineConfig.onnxruntime.use_cuda": True})
+
+ assert cfg.EngineConfig.onnxruntime.use_cuda is True
+
+
def test_input_three_ndim_two_channel(engine):
img_npy = test_dir / "two_dim_image.npy"
image_array = np.load(str(img_npy))