predictor.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. import numpy as np
  15. from ....modules.text_recognition.model_list import MODELS
  16. from ....utils.fonts import (
  17. ARABIC_FONT,
  18. CYRILLIC_FONT,
  19. DEVANAGARI_FONT,
  20. EL_FONT,
  21. KANNADA_FONT,
  22. KOREAN_FONT,
  23. LATIN_FONT,
  24. SIMFANG_FONT,
  25. TAMIL_FONT,
  26. TELUGU_FONT,
  27. TH_FONT,
  28. )
  29. from ....utils.func_register import FuncRegister
  30. from ...common.batch_sampler import ImageBatchSampler
  31. from ...common.reader import ReadImage
  32. from ..base import BasePredictor
  33. from .processors import CTCLabelDecode, OCRReisizeNormImg, ToBatch
  34. from .result import TextRecResult
  35. class TextRecPredictor(BasePredictor):
  36. entities = MODELS
  37. _FUNC_MAP = {}
  38. register = FuncRegister(_FUNC_MAP)
  39. def __init__(self, *args, input_shape=None, return_word_box=False, **kwargs):
  40. super().__init__(*args, **kwargs)
  41. self.input_shape = input_shape
  42. self.return_word_box = return_word_box
  43. self.vis_font = self.get_vis_font()
  44. self.pre_tfs, self.infer, self.post_op = self._build()
  45. def _build_batch_sampler(self):
  46. return ImageBatchSampler()
  47. def _get_result_class(self):
  48. return TextRecResult
  49. def _build(self):
  50. pre_tfs = {"Read": ReadImage(format="RGB")}
  51. for cfg in self.config["PreProcess"]["transform_ops"]:
  52. tf_key = list(cfg.keys())[0]
  53. assert tf_key in self._FUNC_MAP
  54. func = self._FUNC_MAP[tf_key]
  55. args = cfg.get(tf_key, {})
  56. name, op = func(self, **args) if args else func(self)
  57. if op:
  58. pre_tfs[name] = op
  59. pre_tfs["ToBatch"] = ToBatch()
  60. infer = self.create_static_infer()
  61. post_op = self.build_postprocess(**self.config["PostProcess"])
  62. return pre_tfs, infer, post_op
  63. def process(self, batch_data, return_word_box=False):
  64. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data.instances)
  65. width_list = []
  66. for img in batch_raw_imgs:
  67. width_list.append(img.shape[1] / float(img.shape[0]))
  68. indices = np.argsort(np.array(width_list))
  69. batch_imgs = self.pre_tfs["ReisizeNorm"](imgs=batch_raw_imgs)
  70. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  71. batch_preds = self.infer(x=x)
  72. batch_num = self.batch_sampler.batch_size
  73. img_num = len(batch_raw_imgs)
  74. rec_image_shape = next(
  75. op["RecResizeImg"]["image_shape"]
  76. for op in self.config["PreProcess"]["transform_ops"]
  77. if "RecResizeImg" in op
  78. )
  79. imgC, imgH, imgW = rec_image_shape[:3]
  80. max_wh_ratio = imgW / imgH
  81. end_img_no = min(img_num, batch_num)
  82. wh_ratio_list = []
  83. for ino in range(0, end_img_no):
  84. h, w = batch_raw_imgs[indices[ino]].shape[0:2]
  85. wh_ratio = w * 1.0 / h
  86. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  87. wh_ratio_list.append(wh_ratio)
  88. texts, scores = self.post_op(
  89. batch_preds,
  90. return_word_box=return_word_box or self.return_word_box,
  91. wh_ratio_list=wh_ratio_list,
  92. max_wh_ratio=max_wh_ratio,
  93. )
  94. return {
  95. "input_path": batch_data.input_paths,
  96. "page_index": batch_data.page_indexes,
  97. "input_img": batch_raw_imgs,
  98. "rec_text": texts,
  99. "rec_score": scores,
  100. "vis_font": [self.vis_font] * len(batch_raw_imgs),
  101. }
  102. @register("DecodeImage")
  103. def build_readimg(self, channel_first, img_mode):
  104. assert channel_first == False
  105. return "Read", ReadImage(format=img_mode)
  106. @register("RecResizeImg")
  107. def build_resize(self, image_shape, **kwargs):
  108. return "ReisizeNorm", OCRReisizeNormImg(
  109. rec_image_shape=image_shape, input_shape=self.input_shape
  110. )
  111. def build_postprocess(self, **kwargs):
  112. if kwargs.get("name") == "CTCLabelDecode":
  113. return CTCLabelDecode(
  114. character_list=kwargs.get("character_dict"),
  115. )
  116. else:
  117. raise Exception()
  118. @register("MultiLabelEncode")
  119. def foo(self, *args, **kwargs):
  120. return None, None
  121. @register("KeepKeys")
  122. def foo(self, *args, **kwargs):
  123. return None, None
  124. def get_vis_font(self):
  125. if self.model_name.startswith(("PP-OCR", "en_PP-OCR")):
  126. return SIMFANG_FONT
  127. if self.model_name in (
  128. "latin_PP-OCRv3_mobile_rec",
  129. "latin_PP-OCRv5_mobile_rec",
  130. ):
  131. return LATIN_FONT
  132. if self.model_name in (
  133. "cyrillic_PP-OCRv3_mobile_rec",
  134. "eslav_PP-OCRv5_mobile_rec",
  135. ):
  136. return CYRILLIC_FONT
  137. if self.model_name in (
  138. "korean_PP-OCRv3_mobile_rec",
  139. "korean_PP-OCRv5_mobile_rec",
  140. ):
  141. return KOREAN_FONT
  142. if self.model_name == "th_PP-OCRv5_mobile_rec":
  143. return TH_FONT
  144. if self.model_name == "el_PP-OCRv5_mobile_rec":
  145. return EL_FONT
  146. if self.model_name == "arabic_PP-OCRv3_mobile_rec":
  147. return ARABIC_FONT
  148. if self.model_name == "ka_PP-OCRv3_mobile_rec":
  149. return KANNADA_FONT
  150. if self.model_name == "te_PP-OCRv3_mobile_rec":
  151. return TELUGU_FONT
  152. if self.model_name == "ta_PP-OCRv3_mobile_rec":
  153. return TAMIL_FONT
  154. if self.model_name == "devanagari_PP-OCRv3_mobile_rec":
  155. return DEVANAGARI_FONT