predictor.py 6.5 KB

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