predictor.py 5.7 KB

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