predictor.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from ....modules.text_recognition.model_list import MODELS
  15. from ....utils.fonts import (
  16. ARABIC_FONT,
  17. CYRILLIC_FONT,
  18. DEVANAGARI_FONT,
  19. KANNADA_FONT,
  20. KOREAN_FONT,
  21. LATIN_FONT,
  22. SIMFANG_FONT,
  23. TAMIL_FONT,
  24. TELUGU_FONT,
  25. )
  26. from ....utils.func_register import FuncRegister
  27. from ...common.batch_sampler import ImageBatchSampler
  28. from ...common.reader import ReadImage
  29. from ..base import BasePredictor
  30. from .processors import CTCLabelDecode, OCRReisizeNormImg, ToBatch
  31. from .result import TextRecResult
  32. class TextRecPredictor(BasePredictor):
  33. entities = MODELS
  34. _FUNC_MAP = {}
  35. register = FuncRegister(_FUNC_MAP)
  36. def __init__(self, *args, input_shape=None, **kwargs):
  37. super().__init__(*args, **kwargs)
  38. self.input_shape = input_shape
  39. self.vis_font = self.get_vis_font()
  40. self.pre_tfs, self.infer, self.post_op = self._build()
  41. def _build_batch_sampler(self):
  42. return ImageBatchSampler()
  43. def _get_result_class(self):
  44. return TextRecResult
  45. def _build(self):
  46. pre_tfs = {"Read": ReadImage(format="RGB")}
  47. for cfg in self.config["PreProcess"]["transform_ops"]:
  48. tf_key = list(cfg.keys())[0]
  49. assert tf_key in self._FUNC_MAP
  50. func = self._FUNC_MAP[tf_key]
  51. args = cfg.get(tf_key, {})
  52. name, op = func(self, **args) if args else func(self)
  53. if op:
  54. pre_tfs[name] = op
  55. pre_tfs["ToBatch"] = ToBatch()
  56. infer = self.create_static_infer()
  57. post_op = self.build_postprocess(**self.config["PostProcess"])
  58. return pre_tfs, infer, post_op
  59. def process(self, batch_data):
  60. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data.instances)
  61. batch_imgs = self.pre_tfs["ReisizeNorm"](imgs=batch_raw_imgs)
  62. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  63. batch_preds = self.infer(x=x)
  64. texts, scores = self.post_op(batch_preds)
  65. return {
  66. "input_path": batch_data.input_paths,
  67. "page_index": batch_data.page_indexes,
  68. "input_img": batch_raw_imgs,
  69. "rec_text": texts,
  70. "rec_score": scores,
  71. "vis_font": [self.vis_font] * len(batch_raw_imgs),
  72. }
  73. @register("DecodeImage")
  74. def build_readimg(self, channel_first, img_mode):
  75. assert channel_first == False
  76. return "Read", ReadImage(format=img_mode)
  77. @register("RecResizeImg")
  78. def build_resize(self, image_shape, **kwargs):
  79. return "ReisizeNorm", OCRReisizeNormImg(
  80. rec_image_shape=image_shape, input_shape=self.input_shape
  81. )
  82. def build_postprocess(self, **kwargs):
  83. if kwargs.get("name") == "CTCLabelDecode":
  84. return CTCLabelDecode(
  85. character_list=kwargs.get("character_dict"),
  86. )
  87. else:
  88. raise Exception()
  89. @register("MultiLabelEncode")
  90. def foo(self, *args, **kwargs):
  91. return None, None
  92. @register("KeepKeys")
  93. def foo(self, *args, **kwargs):
  94. return None, None
  95. def get_vis_font(self):
  96. if self.model_name.startswith(("PP-OCR", "en_PP-OCR")):
  97. return SIMFANG_FONT
  98. if self.model_name in (
  99. "latin_PP-OCRv3_mobile_rec",
  100. "latin_PP-OCRv5_mobile_rec",
  101. ):
  102. return LATIN_FONT
  103. if self.model_name in (
  104. "cyrillic_PP-OCRv3_mobile_rec",
  105. "eslav_PP-OCRv5_mobile_rec",
  106. ):
  107. return CYRILLIC_FONT
  108. if self.model_name in (
  109. "korean_PP-OCRv3_mobile_rec",
  110. "korean_PP-OCRv5_mobile_rec",
  111. ):
  112. return KOREAN_FONT
  113. if self.model_name == "arabic_PP-OCRv3_mobile_rec":
  114. return ARABIC_FONT
  115. if self.model_name == "ka_PP-OCRv3_mobile_rec":
  116. return KANNADA_FONT
  117. if self.model_name == "te_PP-OCRv3_mobile_rec":
  118. return TELUGU_FONT
  119. if self.model_name == "ta_PP-OCRv3_mobile_rec":
  120. return TAMIL_FONT
  121. if self.model_name == "devanagari_PP-OCRv3_mobile_rec":
  122. return DEVANAGARI_FONT